2 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
8 * * Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * * Neither the name of Redis nor the names of its contributors may be used
14 * to endorse or promote products derived from this software without
15 * specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 * POSSIBILITY OF SUCH DAMAGE.
30 #define REDIS_VERSION "1.3.10"
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 "sha1.h" /* SHA1 is used for DEBUG DIGEST */
84 /* Static server configuration */
85 #define REDIS_SERVERPORT 6379 /* TCP port */
86 #define REDIS_MAXIDLETIME (60*5) /* default client timeout */
87 #define REDIS_IOBUF_LEN 1024
88 #define REDIS_LOADBUF_LEN 1024
89 #define REDIS_STATIC_ARGS 8
90 #define REDIS_DEFAULT_DBNUM 16
91 #define REDIS_CONFIGLINE_MAX 1024
92 #define REDIS_OBJFREELIST_MAX 1000000 /* Max number of objects to cache */
93 #define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
94 #define REDIS_EXPIRELOOKUPS_PER_CRON 10 /* lookup 10 expires per loop */
95 #define REDIS_MAX_WRITE_PER_EVENT (1024*64)
96 #define REDIS_REQUEST_MAX_SIZE (1024*1024*256) /* max bytes in inline command */
98 /* If more then REDIS_WRITEV_THRESHOLD write packets are pending use writev */
99 #define REDIS_WRITEV_THRESHOLD 3
100 /* Max number of iovecs used for each writev call */
101 #define REDIS_WRITEV_IOVEC_COUNT 256
103 /* Hash table parameters */
104 #define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
107 #define REDIS_CMD_BULK 1 /* Bulk write command */
108 #define REDIS_CMD_INLINE 2 /* Inline command */
109 /* REDIS_CMD_DENYOOM reserves a longer comment: all the commands marked with
110 this flags will return an error when the 'maxmemory' option is set in the
111 config file and the server is using more than maxmemory bytes of memory.
112 In short this commands are denied on low memory conditions. */
113 #define REDIS_CMD_DENYOOM 4
114 #define REDIS_CMD_FORCE_REPLICATION 8 /* Force replication even if dirty is 0 */
117 #define REDIS_STRING 0
123 /* Objects encoding. Some kind of objects like Strings and Hashes can be
124 * internally represented in multiple ways. The 'encoding' field of the object
125 * is set to one of this fields for this object. */
126 #define REDIS_ENCODING_RAW 0 /* Raw representation */
127 #define REDIS_ENCODING_INT 1 /* Encoded as integer */
128 #define REDIS_ENCODING_ZIPMAP 2 /* Encoded as zipmap */
129 #define REDIS_ENCODING_HT 3 /* Encoded as an hash table */
131 static char* strencoding
[] = {
132 "raw", "int", "zipmap", "hashtable"
135 /* Object types only used for dumping to disk */
136 #define REDIS_EXPIRETIME 253
137 #define REDIS_SELECTDB 254
138 #define REDIS_EOF 255
140 /* Defines related to the dump file format. To store 32 bits lengths for short
141 * keys requires a lot of space, so we check the most significant 2 bits of
142 * the first byte to interpreter the length:
144 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
145 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
146 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
147 * 11|000000 this means: specially encoded object will follow. The six bits
148 * number specify the kind of object that follows.
149 * See the REDIS_RDB_ENC_* defines.
151 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
152 * values, will fit inside. */
153 #define REDIS_RDB_6BITLEN 0
154 #define REDIS_RDB_14BITLEN 1
155 #define REDIS_RDB_32BITLEN 2
156 #define REDIS_RDB_ENCVAL 3
157 #define REDIS_RDB_LENERR UINT_MAX
159 /* When a length of a string object stored on disk has the first two bits
160 * set, the remaining two bits specify a special encoding for the object
161 * accordingly to the following defines: */
162 #define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
163 #define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
164 #define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
165 #define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
167 /* Virtual memory object->where field. */
168 #define REDIS_VM_MEMORY 0 /* The object is on memory */
169 #define REDIS_VM_SWAPPED 1 /* The object is on disk */
170 #define REDIS_VM_SWAPPING 2 /* Redis is swapping this object on disk */
171 #define REDIS_VM_LOADING 3 /* Redis is loading this object from disk */
173 /* Virtual memory static configuration stuff.
174 * Check vmFindContiguousPages() to know more about this magic numbers. */
175 #define REDIS_VM_MAX_NEAR_PAGES 65536
176 #define REDIS_VM_MAX_RANDOM_JUMP 4096
177 #define REDIS_VM_MAX_THREADS 32
178 #define REDIS_THREAD_STACK_SIZE (1024*1024*4)
179 /* The following is the *percentage* of completed I/O jobs to process when the
180 * handelr is called. While Virtual Memory I/O operations are performed by
181 * threads, this operations must be processed by the main thread when completed
182 * in order to take effect. */
183 #define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
186 #define REDIS_SLAVE 1 /* This client is a slave server */
187 #define REDIS_MASTER 2 /* This client is a master server */
188 #define REDIS_MONITOR 4 /* This client is a slave monitor, see MONITOR */
189 #define REDIS_MULTI 8 /* This client is in a MULTI context */
190 #define REDIS_BLOCKED 16 /* The client is waiting in a blocking operation */
191 #define REDIS_IO_WAIT 32 /* The client is waiting for Virtual Memory I/O */
193 /* Slave replication state - slave side */
194 #define REDIS_REPL_NONE 0 /* No active replication */
195 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
196 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
198 /* Slave replication state - from the point of view of master
199 * Note that in SEND_BULK and ONLINE state the slave receives new updates
200 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
201 * to start the next background saving in order to send updates to it. */
202 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
203 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
204 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
205 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
207 /* List related stuff */
211 /* Sort operations */
212 #define REDIS_SORT_GET 0
213 #define REDIS_SORT_ASC 1
214 #define REDIS_SORT_DESC 2
215 #define REDIS_SORTKEY_MAX 1024
218 #define REDIS_DEBUG 0
219 #define REDIS_VERBOSE 1
220 #define REDIS_NOTICE 2
221 #define REDIS_WARNING 3
223 /* Anti-warning macro... */
224 #define REDIS_NOTUSED(V) ((void) V)
226 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
227 #define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
229 /* Append only defines */
230 #define APPENDFSYNC_NO 0
231 #define APPENDFSYNC_ALWAYS 1
232 #define APPENDFSYNC_EVERYSEC 2
234 /* Hashes related defaults */
235 #define REDIS_HASH_MAX_ZIPMAP_ENTRIES 64
236 #define REDIS_HASH_MAX_ZIPMAP_VALUE 512
238 /* We can print the stacktrace, so our assert is defined this way: */
239 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),_exit(1)))
240 #define redisPanic(_e) _redisPanic(#_e,__FILE__,__LINE__),_exit(1)
241 static void _redisAssert(char *estr
, char *file
, int line
);
242 static void _redisPanic(char *msg
, char *file
, int line
);
244 /*================================= Data types ============================== */
246 /* A redis object, that is a type able to hold a string / list / set */
248 /* The VM object structure */
249 struct redisObjectVM
{
250 off_t page
; /* the page at witch the object is stored on disk */
251 off_t usedpages
; /* number of pages used on disk */
252 time_t atime
; /* Last access time */
255 /* The actual Redis Object */
256 typedef struct redisObject
{
259 unsigned char encoding
;
260 unsigned char storage
; /* If this object is a key, where is the value?
261 * REDIS_VM_MEMORY, REDIS_VM_SWAPPED, ... */
262 unsigned char vtype
; /* If this object is a key, and value is swapped out,
263 * this is the type of the swapped out object. */
265 /* VM fields, this are only allocated if VM is active, otherwise the
266 * object allocation function will just allocate
267 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
268 * Redis without VM active will not have any overhead. */
269 struct redisObjectVM vm
;
272 /* Macro used to initalize a Redis object allocated on the stack.
273 * Note that this macro is taken near the structure definition to make sure
274 * we'll update it when the structure is changed, to avoid bugs like
275 * bug #85 introduced exactly in this way. */
276 #define initStaticStringObject(_var,_ptr) do { \
278 _var.type = REDIS_STRING; \
279 _var.encoding = REDIS_ENCODING_RAW; \
281 if (server.vm_enabled) _var.storage = REDIS_VM_MEMORY; \
284 typedef struct redisDb
{
285 dict
*dict
; /* The keyspace for this DB */
286 dict
*expires
; /* Timeout of keys with a timeout set */
287 dict
*blockingkeys
; /* Keys with clients waiting for data (BLPOP) */
288 dict
*io_keys
; /* Keys with clients waiting for VM I/O */
292 /* Client MULTI/EXEC state */
293 typedef struct multiCmd
{
296 struct redisCommand
*cmd
;
299 typedef struct multiState
{
300 multiCmd
*commands
; /* Array of MULTI commands */
301 int count
; /* Total number of MULTI commands */
304 /* With multiplexing we need to take per-clinet state.
305 * Clients are taken in a liked list. */
306 typedef struct redisClient
{
311 robj
**argv
, **mbargv
;
313 int bulklen
; /* bulk read len. -1 if not in bulk read mode */
314 int multibulk
; /* multi bulk command format active */
317 time_t lastinteraction
; /* time of the last interaction, used for timeout */
318 int flags
; /* REDIS_SLAVE | REDIS_MONITOR | REDIS_MULTI ... */
319 int slaveseldb
; /* slave selected db, if this client is a slave */
320 int authenticated
; /* when requirepass is non-NULL */
321 int replstate
; /* replication state if this is a slave */
322 int repldbfd
; /* replication DB file descriptor */
323 long repldboff
; /* replication DB file offset */
324 off_t repldbsize
; /* replication DB file size */
325 multiState mstate
; /* MULTI/EXEC state */
326 robj
**blockingkeys
; /* The key we are waiting to terminate a blocking
327 * operation such as BLPOP. Otherwise NULL. */
328 int blockingkeysnum
; /* Number of blocking keys */
329 time_t blockingto
; /* Blocking operation timeout. If UNIX current time
330 * is >= blockingto then the operation timed out. */
331 list
*io_keys
; /* Keys this client is waiting to be loaded from the
332 * swap file in order to continue. */
333 dict
*pubsub_channels
; /* channels a client is interested in (SUBSCRIBE) */
334 list
*pubsub_patterns
; /* patterns a client is interested in (SUBSCRIBE) */
342 /* Global server state structure */
347 long long dirty
; /* changes to DB from the last save */
349 list
*slaves
, *monitors
;
350 char neterr
[ANET_ERR_LEN
];
352 int cronloops
; /* number of times the cron function run */
353 list
*objfreelist
; /* A list of freed objects to avoid malloc() */
354 time_t lastsave
; /* Unix time of last save succeeede */
355 /* Fields used only for stats */
356 time_t stat_starttime
; /* server start time */
357 long long stat_numcommands
; /* number of processed commands */
358 long long stat_numconnections
; /* number of connections received */
359 long long stat_expiredkeys
; /* number of expired keys */
372 pid_t bgsavechildpid
;
373 pid_t bgrewritechildpid
;
374 sds bgrewritebuf
; /* buffer taken by parent during oppend only rewrite */
375 sds aofbuf
; /* AOF buffer, written before entering the event loop */
376 struct saveparam
*saveparams
;
381 char *appendfilename
;
385 /* Replication related */
390 redisClient
*master
; /* client that is master for this slave */
392 unsigned int maxclients
;
393 unsigned long long maxmemory
;
394 unsigned int blpop_blocked_clients
;
395 unsigned int vm_blocked_clients
;
396 /* Sort parameters - qsort_r() is only available under BSD so we
397 * have to take this state global, in order to pass it to sortCompare() */
401 /* Virtual memory configuration */
406 unsigned long long vm_max_memory
;
408 size_t hash_max_zipmap_entries
;
409 size_t hash_max_zipmap_value
;
410 /* Virtual memory state */
413 off_t vm_next_page
; /* Next probably empty page */
414 off_t vm_near_pages
; /* Number of pages allocated sequentially */
415 unsigned char *vm_bitmap
; /* Bitmap of free/used pages */
416 time_t unixtime
; /* Unix time sampled every second. */
417 /* Virtual memory I/O threads stuff */
418 /* An I/O thread process an element taken from the io_jobs queue and
419 * put the result of the operation in the io_done list. While the
420 * job is being processed, it's put on io_processing queue. */
421 list
*io_newjobs
; /* List of VM I/O jobs yet to be processed */
422 list
*io_processing
; /* List of VM I/O jobs being processed */
423 list
*io_processed
; /* List of VM I/O jobs already processed */
424 list
*io_ready_clients
; /* Clients ready to be unblocked. All keys loaded */
425 pthread_mutex_t io_mutex
; /* lock to access io_jobs/io_done/io_thread_job */
426 pthread_mutex_t obj_freelist_mutex
; /* safe redis objects creation/free */
427 pthread_mutex_t io_swapfile_mutex
; /* So we can lseek + write */
428 pthread_attr_t io_threads_attr
; /* attributes for threads creation */
429 int io_active_threads
; /* Number of running I/O threads */
430 int vm_max_threads
; /* Max number of I/O threads running at the same time */
431 /* Our main thread is blocked on the event loop, locking for sockets ready
432 * to be read or written, so when a threaded I/O operation is ready to be
433 * processed by the main thread, the I/O thread will use a unix pipe to
434 * awake the main thread. The followings are the two pipe FDs. */
435 int io_ready_pipe_read
;
436 int io_ready_pipe_write
;
437 /* Virtual memory stats */
438 unsigned long long vm_stats_used_pages
;
439 unsigned long long vm_stats_swapped_objects
;
440 unsigned long long vm_stats_swapouts
;
441 unsigned long long vm_stats_swapins
;
443 dict
*pubsub_channels
; /* Map channels to list of subscribed clients */
444 list
*pubsub_patterns
; /* A list of pubsub_patterns */
449 typedef struct pubsubPattern
{
454 typedef void redisCommandProc(redisClient
*c
);
455 typedef void redisVmPreloadProc(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
);
456 struct redisCommand
{
458 redisCommandProc
*proc
;
461 /* Use a function to determine which keys need to be loaded
462 * in the background prior to executing this command. Takes precedence
463 * over vm_firstkey and others, ignored when NULL */
464 redisVmPreloadProc
*vm_preload_proc
;
465 /* What keys should be loaded in background when calling this command? */
466 int vm_firstkey
; /* The first argument that's a key (0 = no keys) */
467 int vm_lastkey
; /* THe last argument that's a key */
468 int vm_keystep
; /* The step between first and last key */
471 struct redisFunctionSym
{
473 unsigned long pointer
;
476 typedef struct _redisSortObject
{
484 typedef struct _redisSortOperation
{
487 } redisSortOperation
;
489 /* ZSETs use a specialized version of Skiplists */
491 typedef struct zskiplistNode
{
492 struct zskiplistNode
**forward
;
493 struct zskiplistNode
*backward
;
499 typedef struct zskiplist
{
500 struct zskiplistNode
*header
, *tail
;
501 unsigned long length
;
505 typedef struct zset
{
510 /* Our shared "common" objects */
512 #define REDIS_SHARED_INTEGERS 10000
513 struct sharedObjectsStruct
{
514 robj
*crlf
, *ok
, *err
, *emptybulk
, *czero
, *cone
, *pong
, *space
,
515 *colon
, *nullbulk
, *nullmultibulk
, *queued
,
516 *emptymultibulk
, *wrongtypeerr
, *nokeyerr
, *syntaxerr
, *sameobjecterr
,
517 *outofrangeerr
, *plus
,
518 *select0
, *select1
, *select2
, *select3
, *select4
,
519 *select5
, *select6
, *select7
, *select8
, *select9
,
520 *messagebulk
, *pmessagebulk
, *subscribebulk
, *unsubscribebulk
, *mbulk3
,
521 *mbulk4
, *psubscribebulk
, *punsubscribebulk
,
522 *integers
[REDIS_SHARED_INTEGERS
];
525 /* Global vars that are actally used as constants. The following double
526 * values are used for double on-disk serialization, and are initialized
527 * at runtime to avoid strange compiler optimizations. */
529 static double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
;
531 /* VM threaded I/O request message */
532 #define REDIS_IOJOB_LOAD 0 /* Load from disk to memory */
533 #define REDIS_IOJOB_PREPARE_SWAP 1 /* Compute needed pages */
534 #define REDIS_IOJOB_DO_SWAP 2 /* Swap from memory to disk */
535 typedef struct iojob
{
536 int type
; /* Request type, REDIS_IOJOB_* */
537 redisDb
*db
;/* Redis database */
538 robj
*key
; /* This I/O request is about swapping this key */
539 robj
*val
; /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
540 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
541 off_t page
; /* Swap page where to read/write the object */
542 off_t pages
; /* Swap pages needed to save object. PREPARE_SWAP return val */
543 int canceled
; /* True if this command was canceled by blocking side of VM */
544 pthread_t thread
; /* ID of the thread processing this entry */
547 /*================================ Prototypes =============================== */
549 static void freeStringObject(robj
*o
);
550 static void freeListObject(robj
*o
);
551 static void freeSetObject(robj
*o
);
552 static void decrRefCount(void *o
);
553 static robj
*createObject(int type
, void *ptr
);
554 static void freeClient(redisClient
*c
);
555 static int rdbLoad(char *filename
);
556 static void addReply(redisClient
*c
, robj
*obj
);
557 static void addReplySds(redisClient
*c
, sds s
);
558 static void incrRefCount(robj
*o
);
559 static int rdbSaveBackground(char *filename
);
560 static robj
*createStringObject(char *ptr
, size_t len
);
561 static robj
*dupStringObject(robj
*o
);
562 static void replicationFeedSlaves(list
*slaves
, int dictid
, robj
**argv
, int argc
);
563 static void replicationFeedMonitors(list
*monitors
, int dictid
, robj
**argv
, int argc
);
564 static void flushAppendOnlyFile(void);
565 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
566 static int syncWithMaster(void);
567 static robj
*tryObjectEncoding(robj
*o
);
568 static robj
*getDecodedObject(robj
*o
);
569 static int removeExpire(redisDb
*db
, robj
*key
);
570 static int expireIfNeeded(redisDb
*db
, robj
*key
);
571 static int deleteIfVolatile(redisDb
*db
, robj
*key
);
572 static int deleteIfSwapped(redisDb
*db
, robj
*key
);
573 static int deleteKey(redisDb
*db
, robj
*key
);
574 static time_t getExpire(redisDb
*db
, robj
*key
);
575 static int setExpire(redisDb
*db
, robj
*key
, time_t when
);
576 static void updateSlavesWaitingBgsave(int bgsaveerr
);
577 static void freeMemoryIfNeeded(void);
578 static int processCommand(redisClient
*c
);
579 static void setupSigSegvAction(void);
580 static void rdbRemoveTempFile(pid_t childpid
);
581 static void aofRemoveTempFile(pid_t childpid
);
582 static size_t stringObjectLen(robj
*o
);
583 static void processInputBuffer(redisClient
*c
);
584 static zskiplist
*zslCreate(void);
585 static void zslFree(zskiplist
*zsl
);
586 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
);
587 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
588 static void initClientMultiState(redisClient
*c
);
589 static void freeClientMultiState(redisClient
*c
);
590 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
);
591 static void unblockClientWaitingData(redisClient
*c
);
592 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
);
593 static void vmInit(void);
594 static void vmMarkPagesFree(off_t page
, off_t count
);
595 static robj
*vmLoadObject(robj
*key
);
596 static robj
*vmPreviewObject(robj
*key
);
597 static int vmSwapOneObjectBlocking(void);
598 static int vmSwapOneObjectThreaded(void);
599 static int vmCanSwapOut(void);
600 static int tryFreeOneObjectFromFreelist(void);
601 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
602 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
603 static void vmCancelThreadedIOJob(robj
*o
);
604 static void lockThreadedIO(void);
605 static void unlockThreadedIO(void);
606 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
);
607 static void freeIOJob(iojob
*j
);
608 static void queueIOJob(iojob
*j
);
609 static int vmWriteObjectOnSwap(robj
*o
, off_t page
);
610 static robj
*vmReadObjectFromSwap(off_t page
, int type
);
611 static void waitEmptyIOJobsQueue(void);
612 static void vmReopenSwapFile(void);
613 static int vmFreePage(off_t page
);
614 static void zunionInterBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
);
615 static void execBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
);
616 static int blockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
);
617 static int dontWaitForSwappedKey(redisClient
*c
, robj
*key
);
618 static void handleClientsBlockedOnSwappedKey(redisDb
*db
, robj
*key
);
619 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
620 static struct redisCommand
*lookupCommand(char *name
);
621 static void call(redisClient
*c
, struct redisCommand
*cmd
);
622 static void resetClient(redisClient
*c
);
623 static void convertToRealHash(robj
*o
);
624 static int pubsubUnsubscribeAllChannels(redisClient
*c
, int notify
);
625 static int pubsubUnsubscribeAllPatterns(redisClient
*c
, int notify
);
626 static void freePubsubPattern(void *p
);
627 static int listMatchPubsubPattern(void *a
, void *b
);
628 static int compareStringObjects(robj
*a
, robj
*b
);
629 static int equalStringObjects(robj
*a
, robj
*b
);
631 static int rewriteAppendOnlyFileBackground(void);
632 static int vmSwapObjectBlocking(robj
*key
, robj
*val
);
634 static void authCommand(redisClient
*c
);
635 static void pingCommand(redisClient
*c
);
636 static void echoCommand(redisClient
*c
);
637 static void setCommand(redisClient
*c
);
638 static void setnxCommand(redisClient
*c
);
639 static void setexCommand(redisClient
*c
);
640 static void getCommand(redisClient
*c
);
641 static void delCommand(redisClient
*c
);
642 static void existsCommand(redisClient
*c
);
643 static void incrCommand(redisClient
*c
);
644 static void decrCommand(redisClient
*c
);
645 static void incrbyCommand(redisClient
*c
);
646 static void decrbyCommand(redisClient
*c
);
647 static void selectCommand(redisClient
*c
);
648 static void randomkeyCommand(redisClient
*c
);
649 static void keysCommand(redisClient
*c
);
650 static void dbsizeCommand(redisClient
*c
);
651 static void lastsaveCommand(redisClient
*c
);
652 static void saveCommand(redisClient
*c
);
653 static void bgsaveCommand(redisClient
*c
);
654 static void bgrewriteaofCommand(redisClient
*c
);
655 static void shutdownCommand(redisClient
*c
);
656 static void moveCommand(redisClient
*c
);
657 static void renameCommand(redisClient
*c
);
658 static void renamenxCommand(redisClient
*c
);
659 static void lpushCommand(redisClient
*c
);
660 static void rpushCommand(redisClient
*c
);
661 static void lpopCommand(redisClient
*c
);
662 static void rpopCommand(redisClient
*c
);
663 static void llenCommand(redisClient
*c
);
664 static void lindexCommand(redisClient
*c
);
665 static void lrangeCommand(redisClient
*c
);
666 static void ltrimCommand(redisClient
*c
);
667 static void typeCommand(redisClient
*c
);
668 static void lsetCommand(redisClient
*c
);
669 static void saddCommand(redisClient
*c
);
670 static void sremCommand(redisClient
*c
);
671 static void smoveCommand(redisClient
*c
);
672 static void sismemberCommand(redisClient
*c
);
673 static void scardCommand(redisClient
*c
);
674 static void spopCommand(redisClient
*c
);
675 static void srandmemberCommand(redisClient
*c
);
676 static void sinterCommand(redisClient
*c
);
677 static void sinterstoreCommand(redisClient
*c
);
678 static void sunionCommand(redisClient
*c
);
679 static void sunionstoreCommand(redisClient
*c
);
680 static void sdiffCommand(redisClient
*c
);
681 static void sdiffstoreCommand(redisClient
*c
);
682 static void syncCommand(redisClient
*c
);
683 static void flushdbCommand(redisClient
*c
);
684 static void flushallCommand(redisClient
*c
);
685 static void sortCommand(redisClient
*c
);
686 static void lremCommand(redisClient
*c
);
687 static void rpoplpushcommand(redisClient
*c
);
688 static void infoCommand(redisClient
*c
);
689 static void mgetCommand(redisClient
*c
);
690 static void monitorCommand(redisClient
*c
);
691 static void expireCommand(redisClient
*c
);
692 static void expireatCommand(redisClient
*c
);
693 static void getsetCommand(redisClient
*c
);
694 static void ttlCommand(redisClient
*c
);
695 static void slaveofCommand(redisClient
*c
);
696 static void debugCommand(redisClient
*c
);
697 static void msetCommand(redisClient
*c
);
698 static void msetnxCommand(redisClient
*c
);
699 static void zaddCommand(redisClient
*c
);
700 static void zincrbyCommand(redisClient
*c
);
701 static void zrangeCommand(redisClient
*c
);
702 static void zrangebyscoreCommand(redisClient
*c
);
703 static void zcountCommand(redisClient
*c
);
704 static void zrevrangeCommand(redisClient
*c
);
705 static void zcardCommand(redisClient
*c
);
706 static void zremCommand(redisClient
*c
);
707 static void zscoreCommand(redisClient
*c
);
708 static void zremrangebyscoreCommand(redisClient
*c
);
709 static void multiCommand(redisClient
*c
);
710 static void execCommand(redisClient
*c
);
711 static void discardCommand(redisClient
*c
);
712 static void blpopCommand(redisClient
*c
);
713 static void brpopCommand(redisClient
*c
);
714 static void appendCommand(redisClient
*c
);
715 static void substrCommand(redisClient
*c
);
716 static void zrankCommand(redisClient
*c
);
717 static void zrevrankCommand(redisClient
*c
);
718 static void hsetCommand(redisClient
*c
);
719 static void hsetnxCommand(redisClient
*c
);
720 static void hgetCommand(redisClient
*c
);
721 static void hmsetCommand(redisClient
*c
);
722 static void hmgetCommand(redisClient
*c
);
723 static void hdelCommand(redisClient
*c
);
724 static void hlenCommand(redisClient
*c
);
725 static void zremrangebyrankCommand(redisClient
*c
);
726 static void zunionstoreCommand(redisClient
*c
);
727 static void zinterstoreCommand(redisClient
*c
);
728 static void hkeysCommand(redisClient
*c
);
729 static void hvalsCommand(redisClient
*c
);
730 static void hgetallCommand(redisClient
*c
);
731 static void hexistsCommand(redisClient
*c
);
732 static void configCommand(redisClient
*c
);
733 static void hincrbyCommand(redisClient
*c
);
734 static void subscribeCommand(redisClient
*c
);
735 static void unsubscribeCommand(redisClient
*c
);
736 static void psubscribeCommand(redisClient
*c
);
737 static void punsubscribeCommand(redisClient
*c
);
738 static void publishCommand(redisClient
*c
);
740 /*================================= Globals ================================= */
743 static struct redisServer server
; /* server global state */
744 static struct redisCommand cmdTable
[] = {
745 {"get",getCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
746 {"set",setCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,0,0,0},
747 {"setnx",setnxCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,0,0,0},
748 {"setex",setexCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,0,0,0},
749 {"append",appendCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
750 {"substr",substrCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
751 {"del",delCommand
,-2,REDIS_CMD_INLINE
,NULL
,0,0,0},
752 {"exists",existsCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
753 {"incr",incrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
754 {"decr",decrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
755 {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
,NULL
,1,-1,1},
756 {"rpush",rpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
757 {"lpush",lpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
758 {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
759 {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
760 {"brpop",brpopCommand
,-3,REDIS_CMD_INLINE
,NULL
,1,1,1},
761 {"blpop",blpopCommand
,-3,REDIS_CMD_INLINE
,NULL
,1,1,1},
762 {"llen",llenCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
763 {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
,NULL
,1,1,1},
764 {"lset",lsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
765 {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
766 {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
767 {"lrem",lremCommand
,4,REDIS_CMD_BULK
,NULL
,1,1,1},
768 {"rpoplpush",rpoplpushcommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,2,1},
769 {"sadd",saddCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
770 {"srem",sremCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
771 {"smove",smoveCommand
,4,REDIS_CMD_BULK
,NULL
,1,2,1},
772 {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
773 {"scard",scardCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
774 {"spop",spopCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
775 {"srandmember",srandmemberCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
776 {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
777 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
778 {"sunion",sunionCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
779 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
780 {"sdiff",sdiffCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
781 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
782 {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
783 {"zadd",zaddCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
784 {"zincrby",zincrbyCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
785 {"zrem",zremCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
786 {"zremrangebyscore",zremrangebyscoreCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
787 {"zremrangebyrank",zremrangebyrankCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
788 {"zunionstore",zunionstoreCommand
,-4,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,zunionInterBlockClientOnSwappedKeys
,0,0,0},
789 {"zinterstore",zinterstoreCommand
,-4,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,zunionInterBlockClientOnSwappedKeys
,0,0,0},
790 {"zrange",zrangeCommand
,-4,REDIS_CMD_INLINE
,NULL
,1,1,1},
791 {"zrangebyscore",zrangebyscoreCommand
,-4,REDIS_CMD_INLINE
,NULL
,1,1,1},
792 {"zcount",zcountCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
793 {"zrevrange",zrevrangeCommand
,-4,REDIS_CMD_INLINE
,NULL
,1,1,1},
794 {"zcard",zcardCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
795 {"zscore",zscoreCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
796 {"zrank",zrankCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
797 {"zrevrank",zrevrankCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
798 {"hset",hsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
799 {"hsetnx",hsetnxCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
800 {"hget",hgetCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
801 {"hmset",hmsetCommand
,-4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
802 {"hmget",hmgetCommand
,-3,REDIS_CMD_BULK
,NULL
,1,1,1},
803 {"hincrby",hincrbyCommand
,4,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
804 {"hdel",hdelCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
805 {"hlen",hlenCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
806 {"hkeys",hkeysCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
807 {"hvals",hvalsCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
808 {"hgetall",hgetallCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
809 {"hexists",hexistsCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
810 {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
811 {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
812 {"getset",getsetCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
813 {"mset",msetCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,-1,2},
814 {"msetnx",msetnxCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,-1,2},
815 {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
816 {"select",selectCommand
,2,REDIS_CMD_INLINE
,NULL
,0,0,0},
817 {"move",moveCommand
,3,REDIS_CMD_INLINE
,NULL
,1,1,1},
818 {"rename",renameCommand
,3,REDIS_CMD_INLINE
,NULL
,1,1,1},
819 {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
,NULL
,1,1,1},
820 {"expire",expireCommand
,3,REDIS_CMD_INLINE
,NULL
,0,0,0},
821 {"expireat",expireatCommand
,3,REDIS_CMD_INLINE
,NULL
,0,0,0},
822 {"keys",keysCommand
,2,REDIS_CMD_INLINE
,NULL
,0,0,0},
823 {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
824 {"auth",authCommand
,2,REDIS_CMD_INLINE
,NULL
,0,0,0},
825 {"ping",pingCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
826 {"echo",echoCommand
,2,REDIS_CMD_BULK
,NULL
,0,0,0},
827 {"save",saveCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
828 {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
829 {"bgrewriteaof",bgrewriteaofCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
830 {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
831 {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
832 {"type",typeCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
833 {"multi",multiCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
834 {"exec",execCommand
,1,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,execBlockClientOnSwappedKeys
,0,0,0},
835 {"discard",discardCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
836 {"sync",syncCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
837 {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
838 {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
839 {"sort",sortCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
840 {"info",infoCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
841 {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
842 {"ttl",ttlCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
843 {"slaveof",slaveofCommand
,3,REDIS_CMD_INLINE
,NULL
,0,0,0},
844 {"debug",debugCommand
,-2,REDIS_CMD_INLINE
,NULL
,0,0,0},
845 {"config",configCommand
,-2,REDIS_CMD_BULK
,NULL
,0,0,0},
846 {"subscribe",subscribeCommand
,-2,REDIS_CMD_INLINE
,NULL
,0,0,0},
847 {"unsubscribe",unsubscribeCommand
,-1,REDIS_CMD_INLINE
,NULL
,0,0,0},
848 {"psubscribe",psubscribeCommand
,-2,REDIS_CMD_INLINE
,NULL
,0,0,0},
849 {"punsubscribe",punsubscribeCommand
,-1,REDIS_CMD_INLINE
,NULL
,0,0,0},
850 {"publish",publishCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_FORCE_REPLICATION
,NULL
,0,0,0},
851 {NULL
,NULL
,0,0,NULL
,0,0,0}
854 /*============================ Utility functions ============================ */
856 /* Glob-style pattern matching. */
857 static int stringmatchlen(const char *pattern
, int patternLen
,
858 const char *string
, int stringLen
, int nocase
)
863 while (pattern
[1] == '*') {
868 return 1; /* match */
870 if (stringmatchlen(pattern
+1, patternLen
-1,
871 string
, stringLen
, nocase
))
872 return 1; /* match */
876 return 0; /* no match */
880 return 0; /* no match */
890 not = pattern
[0] == '^';
897 if (pattern
[0] == '\\') {
900 if (pattern
[0] == string
[0])
902 } else if (pattern
[0] == ']') {
904 } else if (patternLen
== 0) {
908 } else if (pattern
[1] == '-' && patternLen
>= 3) {
909 int start
= pattern
[0];
910 int end
= pattern
[2];
918 start
= tolower(start
);
924 if (c
>= start
&& c
<= end
)
928 if (pattern
[0] == string
[0])
931 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
941 return 0; /* no match */
947 if (patternLen
>= 2) {
954 if (pattern
[0] != string
[0])
955 return 0; /* no match */
957 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
958 return 0; /* no match */
966 if (stringLen
== 0) {
967 while(*pattern
== '*') {
974 if (patternLen
== 0 && stringLen
== 0)
979 static int stringmatch(const char *pattern
, const char *string
, int nocase
) {
980 return stringmatchlen(pattern
,strlen(pattern
),string
,strlen(string
),nocase
);
983 /* Convert a string representing an amount of memory into the number of
984 * bytes, so for instance memtoll("1Gi") will return 1073741824 that is
987 * On parsing error, if *err is not NULL, it's set to 1, otherwise it's
989 static long long memtoll(const char *p
, int *err
) {
992 long mul
; /* unit multiplier */
997 /* Search the first non digit character. */
1000 while(*u
&& isdigit(*u
)) u
++;
1001 if (*u
== '\0' || !strcasecmp(u
,"b")) {
1003 } else if (!strcasecmp(u
,"k")) {
1005 } else if (!strcasecmp(u
,"kb")) {
1007 } else if (!strcasecmp(u
,"m")) {
1009 } else if (!strcasecmp(u
,"mb")) {
1011 } else if (!strcasecmp(u
,"g")) {
1012 mul
= 1000L*1000*1000;
1013 } else if (!strcasecmp(u
,"gb")) {
1014 mul
= 1024L*1024*1024;
1020 if (digits
>= sizeof(buf
)) {
1024 memcpy(buf
,p
,digits
);
1026 val
= strtoll(buf
,NULL
,10);
1030 /* Convert a long long into a string. Returns the number of
1031 * characters needed to represent the number, that can be shorter if passed
1032 * buffer length is not enough to store the whole number. */
1033 static int ll2string(char *s
, size_t len
, long long value
) {
1035 unsigned long long v
;
1038 if (len
== 0) return 0;
1039 v
= (value
< 0) ? -value
: value
;
1040 p
= buf
+31; /* point to the last character */
1045 if (value
< 0) *p
-- = '-';
1048 if (l
+1 > len
) l
= len
-1; /* Make sure it fits, including the nul term */
1054 static void redisLog(int level
, const char *fmt
, ...) {
1058 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
1062 if (level
>= server
.verbosity
) {
1068 strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
));
1069 fprintf(fp
,"[%d] %s %c ",(int)getpid(),buf
,c
[level
]);
1070 vfprintf(fp
, fmt
, ap
);
1076 if (server
.logfile
) fclose(fp
);
1079 /*====================== Hash table type implementation ==================== */
1081 /* This is an hash table type that uses the SDS dynamic strings libary as
1082 * keys and radis objects as values (objects can hold SDS strings,
1085 static void dictVanillaFree(void *privdata
, void *val
)
1087 DICT_NOTUSED(privdata
);
1091 static void dictListDestructor(void *privdata
, void *val
)
1093 DICT_NOTUSED(privdata
);
1094 listRelease((list
*)val
);
1097 static int sdsDictKeyCompare(void *privdata
, const void *key1
,
1101 DICT_NOTUSED(privdata
);
1103 l1
= sdslen((sds
)key1
);
1104 l2
= sdslen((sds
)key2
);
1105 if (l1
!= l2
) return 0;
1106 return memcmp(key1
, key2
, l1
) == 0;
1109 static void dictRedisObjectDestructor(void *privdata
, void *val
)
1111 DICT_NOTUSED(privdata
);
1113 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
1117 static int dictObjKeyCompare(void *privdata
, const void *key1
,
1120 const robj
*o1
= key1
, *o2
= key2
;
1121 return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
1124 static unsigned int dictObjHash(const void *key
) {
1125 const robj
*o
= key
;
1126 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
1129 static int dictEncObjKeyCompare(void *privdata
, const void *key1
,
1132 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
1135 if (o1
->encoding
== REDIS_ENCODING_INT
&&
1136 o2
->encoding
== REDIS_ENCODING_INT
)
1137 return o1
->ptr
== o2
->ptr
;
1139 o1
= getDecodedObject(o1
);
1140 o2
= getDecodedObject(o2
);
1141 cmp
= sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
1147 static unsigned int dictEncObjHash(const void *key
) {
1148 robj
*o
= (robj
*) key
;
1150 if (o
->encoding
== REDIS_ENCODING_RAW
) {
1151 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
1153 if (o
->encoding
== REDIS_ENCODING_INT
) {
1157 len
= ll2string(buf
,32,(long)o
->ptr
);
1158 return dictGenHashFunction((unsigned char*)buf
, len
);
1162 o
= getDecodedObject(o
);
1163 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
1170 /* Sets type and expires */
1171 static dictType setDictType
= {
1172 dictEncObjHash
, /* hash function */
1175 dictEncObjKeyCompare
, /* key compare */
1176 dictRedisObjectDestructor
, /* key destructor */
1177 NULL
/* val destructor */
1180 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
1181 static dictType zsetDictType
= {
1182 dictEncObjHash
, /* hash function */
1185 dictEncObjKeyCompare
, /* key compare */
1186 dictRedisObjectDestructor
, /* key destructor */
1187 dictVanillaFree
/* val destructor of malloc(sizeof(double)) */
1191 static dictType dbDictType
= {
1192 dictObjHash
, /* hash function */
1195 dictObjKeyCompare
, /* key compare */
1196 dictRedisObjectDestructor
, /* key destructor */
1197 dictRedisObjectDestructor
/* val destructor */
1201 static dictType keyptrDictType
= {
1202 dictObjHash
, /* hash function */
1205 dictObjKeyCompare
, /* key compare */
1206 dictRedisObjectDestructor
, /* key destructor */
1207 NULL
/* val destructor */
1210 /* Hash type hash table (note that small hashes are represented with zimpaps) */
1211 static dictType hashDictType
= {
1212 dictEncObjHash
, /* hash function */
1215 dictEncObjKeyCompare
, /* key compare */
1216 dictRedisObjectDestructor
, /* key destructor */
1217 dictRedisObjectDestructor
/* val destructor */
1220 /* Keylist hash table type has unencoded redis objects as keys and
1221 * lists as values. It's used for blocking operations (BLPOP) and to
1222 * map swapped keys to a list of clients waiting for this keys to be loaded. */
1223 static dictType keylistDictType
= {
1224 dictObjHash
, /* hash function */
1227 dictObjKeyCompare
, /* key compare */
1228 dictRedisObjectDestructor
, /* key destructor */
1229 dictListDestructor
/* val destructor */
1232 static void version();
1234 /* ========================= Random utility functions ======================= */
1236 /* Redis generally does not try to recover from out of memory conditions
1237 * when allocating objects or strings, it is not clear if it will be possible
1238 * to report this condition to the client since the networking layer itself
1239 * is based on heap allocation for send buffers, so we simply abort.
1240 * At least the code will be simpler to read... */
1241 static void oom(const char *msg
) {
1242 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
1247 /* ====================== Redis server networking stuff ===================== */
1248 static void closeTimedoutClients(void) {
1251 time_t now
= time(NULL
);
1254 listRewind(server
.clients
,&li
);
1255 while ((ln
= listNext(&li
)) != NULL
) {
1256 c
= listNodeValue(ln
);
1257 if (server
.maxidletime
&&
1258 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
1259 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
1260 dictSize(c
->pubsub_channels
) == 0 && /* no timeout for pubsub */
1261 listLength(c
->pubsub_patterns
) == 0 &&
1262 (now
- c
->lastinteraction
> server
.maxidletime
))
1264 redisLog(REDIS_VERBOSE
,"Closing idle client");
1266 } else if (c
->flags
& REDIS_BLOCKED
) {
1267 if (c
->blockingto
!= 0 && c
->blockingto
< now
) {
1268 addReply(c
,shared
.nullmultibulk
);
1269 unblockClientWaitingData(c
);
1275 static int htNeedsResize(dict
*dict
) {
1276 long long size
, used
;
1278 size
= dictSlots(dict
);
1279 used
= dictSize(dict
);
1280 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
1281 (used
*100/size
< REDIS_HT_MINFILL
));
1284 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
1285 * we resize the hash table to save memory */
1286 static void tryResizeHashTables(void) {
1289 for (j
= 0; j
< server
.dbnum
; j
++) {
1290 if (htNeedsResize(server
.db
[j
].dict
))
1291 dictResize(server
.db
[j
].dict
);
1292 if (htNeedsResize(server
.db
[j
].expires
))
1293 dictResize(server
.db
[j
].expires
);
1297 /* Our hash table implementation performs rehashing incrementally while
1298 * we write/read from the hash table. Still if the server is idle, the hash
1299 * table will use two tables for a long time. So we try to use 1 millisecond
1300 * of CPU time at every serverCron() loop in order to rehash some key. */
1301 static void incrementallyRehash(void) {
1304 for (j
= 0; j
< server
.dbnum
; j
++) {
1305 if (dictIsRehashing(server
.db
[j
].dict
)) {
1306 dictRehashMilliseconds(server
.db
[j
].dict
,1);
1307 break; /* already used our millisecond for this loop... */
1312 /* A background saving child (BGSAVE) terminated its work. Handle this. */
1313 void backgroundSaveDoneHandler(int statloc
) {
1314 int exitcode
= WEXITSTATUS(statloc
);
1315 int bysignal
= WIFSIGNALED(statloc
);
1317 if (!bysignal
&& exitcode
== 0) {
1318 redisLog(REDIS_NOTICE
,
1319 "Background saving terminated with success");
1321 server
.lastsave
= time(NULL
);
1322 } else if (!bysignal
&& exitcode
!= 0) {
1323 redisLog(REDIS_WARNING
, "Background saving error");
1325 redisLog(REDIS_WARNING
,
1326 "Background saving terminated by signal %d", WTERMSIG(statloc
));
1327 rdbRemoveTempFile(server
.bgsavechildpid
);
1329 server
.bgsavechildpid
= -1;
1330 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1331 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1332 updateSlavesWaitingBgsave(exitcode
== 0 ? REDIS_OK
: REDIS_ERR
);
1335 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1337 void backgroundRewriteDoneHandler(int statloc
) {
1338 int exitcode
= WEXITSTATUS(statloc
);
1339 int bysignal
= WIFSIGNALED(statloc
);
1341 if (!bysignal
&& exitcode
== 0) {
1345 redisLog(REDIS_NOTICE
,
1346 "Background append only file rewriting terminated with success");
1347 /* Now it's time to flush the differences accumulated by the parent */
1348 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) server
.bgrewritechildpid
);
1349 fd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
1351 redisLog(REDIS_WARNING
, "Not able to open the temp append only file produced by the child: %s", strerror(errno
));
1354 /* Flush our data... */
1355 if (write(fd
,server
.bgrewritebuf
,sdslen(server
.bgrewritebuf
)) !=
1356 (signed) sdslen(server
.bgrewritebuf
)) {
1357 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
));
1361 redisLog(REDIS_NOTICE
,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server
.bgrewritebuf
));
1362 /* Now our work is to rename the temp file into the stable file. And
1363 * switch the file descriptor used by the server for append only. */
1364 if (rename(tmpfile
,server
.appendfilename
) == -1) {
1365 redisLog(REDIS_WARNING
,"Can't rename the temp append only file into the stable one: %s", strerror(errno
));
1369 /* Mission completed... almost */
1370 redisLog(REDIS_NOTICE
,"Append only file successfully rewritten.");
1371 if (server
.appendfd
!= -1) {
1372 /* If append only is actually enabled... */
1373 close(server
.appendfd
);
1374 server
.appendfd
= fd
;
1376 server
.appendseldb
= -1; /* Make sure it will issue SELECT */
1377 redisLog(REDIS_NOTICE
,"The new append only file was selected for future appends.");
1379 /* If append only is disabled we just generate a dump in this
1380 * format. Why not? */
1383 } else if (!bysignal
&& exitcode
!= 0) {
1384 redisLog(REDIS_WARNING
, "Background append only file rewriting error");
1386 redisLog(REDIS_WARNING
,
1387 "Background append only file rewriting terminated by signal %d",
1391 sdsfree(server
.bgrewritebuf
);
1392 server
.bgrewritebuf
= sdsempty();
1393 aofRemoveTempFile(server
.bgrewritechildpid
);
1394 server
.bgrewritechildpid
= -1;
1397 /* This function is called once a background process of some kind terminates,
1398 * as we want to avoid resizing the hash tables when there is a child in order
1399 * to play well with copy-on-write (otherwise when a resize happens lots of
1400 * memory pages are copied). The goal of this function is to update the ability
1401 * for dict.c to resize the hash tables accordingly to the fact we have o not
1402 * running childs. */
1403 static void updateDictResizePolicy(void) {
1404 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1)
1407 dictDisableResize();
1410 static int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
1411 int j
, loops
= server
.cronloops
++;
1412 REDIS_NOTUSED(eventLoop
);
1414 REDIS_NOTUSED(clientData
);
1416 /* We take a cached value of the unix time in the global state because
1417 * with virtual memory and aging there is to store the current time
1418 * in objects at every object access, and accuracy is not needed.
1419 * To access a global var is faster than calling time(NULL) */
1420 server
.unixtime
= time(NULL
);
1422 /* Show some info about non-empty databases */
1423 for (j
= 0; j
< server
.dbnum
; j
++) {
1424 long long size
, used
, vkeys
;
1426 size
= dictSlots(server
.db
[j
].dict
);
1427 used
= dictSize(server
.db
[j
].dict
);
1428 vkeys
= dictSize(server
.db
[j
].expires
);
1429 if (!(loops
% 50) && (used
|| vkeys
)) {
1430 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
1431 /* dictPrintStats(server.dict); */
1435 /* We don't want to resize the hash tables while a bacground saving
1436 * is in progress: the saving child is created using fork() that is
1437 * implemented with a copy-on-write semantic in most modern systems, so
1438 * if we resize the HT while there is the saving child at work actually
1439 * a lot of memory movements in the parent will cause a lot of pages
1441 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1) {
1442 if (!(loops
% 10)) tryResizeHashTables();
1443 if (server
.activerehashing
) incrementallyRehash();
1446 /* Show information about connected clients */
1447 if (!(loops
% 50)) {
1448 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use",
1449 listLength(server
.clients
)-listLength(server
.slaves
),
1450 listLength(server
.slaves
),
1451 zmalloc_used_memory());
1454 /* Close connections of timedout clients */
1455 if ((server
.maxidletime
&& !(loops
% 100)) || server
.blpop_blocked_clients
)
1456 closeTimedoutClients();
1458 /* Check if a background saving or AOF rewrite in progress terminated */
1459 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
1463 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
1464 if (pid
== server
.bgsavechildpid
) {
1465 backgroundSaveDoneHandler(statloc
);
1467 backgroundRewriteDoneHandler(statloc
);
1469 updateDictResizePolicy();
1472 /* If there is not a background saving in progress check if
1473 * we have to save now */
1474 time_t now
= time(NULL
);
1475 for (j
= 0; j
< server
.saveparamslen
; j
++) {
1476 struct saveparam
*sp
= server
.saveparams
+j
;
1478 if (server
.dirty
>= sp
->changes
&&
1479 now
-server
.lastsave
> sp
->seconds
) {
1480 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
1481 sp
->changes
, sp
->seconds
);
1482 rdbSaveBackground(server
.dbfilename
);
1488 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1489 * will use few CPU cycles if there are few expiring keys, otherwise
1490 * it will get more aggressive to avoid that too much memory is used by
1491 * keys that can be removed from the keyspace. */
1492 for (j
= 0; j
< server
.dbnum
; j
++) {
1494 redisDb
*db
= server
.db
+j
;
1496 /* Continue to expire if at the end of the cycle more than 25%
1497 * of the keys were expired. */
1499 long num
= dictSize(db
->expires
);
1500 time_t now
= time(NULL
);
1503 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
1504 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
1509 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
1510 t
= (time_t) dictGetEntryVal(de
);
1512 deleteKey(db
,dictGetEntryKey(de
));
1514 server
.stat_expiredkeys
++;
1517 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
1520 /* Swap a few keys on disk if we are over the memory limit and VM
1521 * is enbled. Try to free objects from the free list first. */
1522 if (vmCanSwapOut()) {
1523 while (server
.vm_enabled
&& zmalloc_used_memory() >
1524 server
.vm_max_memory
)
1528 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
1529 retval
= (server
.vm_max_threads
== 0) ?
1530 vmSwapOneObjectBlocking() :
1531 vmSwapOneObjectThreaded();
1532 if (retval
== REDIS_ERR
&& !(loops
% 300) &&
1533 zmalloc_used_memory() >
1534 (server
.vm_max_memory
+server
.vm_max_memory
/10))
1536 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
1538 /* Note that when using threade I/O we free just one object,
1539 * because anyway when the I/O thread in charge to swap this
1540 * object out will finish, the handler of completed jobs
1541 * will try to swap more objects if we are still out of memory. */
1542 if (retval
== REDIS_ERR
|| server
.vm_max_threads
> 0) break;
1546 /* Check if we should connect to a MASTER */
1547 if (server
.replstate
== REDIS_REPL_CONNECT
&& !(loops
% 10)) {
1548 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
1549 if (syncWithMaster() == REDIS_OK
) {
1550 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
1551 if (server
.appendonly
) rewriteAppendOnlyFileBackground();
1557 /* This function gets called every time Redis is entering the
1558 * main loop of the event driven library, that is, before to sleep
1559 * for ready file descriptors. */
1560 static void beforeSleep(struct aeEventLoop
*eventLoop
) {
1561 REDIS_NOTUSED(eventLoop
);
1563 /* Awake clients that got all the swapped keys they requested */
1564 if (server
.vm_enabled
&& listLength(server
.io_ready_clients
)) {
1568 listRewind(server
.io_ready_clients
,&li
);
1569 while((ln
= listNext(&li
))) {
1570 redisClient
*c
= ln
->value
;
1571 struct redisCommand
*cmd
;
1573 /* Resume the client. */
1574 listDelNode(server
.io_ready_clients
,ln
);
1575 c
->flags
&= (~REDIS_IO_WAIT
);
1576 server
.vm_blocked_clients
--;
1577 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
1578 readQueryFromClient
, c
);
1579 cmd
= lookupCommand(c
->argv
[0]->ptr
);
1580 assert(cmd
!= NULL
);
1583 /* There may be more data to process in the input buffer. */
1584 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
1585 processInputBuffer(c
);
1588 /* Write the AOF buffer on disk */
1589 flushAppendOnlyFile();
1592 static void createSharedObjects(void) {
1595 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
1596 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
1597 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
1598 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
1599 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
1600 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
1601 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
1602 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
1603 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
1604 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
1605 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
1606 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
1607 "-ERR Operation against a key holding the wrong kind of value\r\n"));
1608 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
1609 "-ERR no such key\r\n"));
1610 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
1611 "-ERR syntax error\r\n"));
1612 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
1613 "-ERR source and destination objects are the same\r\n"));
1614 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
1615 "-ERR index out of range\r\n"));
1616 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
1617 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
1618 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
1619 shared
.select0
= createStringObject("select 0\r\n",10);
1620 shared
.select1
= createStringObject("select 1\r\n",10);
1621 shared
.select2
= createStringObject("select 2\r\n",10);
1622 shared
.select3
= createStringObject("select 3\r\n",10);
1623 shared
.select4
= createStringObject("select 4\r\n",10);
1624 shared
.select5
= createStringObject("select 5\r\n",10);
1625 shared
.select6
= createStringObject("select 6\r\n",10);
1626 shared
.select7
= createStringObject("select 7\r\n",10);
1627 shared
.select8
= createStringObject("select 8\r\n",10);
1628 shared
.select9
= createStringObject("select 9\r\n",10);
1629 shared
.messagebulk
= createStringObject("$7\r\nmessage\r\n",13);
1630 shared
.pmessagebulk
= createStringObject("$8\r\npmessage\r\n",14);
1631 shared
.subscribebulk
= createStringObject("$9\r\nsubscribe\r\n",15);
1632 shared
.unsubscribebulk
= createStringObject("$11\r\nunsubscribe\r\n",18);
1633 shared
.psubscribebulk
= createStringObject("$10\r\npsubscribe\r\n",17);
1634 shared
.punsubscribebulk
= createStringObject("$12\r\npunsubscribe\r\n",19);
1635 shared
.mbulk3
= createStringObject("*3\r\n",4);
1636 shared
.mbulk4
= createStringObject("*4\r\n",4);
1637 for (j
= 0; j
< REDIS_SHARED_INTEGERS
; j
++) {
1638 shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
);
1639 shared
.integers
[j
]->encoding
= REDIS_ENCODING_INT
;
1643 static void appendServerSaveParams(time_t seconds
, int changes
) {
1644 server
.saveparams
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1));
1645 server
.saveparams
[server
.saveparamslen
].seconds
= seconds
;
1646 server
.saveparams
[server
.saveparamslen
].changes
= changes
;
1647 server
.saveparamslen
++;
1650 static void resetServerSaveParams() {
1651 zfree(server
.saveparams
);
1652 server
.saveparams
= NULL
;
1653 server
.saveparamslen
= 0;
1656 static void initServerConfig() {
1657 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
1658 server
.port
= REDIS_SERVERPORT
;
1659 server
.verbosity
= REDIS_VERBOSE
;
1660 server
.maxidletime
= REDIS_MAXIDLETIME
;
1661 server
.saveparams
= NULL
;
1662 server
.logfile
= NULL
; /* NULL = log on standard output */
1663 server
.bindaddr
= NULL
;
1664 server
.glueoutputbuf
= 1;
1665 server
.daemonize
= 0;
1666 server
.appendonly
= 0;
1667 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
1668 server
.lastfsync
= time(NULL
);
1669 server
.appendfd
= -1;
1670 server
.appendseldb
= -1; /* Make sure the first time will not match */
1671 server
.pidfile
= zstrdup("/var/run/redis.pid");
1672 server
.dbfilename
= zstrdup("dump.rdb");
1673 server
.appendfilename
= zstrdup("appendonly.aof");
1674 server
.requirepass
= NULL
;
1675 server
.rdbcompression
= 1;
1676 server
.activerehashing
= 1;
1677 server
.maxclients
= 0;
1678 server
.blpop_blocked_clients
= 0;
1679 server
.maxmemory
= 0;
1680 server
.vm_enabled
= 0;
1681 server
.vm_swap_file
= zstrdup("/tmp/redis-%p.vm");
1682 server
.vm_page_size
= 256; /* 256 bytes per page */
1683 server
.vm_pages
= 1024*1024*100; /* 104 millions of pages */
1684 server
.vm_max_memory
= 1024LL*1024*1024*1; /* 1 GB of RAM */
1685 server
.vm_max_threads
= 4;
1686 server
.vm_blocked_clients
= 0;
1687 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
1688 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
1690 resetServerSaveParams();
1692 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1693 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1694 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1695 /* Replication related */
1697 server
.masterauth
= NULL
;
1698 server
.masterhost
= NULL
;
1699 server
.masterport
= 6379;
1700 server
.master
= NULL
;
1701 server
.replstate
= REDIS_REPL_NONE
;
1703 /* Double constants initialization */
1705 R_PosInf
= 1.0/R_Zero
;
1706 R_NegInf
= -1.0/R_Zero
;
1707 R_Nan
= R_Zero
/R_Zero
;
1710 static void initServer() {
1713 signal(SIGHUP
, SIG_IGN
);
1714 signal(SIGPIPE
, SIG_IGN
);
1715 setupSigSegvAction();
1717 server
.devnull
= fopen("/dev/null","w");
1718 if (server
.devnull
== NULL
) {
1719 redisLog(REDIS_WARNING
, "Can't open /dev/null: %s", server
.neterr
);
1722 server
.clients
= listCreate();
1723 server
.slaves
= listCreate();
1724 server
.monitors
= listCreate();
1725 server
.objfreelist
= listCreate();
1726 createSharedObjects();
1727 server
.el
= aeCreateEventLoop();
1728 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
1729 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
1730 if (server
.fd
== -1) {
1731 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
1734 for (j
= 0; j
< server
.dbnum
; j
++) {
1735 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
1736 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
1737 server
.db
[j
].blockingkeys
= dictCreate(&keylistDictType
,NULL
);
1738 if (server
.vm_enabled
)
1739 server
.db
[j
].io_keys
= dictCreate(&keylistDictType
,NULL
);
1740 server
.db
[j
].id
= j
;
1742 server
.pubsub_channels
= dictCreate(&keylistDictType
,NULL
);
1743 server
.pubsub_patterns
= listCreate();
1744 listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
);
1745 listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
);
1746 server
.cronloops
= 0;
1747 server
.bgsavechildpid
= -1;
1748 server
.bgrewritechildpid
= -1;
1749 server
.bgrewritebuf
= sdsempty();
1750 server
.aofbuf
= sdsempty();
1751 server
.lastsave
= time(NULL
);
1753 server
.stat_numcommands
= 0;
1754 server
.stat_numconnections
= 0;
1755 server
.stat_expiredkeys
= 0;
1756 server
.stat_starttime
= time(NULL
);
1757 server
.unixtime
= time(NULL
);
1758 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
1759 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
1760 acceptHandler
, NULL
) == AE_ERR
) oom("creating file event");
1762 if (server
.appendonly
) {
1763 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
1764 if (server
.appendfd
== -1) {
1765 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
1771 if (server
.vm_enabled
) vmInit();
1774 /* Empty the whole database */
1775 static long long emptyDb() {
1777 long long removed
= 0;
1779 for (j
= 0; j
< server
.dbnum
; j
++) {
1780 removed
+= dictSize(server
.db
[j
].dict
);
1781 dictEmpty(server
.db
[j
].dict
);
1782 dictEmpty(server
.db
[j
].expires
);
1787 static int yesnotoi(char *s
) {
1788 if (!strcasecmp(s
,"yes")) return 1;
1789 else if (!strcasecmp(s
,"no")) return 0;
1793 /* I agree, this is a very rudimental way to load a configuration...
1794 will improve later if the config gets more complex */
1795 static void loadServerConfig(char *filename
) {
1797 char buf
[REDIS_CONFIGLINE_MAX
+1], *err
= NULL
;
1801 if (filename
[0] == '-' && filename
[1] == '\0')
1804 if ((fp
= fopen(filename
,"r")) == NULL
) {
1805 redisLog(REDIS_WARNING
, "Fatal error, can't open config file '%s'", filename
);
1810 while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) {
1816 line
= sdstrim(line
," \t\r\n");
1818 /* Skip comments and blank lines*/
1819 if (line
[0] == '#' || line
[0] == '\0') {
1824 /* Split into arguments */
1825 argv
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
);
1826 sdstolower(argv
[0]);
1828 /* Execute config directives */
1829 if (!strcasecmp(argv
[0],"timeout") && argc
== 2) {
1830 server
.maxidletime
= atoi(argv
[1]);
1831 if (server
.maxidletime
< 0) {
1832 err
= "Invalid timeout value"; goto loaderr
;
1834 } else if (!strcasecmp(argv
[0],"port") && argc
== 2) {
1835 server
.port
= atoi(argv
[1]);
1836 if (server
.port
< 1 || server
.port
> 65535) {
1837 err
= "Invalid port"; goto loaderr
;
1839 } else if (!strcasecmp(argv
[0],"bind") && argc
== 2) {
1840 server
.bindaddr
= zstrdup(argv
[1]);
1841 } else if (!strcasecmp(argv
[0],"save") && argc
== 3) {
1842 int seconds
= atoi(argv
[1]);
1843 int changes
= atoi(argv
[2]);
1844 if (seconds
< 1 || changes
< 0) {
1845 err
= "Invalid save parameters"; goto loaderr
;
1847 appendServerSaveParams(seconds
,changes
);
1848 } else if (!strcasecmp(argv
[0],"dir") && argc
== 2) {
1849 if (chdir(argv
[1]) == -1) {
1850 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s",
1851 argv
[1], strerror(errno
));
1854 } else if (!strcasecmp(argv
[0],"loglevel") && argc
== 2) {
1855 if (!strcasecmp(argv
[1],"debug")) server
.verbosity
= REDIS_DEBUG
;
1856 else if (!strcasecmp(argv
[1],"verbose")) server
.verbosity
= REDIS_VERBOSE
;
1857 else if (!strcasecmp(argv
[1],"notice")) server
.verbosity
= REDIS_NOTICE
;
1858 else if (!strcasecmp(argv
[1],"warning")) server
.verbosity
= REDIS_WARNING
;
1860 err
= "Invalid log level. Must be one of debug, notice, warning";
1863 } else if (!strcasecmp(argv
[0],"logfile") && argc
== 2) {
1866 server
.logfile
= zstrdup(argv
[1]);
1867 if (!strcasecmp(server
.logfile
,"stdout")) {
1868 zfree(server
.logfile
);
1869 server
.logfile
= NULL
;
1871 if (server
.logfile
) {
1872 /* Test if we are able to open the file. The server will not
1873 * be able to abort just for this problem later... */
1874 logfp
= fopen(server
.logfile
,"a");
1875 if (logfp
== NULL
) {
1876 err
= sdscatprintf(sdsempty(),
1877 "Can't open the log file: %s", strerror(errno
));
1882 } else if (!strcasecmp(argv
[0],"databases") && argc
== 2) {
1883 server
.dbnum
= atoi(argv
[1]);
1884 if (server
.dbnum
< 1) {
1885 err
= "Invalid number of databases"; goto loaderr
;
1887 } else if (!strcasecmp(argv
[0],"include") && argc
== 2) {
1888 loadServerConfig(argv
[1]);
1889 } else if (!strcasecmp(argv
[0],"maxclients") && argc
== 2) {
1890 server
.maxclients
= atoi(argv
[1]);
1891 } else if (!strcasecmp(argv
[0],"maxmemory") && argc
== 2) {
1892 server
.maxmemory
= memtoll(argv
[1],NULL
);
1893 } else if (!strcasecmp(argv
[0],"slaveof") && argc
== 3) {
1894 server
.masterhost
= sdsnew(argv
[1]);
1895 server
.masterport
= atoi(argv
[2]);
1896 server
.replstate
= REDIS_REPL_CONNECT
;
1897 } else if (!strcasecmp(argv
[0],"masterauth") && argc
== 2) {
1898 server
.masterauth
= zstrdup(argv
[1]);
1899 } else if (!strcasecmp(argv
[0],"glueoutputbuf") && argc
== 2) {
1900 if ((server
.glueoutputbuf
= yesnotoi(argv
[1])) == -1) {
1901 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1903 } else if (!strcasecmp(argv
[0],"rdbcompression") && argc
== 2) {
1904 if ((server
.rdbcompression
= yesnotoi(argv
[1])) == -1) {
1905 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1907 } else if (!strcasecmp(argv
[0],"activerehashing") && argc
== 2) {
1908 if ((server
.activerehashing
= yesnotoi(argv
[1])) == -1) {
1909 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1911 } else if (!strcasecmp(argv
[0],"daemonize") && argc
== 2) {
1912 if ((server
.daemonize
= yesnotoi(argv
[1])) == -1) {
1913 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1915 } else if (!strcasecmp(argv
[0],"appendonly") && argc
== 2) {
1916 if ((server
.appendonly
= yesnotoi(argv
[1])) == -1) {
1917 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1919 } else if (!strcasecmp(argv
[0],"appendfilename") && argc
== 2) {
1920 zfree(server
.appendfilename
);
1921 server
.appendfilename
= zstrdup(argv
[1]);
1922 } else if (!strcasecmp(argv
[0],"appendfsync") && argc
== 2) {
1923 if (!strcasecmp(argv
[1],"no")) {
1924 server
.appendfsync
= APPENDFSYNC_NO
;
1925 } else if (!strcasecmp(argv
[1],"always")) {
1926 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1927 } else if (!strcasecmp(argv
[1],"everysec")) {
1928 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
1930 err
= "argument must be 'no', 'always' or 'everysec'";
1933 } else if (!strcasecmp(argv
[0],"requirepass") && argc
== 2) {
1934 server
.requirepass
= zstrdup(argv
[1]);
1935 } else if (!strcasecmp(argv
[0],"pidfile") && argc
== 2) {
1936 zfree(server
.pidfile
);
1937 server
.pidfile
= zstrdup(argv
[1]);
1938 } else if (!strcasecmp(argv
[0],"dbfilename") && argc
== 2) {
1939 zfree(server
.dbfilename
);
1940 server
.dbfilename
= zstrdup(argv
[1]);
1941 } else if (!strcasecmp(argv
[0],"vm-enabled") && argc
== 2) {
1942 if ((server
.vm_enabled
= yesnotoi(argv
[1])) == -1) {
1943 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1945 } else if (!strcasecmp(argv
[0],"vm-swap-file") && argc
== 2) {
1946 zfree(server
.vm_swap_file
);
1947 server
.vm_swap_file
= zstrdup(argv
[1]);
1948 } else if (!strcasecmp(argv
[0],"vm-max-memory") && argc
== 2) {
1949 server
.vm_max_memory
= memtoll(argv
[1],NULL
);
1950 } else if (!strcasecmp(argv
[0],"vm-page-size") && argc
== 2) {
1951 server
.vm_page_size
= memtoll(argv
[1], NULL
);
1952 } else if (!strcasecmp(argv
[0],"vm-pages") && argc
== 2) {
1953 server
.vm_pages
= memtoll(argv
[1], NULL
);
1954 } else if (!strcasecmp(argv
[0],"vm-max-threads") && argc
== 2) {
1955 server
.vm_max_threads
= strtoll(argv
[1], NULL
, 10);
1956 } else if (!strcasecmp(argv
[0],"hash-max-zipmap-entries") && argc
== 2){
1957 server
.hash_max_zipmap_entries
= memtoll(argv
[1], NULL
);
1958 } else if (!strcasecmp(argv
[0],"hash-max-zipmap-value") && argc
== 2){
1959 server
.hash_max_zipmap_value
= memtoll(argv
[1], NULL
);
1961 err
= "Bad directive or wrong number of arguments"; goto loaderr
;
1963 for (j
= 0; j
< argc
; j
++)
1968 if (fp
!= stdin
) fclose(fp
);
1972 fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n");
1973 fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
);
1974 fprintf(stderr
, ">>> '%s'\n", line
);
1975 fprintf(stderr
, "%s\n", err
);
1979 static void freeClientArgv(redisClient
*c
) {
1982 for (j
= 0; j
< c
->argc
; j
++)
1983 decrRefCount(c
->argv
[j
]);
1984 for (j
= 0; j
< c
->mbargc
; j
++)
1985 decrRefCount(c
->mbargv
[j
]);
1990 static void freeClient(redisClient
*c
) {
1993 /* Note that if the client we are freeing is blocked into a blocking
1994 * call, we have to set querybuf to NULL *before* to call
1995 * unblockClientWaitingData() to avoid processInputBuffer() will get
1996 * called. Also it is important to remove the file events after
1997 * this, because this call adds the READABLE event. */
1998 sdsfree(c
->querybuf
);
2000 if (c
->flags
& REDIS_BLOCKED
)
2001 unblockClientWaitingData(c
);
2003 /* Unsubscribe from all the pubsub channels */
2004 pubsubUnsubscribeAllChannels(c
,0);
2005 pubsubUnsubscribeAllPatterns(c
,0);
2006 dictRelease(c
->pubsub_channels
);
2007 listRelease(c
->pubsub_patterns
);
2008 /* Obvious cleanup */
2009 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
2010 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
2011 listRelease(c
->reply
);
2014 /* Remove from the list of clients */
2015 ln
= listSearchKey(server
.clients
,c
);
2016 redisAssert(ln
!= NULL
);
2017 listDelNode(server
.clients
,ln
);
2018 /* Remove from the list of clients waiting for swapped keys */
2019 if (c
->flags
& REDIS_IO_WAIT
&& listLength(c
->io_keys
) == 0) {
2020 ln
= listSearchKey(server
.io_ready_clients
,c
);
2022 listDelNode(server
.io_ready_clients
,ln
);
2023 server
.vm_blocked_clients
--;
2026 while (server
.vm_enabled
&& listLength(c
->io_keys
)) {
2027 ln
= listFirst(c
->io_keys
);
2028 dontWaitForSwappedKey(c
,ln
->value
);
2030 listRelease(c
->io_keys
);
2031 /* Master/slave cleanup */
2032 if (c
->flags
& REDIS_SLAVE
) {
2033 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
2035 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
2036 ln
= listSearchKey(l
,c
);
2037 redisAssert(ln
!= NULL
);
2040 if (c
->flags
& REDIS_MASTER
) {
2041 server
.master
= NULL
;
2042 server
.replstate
= REDIS_REPL_CONNECT
;
2044 /* Release memory */
2047 freeClientMultiState(c
);
2051 #define GLUEREPLY_UP_TO (1024)
2052 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
2054 char buf
[GLUEREPLY_UP_TO
];
2059 listRewind(c
->reply
,&li
);
2060 while((ln
= listNext(&li
))) {
2064 objlen
= sdslen(o
->ptr
);
2065 if (copylen
+ objlen
<= GLUEREPLY_UP_TO
) {
2066 memcpy(buf
+copylen
,o
->ptr
,objlen
);
2068 listDelNode(c
->reply
,ln
);
2070 if (copylen
== 0) return;
2074 /* Now the output buffer is empty, add the new single element */
2075 o
= createObject(REDIS_STRING
,sdsnewlen(buf
,copylen
));
2076 listAddNodeHead(c
->reply
,o
);
2079 static void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2080 redisClient
*c
= privdata
;
2081 int nwritten
= 0, totwritten
= 0, objlen
;
2084 REDIS_NOTUSED(mask
);
2086 /* Use writev() if we have enough buffers to send */
2087 if (!server
.glueoutputbuf
&&
2088 listLength(c
->reply
) > REDIS_WRITEV_THRESHOLD
&&
2089 !(c
->flags
& REDIS_MASTER
))
2091 sendReplyToClientWritev(el
, fd
, privdata
, mask
);
2095 while(listLength(c
->reply
)) {
2096 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
2097 glueReplyBuffersIfNeeded(c
);
2099 o
= listNodeValue(listFirst(c
->reply
));
2100 objlen
= sdslen(o
->ptr
);
2103 listDelNode(c
->reply
,listFirst(c
->reply
));
2107 if (c
->flags
& REDIS_MASTER
) {
2108 /* Don't reply to a master */
2109 nwritten
= objlen
- c
->sentlen
;
2111 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen
- c
->sentlen
);
2112 if (nwritten
<= 0) break;
2114 c
->sentlen
+= nwritten
;
2115 totwritten
+= nwritten
;
2116 /* If we fully sent the object on head go to the next one */
2117 if (c
->sentlen
== objlen
) {
2118 listDelNode(c
->reply
,listFirst(c
->reply
));
2121 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
2122 * bytes, in a single threaded server it's a good idea to serve
2123 * other clients as well, even if a very large request comes from
2124 * super fast link that is always able to accept data (in real world
2125 * scenario think about 'KEYS *' against the loopback interfae) */
2126 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
) break;
2128 if (nwritten
== -1) {
2129 if (errno
== EAGAIN
) {
2132 redisLog(REDIS_VERBOSE
,
2133 "Error writing to client: %s", strerror(errno
));
2138 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
2139 if (listLength(c
->reply
) == 0) {
2141 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
2145 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
)
2147 redisClient
*c
= privdata
;
2148 int nwritten
= 0, totwritten
= 0, objlen
, willwrite
;
2150 struct iovec iov
[REDIS_WRITEV_IOVEC_COUNT
];
2151 int offset
, ion
= 0;
2153 REDIS_NOTUSED(mask
);
2156 while (listLength(c
->reply
)) {
2157 offset
= c
->sentlen
;
2161 /* fill-in the iov[] array */
2162 for(node
= listFirst(c
->reply
); node
; node
= listNextNode(node
)) {
2163 o
= listNodeValue(node
);
2164 objlen
= sdslen(o
->ptr
);
2166 if (totwritten
+ objlen
- offset
> REDIS_MAX_WRITE_PER_EVENT
)
2169 if(ion
== REDIS_WRITEV_IOVEC_COUNT
)
2170 break; /* no more iovecs */
2172 iov
[ion
].iov_base
= ((char*)o
->ptr
) + offset
;
2173 iov
[ion
].iov_len
= objlen
- offset
;
2174 willwrite
+= objlen
- offset
;
2175 offset
= 0; /* just for the first item */
2182 /* write all collected blocks at once */
2183 if((nwritten
= writev(fd
, iov
, ion
)) < 0) {
2184 if (errno
!= EAGAIN
) {
2185 redisLog(REDIS_VERBOSE
,
2186 "Error writing to client: %s", strerror(errno
));
2193 totwritten
+= nwritten
;
2194 offset
= c
->sentlen
;
2196 /* remove written robjs from c->reply */
2197 while (nwritten
&& listLength(c
->reply
)) {
2198 o
= listNodeValue(listFirst(c
->reply
));
2199 objlen
= sdslen(o
->ptr
);
2201 if(nwritten
>= objlen
- offset
) {
2202 listDelNode(c
->reply
, listFirst(c
->reply
));
2203 nwritten
-= objlen
- offset
;
2207 c
->sentlen
+= nwritten
;
2215 c
->lastinteraction
= time(NULL
);
2217 if (listLength(c
->reply
) == 0) {
2219 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
2223 static struct redisCommand
*lookupCommand(char *name
) {
2225 while(cmdTable
[j
].name
!= NULL
) {
2226 if (!strcasecmp(name
,cmdTable
[j
].name
)) return &cmdTable
[j
];
2232 /* resetClient prepare the client to process the next command */
2233 static void resetClient(redisClient
*c
) {
2239 /* Call() is the core of Redis execution of a command */
2240 static void call(redisClient
*c
, struct redisCommand
*cmd
) {
2243 dirty
= server
.dirty
;
2245 dirty
= server
.dirty
-dirty
;
2247 if (server
.appendonly
&& dirty
)
2248 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
2249 if ((dirty
|| cmd
->flags
& REDIS_CMD_FORCE_REPLICATION
) &&
2250 listLength(server
.slaves
))
2251 replicationFeedSlaves(server
.slaves
,c
->db
->id
,c
->argv
,c
->argc
);
2252 if (listLength(server
.monitors
))
2253 replicationFeedMonitors(server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
);
2254 server
.stat_numcommands
++;
2257 /* If this function gets called we already read a whole
2258 * command, argments are in the client argv/argc fields.
2259 * processCommand() execute the command or prepare the
2260 * server for a bulk read from the client.
2262 * If 1 is returned the client is still alive and valid and
2263 * and other operations can be performed by the caller. Otherwise
2264 * if 0 is returned the client was destroied (i.e. after QUIT). */
2265 static int processCommand(redisClient
*c
) {
2266 struct redisCommand
*cmd
;
2268 /* Free some memory if needed (maxmemory setting) */
2269 if (server
.maxmemory
) freeMemoryIfNeeded();
2271 /* Handle the multi bulk command type. This is an alternative protocol
2272 * supported by Redis in order to receive commands that are composed of
2273 * multiple binary-safe "bulk" arguments. The latency of processing is
2274 * a bit higher but this allows things like multi-sets, so if this
2275 * protocol is used only for MSET and similar commands this is a big win. */
2276 if (c
->multibulk
== 0 && c
->argc
== 1 && ((char*)(c
->argv
[0]->ptr
))[0] == '*') {
2277 c
->multibulk
= atoi(((char*)c
->argv
[0]->ptr
)+1);
2278 if (c
->multibulk
<= 0) {
2282 decrRefCount(c
->argv
[c
->argc
-1]);
2286 } else if (c
->multibulk
) {
2287 if (c
->bulklen
== -1) {
2288 if (((char*)c
->argv
[0]->ptr
)[0] != '$') {
2289 addReplySds(c
,sdsnew("-ERR multi bulk protocol error\r\n"));
2293 int bulklen
= atoi(((char*)c
->argv
[0]->ptr
)+1);
2294 decrRefCount(c
->argv
[0]);
2295 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
2297 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
2302 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
2306 c
->mbargv
= zrealloc(c
->mbargv
,(sizeof(robj
*))*(c
->mbargc
+1));
2307 c
->mbargv
[c
->mbargc
] = c
->argv
[0];
2311 if (c
->multibulk
== 0) {
2315 /* Here we need to swap the multi-bulk argc/argv with the
2316 * normal argc/argv of the client structure. */
2318 c
->argv
= c
->mbargv
;
2319 c
->mbargv
= auxargv
;
2322 c
->argc
= c
->mbargc
;
2323 c
->mbargc
= auxargc
;
2325 /* We need to set bulklen to something different than -1
2326 * in order for the code below to process the command without
2327 * to try to read the last argument of a bulk command as
2328 * a special argument. */
2330 /* continue below and process the command */
2337 /* -- end of multi bulk commands processing -- */
2339 /* The QUIT command is handled as a special case. Normal command
2340 * procs are unable to close the client connection safely */
2341 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
2346 /* Now lookup the command and check ASAP about trivial error conditions
2347 * such wrong arity, bad command name and so forth. */
2348 cmd
= lookupCommand(c
->argv
[0]->ptr
);
2351 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
2352 (char*)c
->argv
[0]->ptr
));
2355 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
2356 (c
->argc
< -cmd
->arity
)) {
2358 sdscatprintf(sdsempty(),
2359 "-ERR wrong number of arguments for '%s' command\r\n",
2363 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
2364 /* This is a bulk command, we have to read the last argument yet. */
2365 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
2367 decrRefCount(c
->argv
[c
->argc
-1]);
2368 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
2370 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
2375 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
2376 /* It is possible that the bulk read is already in the
2377 * buffer. Check this condition and handle it accordingly.
2378 * This is just a fast path, alternative to call processInputBuffer().
2379 * It's a good idea since the code is small and this condition
2380 * happens most of the times. */
2381 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
2382 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2384 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2386 /* Otherwise return... there is to read the last argument
2387 * from the socket. */
2391 /* Let's try to encode the bulk object to save space. */
2392 if (cmd
->flags
& REDIS_CMD_BULK
)
2393 c
->argv
[c
->argc
-1] = tryObjectEncoding(c
->argv
[c
->argc
-1]);
2395 /* Check if the user is authenticated */
2396 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
2397 addReplySds(c
,sdsnew("-ERR operation not permitted\r\n"));
2402 /* Handle the maxmemory directive */
2403 if (server
.maxmemory
&& (cmd
->flags
& REDIS_CMD_DENYOOM
) &&
2404 zmalloc_used_memory() > server
.maxmemory
)
2406 addReplySds(c
,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
2411 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
2412 if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0)
2414 cmd
->proc
!= subscribeCommand
&& cmd
->proc
!= unsubscribeCommand
&&
2415 cmd
->proc
!= psubscribeCommand
&& cmd
->proc
!= punsubscribeCommand
) {
2416 addReplySds(c
,sdsnew("-ERR only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context\r\n"));
2421 /* Exec the command */
2422 if (c
->flags
& REDIS_MULTI
&& cmd
->proc
!= execCommand
&& cmd
->proc
!= discardCommand
) {
2423 queueMultiCommand(c
,cmd
);
2424 addReply(c
,shared
.queued
);
2426 if (server
.vm_enabled
&& server
.vm_max_threads
> 0 &&
2427 blockClientOnSwappedKeys(c
,cmd
)) return 1;
2431 /* Prepare the client for the next command */
2436 static void replicationFeedSlaves(list
*slaves
, int dictid
, robj
**argv
, int argc
) {
2441 /* We need 1+(ARGS*3) objects since commands are using the new protocol
2442 * and we one 1 object for the first "*<count>\r\n" multibulk count, then
2443 * for every additional object we have "$<count>\r\n" + object + "\r\n". */
2444 robj
*static_outv
[REDIS_STATIC_ARGS
*3+1];
2447 if (argc
<= REDIS_STATIC_ARGS
) {
2450 outv
= zmalloc(sizeof(robj
*)*(argc
*3+1));
2453 lenobj
= createObject(REDIS_STRING
,
2454 sdscatprintf(sdsempty(), "*%d\r\n", argc
));
2455 lenobj
->refcount
= 0;
2456 outv
[outc
++] = lenobj
;
2457 for (j
= 0; j
< argc
; j
++) {
2458 lenobj
= createObject(REDIS_STRING
,
2459 sdscatprintf(sdsempty(),"$%lu\r\n",
2460 (unsigned long) stringObjectLen(argv
[j
])));
2461 lenobj
->refcount
= 0;
2462 outv
[outc
++] = lenobj
;
2463 outv
[outc
++] = argv
[j
];
2464 outv
[outc
++] = shared
.crlf
;
2467 /* Increment all the refcounts at start and decrement at end in order to
2468 * be sure to free objects if there is no slave in a replication state
2469 * able to be feed with commands */
2470 for (j
= 0; j
< outc
; j
++) incrRefCount(outv
[j
]);
2471 listRewind(slaves
,&li
);
2472 while((ln
= listNext(&li
))) {
2473 redisClient
*slave
= ln
->value
;
2475 /* Don't feed slaves that are still waiting for BGSAVE to start */
2476 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) continue;
2478 /* Feed all the other slaves, MONITORs and so on */
2479 if (slave
->slaveseldb
!= dictid
) {
2483 case 0: selectcmd
= shared
.select0
; break;
2484 case 1: selectcmd
= shared
.select1
; break;
2485 case 2: selectcmd
= shared
.select2
; break;
2486 case 3: selectcmd
= shared
.select3
; break;
2487 case 4: selectcmd
= shared
.select4
; break;
2488 case 5: selectcmd
= shared
.select5
; break;
2489 case 6: selectcmd
= shared
.select6
; break;
2490 case 7: selectcmd
= shared
.select7
; break;
2491 case 8: selectcmd
= shared
.select8
; break;
2492 case 9: selectcmd
= shared
.select9
; break;
2494 selectcmd
= createObject(REDIS_STRING
,
2495 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
2496 selectcmd
->refcount
= 0;
2499 addReply(slave
,selectcmd
);
2500 slave
->slaveseldb
= dictid
;
2502 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
2504 for (j
= 0; j
< outc
; j
++) decrRefCount(outv
[j
]);
2505 if (outv
!= static_outv
) zfree(outv
);
2508 static sds
sdscatrepr(sds s
, char *p
, size_t len
) {
2509 s
= sdscatlen(s
,"\"",1);
2514 s
= sdscatprintf(s
,"\\%c",*p
);
2516 case '\n': s
= sdscatlen(s
,"\\n",1); break;
2517 case '\r': s
= sdscatlen(s
,"\\r",1); break;
2518 case '\t': s
= sdscatlen(s
,"\\t",1); break;
2519 case '\a': s
= sdscatlen(s
,"\\a",1); break;
2520 case '\b': s
= sdscatlen(s
,"\\b",1); break;
2523 s
= sdscatprintf(s
,"%c",*p
);
2525 s
= sdscatprintf(s
,"\\x%02x",(unsigned char)*p
);
2530 return sdscatlen(s
,"\"",1);
2533 static void replicationFeedMonitors(list
*monitors
, int dictid
, robj
**argv
, int argc
) {
2537 sds cmdrepr
= sdsnew("+");
2541 gettimeofday(&tv
,NULL
);
2542 cmdrepr
= sdscatprintf(cmdrepr
,"%ld.%ld ",(long)tv
.tv_sec
,(long)tv
.tv_usec
);
2543 if (dictid
!= 0) cmdrepr
= sdscatprintf(cmdrepr
,"(db %d) ", dictid
);
2545 for (j
= 0; j
< argc
; j
++) {
2546 if (argv
[j
]->encoding
== REDIS_ENCODING_INT
) {
2547 cmdrepr
= sdscatprintf(cmdrepr
, "%ld", (long)argv
[j
]->ptr
);
2549 cmdrepr
= sdscatrepr(cmdrepr
,(char*)argv
[j
]->ptr
,
2550 sdslen(argv
[j
]->ptr
));
2553 cmdrepr
= sdscatlen(cmdrepr
," ",1);
2555 cmdrepr
= sdscatlen(cmdrepr
,"\r\n",2);
2556 cmdobj
= createObject(REDIS_STRING
,cmdrepr
);
2558 listRewind(monitors
,&li
);
2559 while((ln
= listNext(&li
))) {
2560 redisClient
*monitor
= ln
->value
;
2561 addReply(monitor
,cmdobj
);
2563 decrRefCount(cmdobj
);
2566 static void processInputBuffer(redisClient
*c
) {
2568 /* Before to process the input buffer, make sure the client is not
2569 * waitig for a blocking operation such as BLPOP. Note that the first
2570 * iteration the client is never blocked, otherwise the processInputBuffer
2571 * would not be called at all, but after the execution of the first commands
2572 * in the input buffer the client may be blocked, and the "goto again"
2573 * will try to reiterate. The following line will make it return asap. */
2574 if (c
->flags
& REDIS_BLOCKED
|| c
->flags
& REDIS_IO_WAIT
) return;
2575 if (c
->bulklen
== -1) {
2576 /* Read the first line of the query */
2577 char *p
= strchr(c
->querybuf
,'\n');
2584 query
= c
->querybuf
;
2585 c
->querybuf
= sdsempty();
2586 querylen
= 1+(p
-(query
));
2587 if (sdslen(query
) > querylen
) {
2588 /* leave data after the first line of the query in the buffer */
2589 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
2591 *p
= '\0'; /* remove "\n" */
2592 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
2593 sdsupdatelen(query
);
2595 /* Now we can split the query in arguments */
2596 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
2599 if (c
->argv
) zfree(c
->argv
);
2600 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
2602 for (j
= 0; j
< argc
; j
++) {
2603 if (sdslen(argv
[j
])) {
2604 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
2612 /* Execute the command. If the client is still valid
2613 * after processCommand() return and there is something
2614 * on the query buffer try to process the next command. */
2615 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2617 /* Nothing to process, argc == 0. Just process the query
2618 * buffer if it's not empty or return to the caller */
2619 if (sdslen(c
->querybuf
)) goto again
;
2622 } else if (sdslen(c
->querybuf
) >= REDIS_REQUEST_MAX_SIZE
) {
2623 redisLog(REDIS_VERBOSE
, "Client protocol error");
2628 /* Bulk read handling. Note that if we are at this point
2629 the client already sent a command terminated with a newline,
2630 we are reading the bulk data that is actually the last
2631 argument of the command. */
2632 int qbl
= sdslen(c
->querybuf
);
2634 if (c
->bulklen
<= qbl
) {
2635 /* Copy everything but the final CRLF as final argument */
2636 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2638 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2639 /* Process the command. If the client is still valid after
2640 * the processing and there is more data in the buffer
2641 * try to parse it. */
2642 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2648 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2649 redisClient
*c
= (redisClient
*) privdata
;
2650 char buf
[REDIS_IOBUF_LEN
];
2653 REDIS_NOTUSED(mask
);
2655 nread
= read(fd
, buf
, REDIS_IOBUF_LEN
);
2657 if (errno
== EAGAIN
) {
2660 redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
));
2664 } else if (nread
== 0) {
2665 redisLog(REDIS_VERBOSE
, "Client closed connection");
2670 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
2671 c
->lastinteraction
= time(NULL
);
2675 processInputBuffer(c
);
2678 static int selectDb(redisClient
*c
, int id
) {
2679 if (id
< 0 || id
>= server
.dbnum
)
2681 c
->db
= &server
.db
[id
];
2685 static void *dupClientReplyValue(void *o
) {
2686 incrRefCount((robj
*)o
);
2690 static int listMatchObjects(void *a
, void *b
) {
2691 return equalStringObjects(a
,b
);
2694 static redisClient
*createClient(int fd
) {
2695 redisClient
*c
= zmalloc(sizeof(*c
));
2697 anetNonBlock(NULL
,fd
);
2698 anetTcpNoDelay(NULL
,fd
);
2699 if (!c
) return NULL
;
2702 c
->querybuf
= sdsempty();
2711 c
->lastinteraction
= time(NULL
);
2712 c
->authenticated
= 0;
2713 c
->replstate
= REDIS_REPL_NONE
;
2714 c
->reply
= listCreate();
2715 listSetFreeMethod(c
->reply
,decrRefCount
);
2716 listSetDupMethod(c
->reply
,dupClientReplyValue
);
2717 c
->blockingkeys
= NULL
;
2718 c
->blockingkeysnum
= 0;
2719 c
->io_keys
= listCreate();
2720 listSetFreeMethod(c
->io_keys
,decrRefCount
);
2721 c
->pubsub_channels
= dictCreate(&setDictType
,NULL
);
2722 c
->pubsub_patterns
= listCreate();
2723 listSetFreeMethod(c
->pubsub_patterns
,decrRefCount
);
2724 listSetMatchMethod(c
->pubsub_patterns
,listMatchObjects
);
2725 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
2726 readQueryFromClient
, c
) == AE_ERR
) {
2730 listAddNodeTail(server
.clients
,c
);
2731 initClientMultiState(c
);
2735 static void addReply(redisClient
*c
, robj
*obj
) {
2736 if (listLength(c
->reply
) == 0 &&
2737 (c
->replstate
== REDIS_REPL_NONE
||
2738 c
->replstate
== REDIS_REPL_ONLINE
) &&
2739 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
2740 sendReplyToClient
, c
) == AE_ERR
) return;
2742 if (server
.vm_enabled
&& obj
->storage
!= REDIS_VM_MEMORY
) {
2743 obj
= dupStringObject(obj
);
2744 obj
->refcount
= 0; /* getDecodedObject() will increment the refcount */
2746 listAddNodeTail(c
->reply
,getDecodedObject(obj
));
2749 static void addReplySds(redisClient
*c
, sds s
) {
2750 robj
*o
= createObject(REDIS_STRING
,s
);
2755 static void addReplyDouble(redisClient
*c
, double d
) {
2758 snprintf(buf
,sizeof(buf
),"%.17g",d
);
2759 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
2760 (unsigned long) strlen(buf
),buf
));
2763 static void addReplyLong(redisClient
*c
, long l
) {
2768 addReply(c
,shared
.czero
);
2770 } else if (l
== 1) {
2771 addReply(c
,shared
.cone
);
2774 len
= snprintf(buf
,sizeof(buf
),":%ld\r\n",l
);
2775 addReplySds(c
,sdsnewlen(buf
,len
));
2778 static void addReplyLongLong(redisClient
*c
, long long ll
) {
2783 addReply(c
,shared
.czero
);
2785 } else if (ll
== 1) {
2786 addReply(c
,shared
.cone
);
2789 len
= snprintf(buf
,sizeof(buf
),":%lld\r\n",ll
);
2790 addReplySds(c
,sdsnewlen(buf
,len
));
2793 static void addReplyUlong(redisClient
*c
, unsigned long ul
) {
2798 addReply(c
,shared
.czero
);
2800 } else if (ul
== 1) {
2801 addReply(c
,shared
.cone
);
2804 len
= snprintf(buf
,sizeof(buf
),":%lu\r\n",ul
);
2805 addReplySds(c
,sdsnewlen(buf
,len
));
2808 static void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
2811 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
2812 len
= sdslen(obj
->ptr
);
2814 long n
= (long)obj
->ptr
;
2816 /* Compute how many bytes will take this integer as a radix 10 string */
2822 while((n
= n
/10) != 0) {
2826 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",(unsigned long)len
));
2829 static void addReplyBulk(redisClient
*c
, robj
*obj
) {
2830 addReplyBulkLen(c
,obj
);
2832 addReply(c
,shared
.crlf
);
2835 /* In the CONFIG command we need to add vanilla C string as bulk replies */
2836 static void addReplyBulkCString(redisClient
*c
, char *s
) {
2838 addReply(c
,shared
.nullbulk
);
2840 robj
*o
= createStringObject(s
,strlen(s
));
2846 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2851 REDIS_NOTUSED(mask
);
2852 REDIS_NOTUSED(privdata
);
2854 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
2855 if (cfd
== AE_ERR
) {
2856 redisLog(REDIS_VERBOSE
,"Accepting client connection: %s", server
.neterr
);
2859 redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
);
2860 if ((c
= createClient(cfd
)) == NULL
) {
2861 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
2862 close(cfd
); /* May be already closed, just ingore errors */
2865 /* If maxclient directive is set and this is one client more... close the
2866 * connection. Note that we create the client instead to check before
2867 * for this condition, since now the socket is already set in nonblocking
2868 * mode and we can send an error for free using the Kernel I/O */
2869 if (server
.maxclients
&& listLength(server
.clients
) > server
.maxclients
) {
2870 char *err
= "-ERR max number of clients reached\r\n";
2872 /* That's a best effort error message, don't check write errors */
2873 if (write(c
->fd
,err
,strlen(err
)) == -1) {
2874 /* Nothing to do, Just to avoid the warning... */
2879 server
.stat_numconnections
++;
2882 /* ======================= Redis objects implementation ===================== */
2884 static robj
*createObject(int type
, void *ptr
) {
2887 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
2888 if (listLength(server
.objfreelist
)) {
2889 listNode
*head
= listFirst(server
.objfreelist
);
2890 o
= listNodeValue(head
);
2891 listDelNode(server
.objfreelist
,head
);
2892 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2894 if (server
.vm_enabled
) {
2895 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2896 o
= zmalloc(sizeof(*o
));
2898 o
= zmalloc(sizeof(*o
)-sizeof(struct redisObjectVM
));
2902 o
->encoding
= REDIS_ENCODING_RAW
;
2905 if (server
.vm_enabled
) {
2906 /* Note that this code may run in the context of an I/O thread
2907 * and accessing to server.unixtime in theory is an error
2908 * (no locks). But in practice this is safe, and even if we read
2909 * garbage Redis will not fail, as it's just a statistical info */
2910 o
->vm
.atime
= server
.unixtime
;
2911 o
->storage
= REDIS_VM_MEMORY
;
2916 static robj
*createStringObject(char *ptr
, size_t len
) {
2917 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
2920 static robj
*createStringObjectFromLongLong(long long value
) {
2922 if (value
>= 0 && value
< REDIS_SHARED_INTEGERS
) {
2923 incrRefCount(shared
.integers
[value
]);
2924 o
= shared
.integers
[value
];
2926 o
= createObject(REDIS_STRING
, NULL
);
2927 if (value
>= LONG_MIN
&& value
<= LONG_MAX
) {
2928 o
->encoding
= REDIS_ENCODING_INT
;
2929 o
->ptr
= (void*)((long)value
);
2931 o
= createObject(REDIS_STRING
,sdsfromlonglong(value
));
2937 static robj
*dupStringObject(robj
*o
) {
2938 assert(o
->encoding
== REDIS_ENCODING_RAW
);
2939 return createStringObject(o
->ptr
,sdslen(o
->ptr
));
2942 static robj
*createListObject(void) {
2943 list
*l
= listCreate();
2945 listSetFreeMethod(l
,decrRefCount
);
2946 return createObject(REDIS_LIST
,l
);
2949 static robj
*createSetObject(void) {
2950 dict
*d
= dictCreate(&setDictType
,NULL
);
2951 return createObject(REDIS_SET
,d
);
2954 static robj
*createHashObject(void) {
2955 /* All the Hashes start as zipmaps. Will be automatically converted
2956 * into hash tables if there are enough elements or big elements
2958 unsigned char *zm
= zipmapNew();
2959 robj
*o
= createObject(REDIS_HASH
,zm
);
2960 o
->encoding
= REDIS_ENCODING_ZIPMAP
;
2964 static robj
*createZsetObject(void) {
2965 zset
*zs
= zmalloc(sizeof(*zs
));
2967 zs
->dict
= dictCreate(&zsetDictType
,NULL
);
2968 zs
->zsl
= zslCreate();
2969 return createObject(REDIS_ZSET
,zs
);
2972 static void freeStringObject(robj
*o
) {
2973 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2978 static void freeListObject(robj
*o
) {
2979 listRelease((list
*) o
->ptr
);
2982 static void freeSetObject(robj
*o
) {
2983 dictRelease((dict
*) o
->ptr
);
2986 static void freeZsetObject(robj
*o
) {
2989 dictRelease(zs
->dict
);
2994 static void freeHashObject(robj
*o
) {
2995 switch (o
->encoding
) {
2996 case REDIS_ENCODING_HT
:
2997 dictRelease((dict
*) o
->ptr
);
2999 case REDIS_ENCODING_ZIPMAP
:
3003 redisPanic("Unknown hash encoding type");
3008 static void incrRefCount(robj
*o
) {
3012 static void decrRefCount(void *obj
) {
3015 if (o
->refcount
<= 0) redisPanic("decrRefCount against refcount <= 0");
3016 /* Object is a key of a swapped out value, or in the process of being
3018 if (server
.vm_enabled
&&
3019 (o
->storage
== REDIS_VM_SWAPPED
|| o
->storage
== REDIS_VM_LOADING
))
3021 if (o
->storage
== REDIS_VM_LOADING
) vmCancelThreadedIOJob(obj
);
3022 redisAssert(o
->type
== REDIS_STRING
);
3023 freeStringObject(o
);
3024 vmMarkPagesFree(o
->vm
.page
,o
->vm
.usedpages
);
3025 pthread_mutex_lock(&server
.obj_freelist_mutex
);
3026 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
3027 !listAddNodeHead(server
.objfreelist
,o
))
3029 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
3030 server
.vm_stats_swapped_objects
--;
3033 /* Object is in memory, or in the process of being swapped out. */
3034 if (--(o
->refcount
) == 0) {
3035 if (server
.vm_enabled
&& o
->storage
== REDIS_VM_SWAPPING
)
3036 vmCancelThreadedIOJob(obj
);
3038 case REDIS_STRING
: freeStringObject(o
); break;
3039 case REDIS_LIST
: freeListObject(o
); break;
3040 case REDIS_SET
: freeSetObject(o
); break;
3041 case REDIS_ZSET
: freeZsetObject(o
); break;
3042 case REDIS_HASH
: freeHashObject(o
); break;
3043 default: redisPanic("Unknown object type"); break;
3045 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
3046 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
3047 !listAddNodeHead(server
.objfreelist
,o
))
3049 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
3053 static robj
*lookupKey(redisDb
*db
, robj
*key
) {
3054 dictEntry
*de
= dictFind(db
->dict
,key
);
3056 robj
*key
= dictGetEntryKey(de
);
3057 robj
*val
= dictGetEntryVal(de
);
3059 if (server
.vm_enabled
) {
3060 if (key
->storage
== REDIS_VM_MEMORY
||
3061 key
->storage
== REDIS_VM_SWAPPING
)
3063 /* If we were swapping the object out, stop it, this key
3065 if (key
->storage
== REDIS_VM_SWAPPING
)
3066 vmCancelThreadedIOJob(key
);
3067 /* Update the access time of the key for the aging algorithm. */
3068 key
->vm
.atime
= server
.unixtime
;
3070 int notify
= (key
->storage
== REDIS_VM_LOADING
);
3072 /* Our value was swapped on disk. Bring it at home. */
3073 redisAssert(val
== NULL
);
3074 val
= vmLoadObject(key
);
3075 dictGetEntryVal(de
) = val
;
3077 /* Clients blocked by the VM subsystem may be waiting for
3079 if (notify
) handleClientsBlockedOnSwappedKey(db
,key
);
3088 static robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
3089 expireIfNeeded(db
,key
);
3090 return lookupKey(db
,key
);
3093 static robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
3094 deleteIfVolatile(db
,key
);
3095 return lookupKey(db
,key
);
3098 static robj
*lookupKeyReadOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
3099 robj
*o
= lookupKeyRead(c
->db
, key
);
3100 if (!o
) addReply(c
,reply
);
3104 static robj
*lookupKeyWriteOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
3105 robj
*o
= lookupKeyWrite(c
->db
, key
);
3106 if (!o
) addReply(c
,reply
);
3110 static int checkType(redisClient
*c
, robj
*o
, int type
) {
3111 if (o
->type
!= type
) {
3112 addReply(c
,shared
.wrongtypeerr
);
3118 static int deleteKey(redisDb
*db
, robj
*key
) {
3121 /* We need to protect key from destruction: after the first dictDelete()
3122 * it may happen that 'key' is no longer valid if we don't increment
3123 * it's count. This may happen when we get the object reference directly
3124 * from the hash table with dictRandomKey() or dict iterators */
3126 if (dictSize(db
->expires
)) dictDelete(db
->expires
,key
);
3127 retval
= dictDelete(db
->dict
,key
);
3130 return retval
== DICT_OK
;
3133 /* Check if the nul-terminated string 's' can be represented by a long
3134 * (that is, is a number that fits into long without any other space or
3135 * character before or after the digits).
3137 * If so, the function returns REDIS_OK and *longval is set to the value
3138 * of the number. Otherwise REDIS_ERR is returned */
3139 static int isStringRepresentableAsLong(sds s
, long *longval
) {
3140 char buf
[32], *endptr
;
3144 value
= strtol(s
, &endptr
, 10);
3145 if (endptr
[0] != '\0') return REDIS_ERR
;
3146 slen
= ll2string(buf
,32,value
);
3148 /* If the number converted back into a string is not identical
3149 * then it's not possible to encode the string as integer */
3150 if (sdslen(s
) != (unsigned)slen
|| memcmp(buf
,s
,slen
)) return REDIS_ERR
;
3151 if (longval
) *longval
= value
;
3155 /* Try to encode a string object in order to save space */
3156 static robj
*tryObjectEncoding(robj
*o
) {
3160 if (o
->encoding
!= REDIS_ENCODING_RAW
)
3161 return o
; /* Already encoded */
3163 /* It's not safe to encode shared objects: shared objects can be shared
3164 * everywhere in the "object space" of Redis. Encoded objects can only
3165 * appear as "values" (and not, for instance, as keys) */
3166 if (o
->refcount
> 1) return o
;
3168 /* Currently we try to encode only strings */
3169 redisAssert(o
->type
== REDIS_STRING
);
3171 /* Check if we can represent this string as a long integer */
3172 if (isStringRepresentableAsLong(s
,&value
) == REDIS_ERR
) return o
;
3174 /* Ok, this object can be encoded */
3175 if (value
>= 0 && value
< REDIS_SHARED_INTEGERS
) {
3177 incrRefCount(shared
.integers
[value
]);
3178 return shared
.integers
[value
];
3180 o
->encoding
= REDIS_ENCODING_INT
;
3182 o
->ptr
= (void*) value
;
3187 /* Get a decoded version of an encoded object (returned as a new object).
3188 * If the object is already raw-encoded just increment the ref count. */
3189 static robj
*getDecodedObject(robj
*o
) {
3192 if (o
->encoding
== REDIS_ENCODING_RAW
) {
3196 if (o
->type
== REDIS_STRING
&& o
->encoding
== REDIS_ENCODING_INT
) {
3199 ll2string(buf
,32,(long)o
->ptr
);
3200 dec
= createStringObject(buf
,strlen(buf
));
3203 redisPanic("Unknown encoding type");
3207 /* Compare two string objects via strcmp() or alike.
3208 * Note that the objects may be integer-encoded. In such a case we
3209 * use ll2string() to get a string representation of the numbers on the stack
3210 * and compare the strings, it's much faster than calling getDecodedObject().
3212 * Important note: if objects are not integer encoded, but binary-safe strings,
3213 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
3215 static int compareStringObjects(robj
*a
, robj
*b
) {
3216 redisAssert(a
->type
== REDIS_STRING
&& b
->type
== REDIS_STRING
);
3217 char bufa
[128], bufb
[128], *astr
, *bstr
;
3220 if (a
== b
) return 0;
3221 if (a
->encoding
!= REDIS_ENCODING_RAW
) {
3222 ll2string(bufa
,sizeof(bufa
),(long) a
->ptr
);
3228 if (b
->encoding
!= REDIS_ENCODING_RAW
) {
3229 ll2string(bufb
,sizeof(bufb
),(long) b
->ptr
);
3235 return bothsds
? sdscmp(astr
,bstr
) : strcmp(astr
,bstr
);
3238 /* Equal string objects return 1 if the two objects are the same from the
3239 * point of view of a string comparison, otherwise 0 is returned. Note that
3240 * this function is faster then checking for (compareStringObject(a,b) == 0)
3241 * because it can perform some more optimization. */
3242 static int equalStringObjects(robj
*a
, robj
*b
) {
3243 if (a
->encoding
!= REDIS_ENCODING_RAW
&& b
->encoding
!= REDIS_ENCODING_RAW
){
3244 return a
->ptr
== b
->ptr
;
3246 return compareStringObjects(a
,b
) == 0;
3250 static size_t stringObjectLen(robj
*o
) {
3251 redisAssert(o
->type
== REDIS_STRING
);
3252 if (o
->encoding
== REDIS_ENCODING_RAW
) {
3253 return sdslen(o
->ptr
);
3257 return ll2string(buf
,32,(long)o
->ptr
);
3261 static int getDoubleFromObject(robj
*o
, double *target
) {
3268 redisAssert(o
->type
== REDIS_STRING
);
3269 if (o
->encoding
== REDIS_ENCODING_RAW
) {
3270 value
= strtod(o
->ptr
, &eptr
);
3271 if (eptr
[0] != '\0') return REDIS_ERR
;
3272 } else if (o
->encoding
== REDIS_ENCODING_INT
) {
3273 value
= (long)o
->ptr
;
3275 redisPanic("Unknown string encoding");
3283 static int getDoubleFromObjectOrReply(redisClient
*c
, robj
*o
, double *target
, const char *msg
) {
3285 if (getDoubleFromObject(o
, &value
) != REDIS_OK
) {
3287 addReplySds(c
, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg
));
3289 addReplySds(c
, sdsnew("-ERR value is not a double\r\n"));
3298 static int getLongLongFromObject(robj
*o
, long long *target
) {
3305 redisAssert(o
->type
== REDIS_STRING
);
3306 if (o
->encoding
== REDIS_ENCODING_RAW
) {
3307 value
= strtoll(o
->ptr
, &eptr
, 10);
3308 if (eptr
[0] != '\0') return REDIS_ERR
;
3309 } else if (o
->encoding
== REDIS_ENCODING_INT
) {
3310 value
= (long)o
->ptr
;
3312 redisPanic("Unknown string encoding");
3320 static int getLongLongFromObjectOrReply(redisClient
*c
, robj
*o
, long long *target
, const char *msg
) {
3322 if (getLongLongFromObject(o
, &value
) != REDIS_OK
) {
3324 addReplySds(c
, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg
));
3326 addReplySds(c
, sdsnew("-ERR value is not an integer\r\n"));
3335 static int getLongFromObjectOrReply(redisClient
*c
, robj
*o
, long *target
, const char *msg
) {
3338 if (getLongLongFromObjectOrReply(c
, o
, &value
, msg
) != REDIS_OK
) return REDIS_ERR
;
3339 if (value
< LONG_MIN
|| value
> LONG_MAX
) {
3341 addReplySds(c
, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg
));
3343 addReplySds(c
, sdsnew("-ERR value is out of range\r\n"));
3352 /*============================ RDB saving/loading =========================== */
3354 static int rdbSaveType(FILE *fp
, unsigned char type
) {
3355 if (fwrite(&type
,1,1,fp
) == 0) return -1;
3359 static int rdbSaveTime(FILE *fp
, time_t t
) {
3360 int32_t t32
= (int32_t) t
;
3361 if (fwrite(&t32
,4,1,fp
) == 0) return -1;
3365 /* check rdbLoadLen() comments for more info */
3366 static int rdbSaveLen(FILE *fp
, uint32_t len
) {
3367 unsigned char buf
[2];
3370 /* Save a 6 bit len */
3371 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
3372 if (fwrite(buf
,1,1,fp
) == 0) return -1;
3373 } else if (len
< (1<<14)) {
3374 /* Save a 14 bit len */
3375 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
3377 if (fwrite(buf
,2,1,fp
) == 0) return -1;
3379 /* Save a 32 bit len */
3380 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
3381 if (fwrite(buf
,1,1,fp
) == 0) return -1;
3383 if (fwrite(&len
,4,1,fp
) == 0) return -1;
3388 /* Encode 'value' as an integer if possible (if integer will fit the
3389 * supported range). If the function sucessful encoded the integer
3390 * then the (up to 5 bytes) encoded representation is written in the
3391 * string pointed by 'enc' and the length is returned. Otherwise
3393 static int rdbEncodeInteger(long long value
, unsigned char *enc
) {
3394 /* Finally check if it fits in our ranges */
3395 if (value
>= -(1<<7) && value
<= (1<<7)-1) {
3396 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT8
;
3397 enc
[1] = value
&0xFF;
3399 } else if (value
>= -(1<<15) && value
<= (1<<15)-1) {
3400 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
;
3401 enc
[1] = value
&0xFF;
3402 enc
[2] = (value
>>8)&0xFF;
3404 } else if (value
>= -((long long)1<<31) && value
<= ((long long)1<<31)-1) {
3405 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT32
;
3406 enc
[1] = value
&0xFF;
3407 enc
[2] = (value
>>8)&0xFF;
3408 enc
[3] = (value
>>16)&0xFF;
3409 enc
[4] = (value
>>24)&0xFF;
3416 /* String objects in the form "2391" "-100" without any space and with a
3417 * range of values that can fit in an 8, 16 or 32 bit signed value can be
3418 * encoded as integers to save space */
3419 static int rdbTryIntegerEncoding(char *s
, size_t len
, unsigned char *enc
) {
3421 char *endptr
, buf
[32];
3423 /* Check if it's possible to encode this value as a number */
3424 value
= strtoll(s
, &endptr
, 10);
3425 if (endptr
[0] != '\0') return 0;
3426 ll2string(buf
,32,value
);
3428 /* If the number converted back into a string is not identical
3429 * then it's not possible to encode the string as integer */
3430 if (strlen(buf
) != len
|| memcmp(buf
,s
,len
)) return 0;
3432 return rdbEncodeInteger(value
,enc
);
3435 static int rdbSaveLzfStringObject(FILE *fp
, unsigned char *s
, size_t len
) {
3436 size_t comprlen
, outlen
;
3440 /* We require at least four bytes compression for this to be worth it */
3441 if (len
<= 4) return 0;
3443 if ((out
= zmalloc(outlen
+1)) == NULL
) return 0;
3444 comprlen
= lzf_compress(s
, len
, out
, outlen
);
3445 if (comprlen
== 0) {
3449 /* Data compressed! Let's save it on disk */
3450 byte
= (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_LZF
;
3451 if (fwrite(&byte
,1,1,fp
) == 0) goto writeerr
;
3452 if (rdbSaveLen(fp
,comprlen
) == -1) goto writeerr
;
3453 if (rdbSaveLen(fp
,len
) == -1) goto writeerr
;
3454 if (fwrite(out
,comprlen
,1,fp
) == 0) goto writeerr
;
3463 /* Save a string objet as [len][data] on disk. If the object is a string
3464 * representation of an integer value we try to safe it in a special form */
3465 static int rdbSaveRawString(FILE *fp
, unsigned char *s
, size_t len
) {
3468 /* Try integer encoding */
3470 unsigned char buf
[5];
3471 if ((enclen
= rdbTryIntegerEncoding((char*)s
,len
,buf
)) > 0) {
3472 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
3477 /* Try LZF compression - under 20 bytes it's unable to compress even
3478 * aaaaaaaaaaaaaaaaaa so skip it */
3479 if (server
.rdbcompression
&& len
> 20) {
3482 retval
= rdbSaveLzfStringObject(fp
,s
,len
);
3483 if (retval
== -1) return -1;
3484 if (retval
> 0) return 0;
3485 /* retval == 0 means data can't be compressed, save the old way */
3488 /* Store verbatim */
3489 if (rdbSaveLen(fp
,len
) == -1) return -1;
3490 if (len
&& fwrite(s
,len
,1,fp
) == 0) return -1;
3494 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
3495 static int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
3498 /* Avoid to decode the object, then encode it again, if the
3499 * object is alrady integer encoded. */
3500 if (obj
->encoding
== REDIS_ENCODING_INT
) {
3501 long val
= (long) obj
->ptr
;
3502 unsigned char buf
[5];
3505 if ((enclen
= rdbEncodeInteger(val
,buf
)) > 0) {
3506 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
3509 /* otherwise... fall throught and continue with the usual
3513 /* Avoid incr/decr ref count business when possible.
3514 * This plays well with copy-on-write given that we are probably
3515 * in a child process (BGSAVE). Also this makes sure key objects
3516 * of swapped objects are not incRefCount-ed (an assert does not allow
3517 * this in order to avoid bugs) */
3518 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
3519 obj
= getDecodedObject(obj
);
3520 retval
= rdbSaveRawString(fp
,obj
->ptr
,sdslen(obj
->ptr
));
3523 retval
= rdbSaveRawString(fp
,obj
->ptr
,sdslen(obj
->ptr
));
3528 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
3529 * 8 bit integer specifing the length of the representation.
3530 * This 8 bit integer has special values in order to specify the following
3536 static int rdbSaveDoubleValue(FILE *fp
, double val
) {
3537 unsigned char buf
[128];
3543 } else if (!isfinite(val
)) {
3545 buf
[0] = (val
< 0) ? 255 : 254;
3547 #if (DBL_MANT_DIG >= 52) && (LLONG_MAX == 0x7fffffffffffffffLL)
3548 /* Check if the float is in a safe range to be casted into a
3549 * long long. We are assuming that long long is 64 bit here.
3550 * Also we are assuming that there are no implementations around where
3551 * double has precision < 52 bit.
3553 * Under this assumptions we test if a double is inside an interval
3554 * where casting to long long is safe. Then using two castings we
3555 * make sure the decimal part is zero. If all this is true we use
3556 * integer printing function that is much faster. */
3557 double min
= -4503599627370495; /* (2^52)-1 */
3558 double max
= 4503599627370496; /* -(2^52) */
3559 if (val
> min
&& val
< max
&& val
== ((double)((long long)val
)))
3560 ll2string((char*)buf
+1,sizeof(buf
),(long long)val
);
3563 snprintf((char*)buf
+1,sizeof(buf
)-1,"%.17g",val
);
3564 buf
[0] = strlen((char*)buf
+1);
3567 if (fwrite(buf
,len
,1,fp
) == 0) return -1;
3571 /* Save a Redis object. */
3572 static int rdbSaveObject(FILE *fp
, robj
*o
) {
3573 if (o
->type
== REDIS_STRING
) {
3574 /* Save a string value */
3575 if (rdbSaveStringObject(fp
,o
) == -1) return -1;
3576 } else if (o
->type
== REDIS_LIST
) {
3577 /* Save a list value */
3578 list
*list
= o
->ptr
;
3582 if (rdbSaveLen(fp
,listLength(list
)) == -1) return -1;
3583 listRewind(list
,&li
);
3584 while((ln
= listNext(&li
))) {
3585 robj
*eleobj
= listNodeValue(ln
);
3587 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
3589 } else if (o
->type
== REDIS_SET
) {
3590 /* Save a set value */
3592 dictIterator
*di
= dictGetIterator(set
);
3595 if (rdbSaveLen(fp
,dictSize(set
)) == -1) return -1;
3596 while((de
= dictNext(di
)) != NULL
) {
3597 robj
*eleobj
= dictGetEntryKey(de
);
3599 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
3601 dictReleaseIterator(di
);
3602 } else if (o
->type
== REDIS_ZSET
) {
3603 /* Save a set value */
3605 dictIterator
*di
= dictGetIterator(zs
->dict
);
3608 if (rdbSaveLen(fp
,dictSize(zs
->dict
)) == -1) return -1;
3609 while((de
= dictNext(di
)) != NULL
) {
3610 robj
*eleobj
= dictGetEntryKey(de
);
3611 double *score
= dictGetEntryVal(de
);
3613 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
3614 if (rdbSaveDoubleValue(fp
,*score
) == -1) return -1;
3616 dictReleaseIterator(di
);
3617 } else if (o
->type
== REDIS_HASH
) {
3618 /* Save a hash value */
3619 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
3620 unsigned char *p
= zipmapRewind(o
->ptr
);
3621 unsigned int count
= zipmapLen(o
->ptr
);
3622 unsigned char *key
, *val
;
3623 unsigned int klen
, vlen
;
3625 if (rdbSaveLen(fp
,count
) == -1) return -1;
3626 while((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) != NULL
) {
3627 if (rdbSaveRawString(fp
,key
,klen
) == -1) return -1;
3628 if (rdbSaveRawString(fp
,val
,vlen
) == -1) return -1;
3631 dictIterator
*di
= dictGetIterator(o
->ptr
);
3634 if (rdbSaveLen(fp
,dictSize((dict
*)o
->ptr
)) == -1) return -1;
3635 while((de
= dictNext(di
)) != NULL
) {
3636 robj
*key
= dictGetEntryKey(de
);
3637 robj
*val
= dictGetEntryVal(de
);
3639 if (rdbSaveStringObject(fp
,key
) == -1) return -1;
3640 if (rdbSaveStringObject(fp
,val
) == -1) return -1;
3642 dictReleaseIterator(di
);
3645 redisPanic("Unknown object type");
3650 /* Return the length the object will have on disk if saved with
3651 * the rdbSaveObject() function. Currently we use a trick to get
3652 * this length with very little changes to the code. In the future
3653 * we could switch to a faster solution. */
3654 static off_t
rdbSavedObjectLen(robj
*o
, FILE *fp
) {
3655 if (fp
== NULL
) fp
= server
.devnull
;
3657 assert(rdbSaveObject(fp
,o
) != 1);
3661 /* Return the number of pages required to save this object in the swap file */
3662 static off_t
rdbSavedObjectPages(robj
*o
, FILE *fp
) {
3663 off_t bytes
= rdbSavedObjectLen(o
,fp
);
3665 return (bytes
+(server
.vm_page_size
-1))/server
.vm_page_size
;
3668 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
3669 static int rdbSave(char *filename
) {
3670 dictIterator
*di
= NULL
;
3675 time_t now
= time(NULL
);
3677 /* Wait for I/O therads to terminate, just in case this is a
3678 * foreground-saving, to avoid seeking the swap file descriptor at the
3680 if (server
.vm_enabled
)
3681 waitEmptyIOJobsQueue();
3683 snprintf(tmpfile
,256,"temp-%d.rdb", (int) getpid());
3684 fp
= fopen(tmpfile
,"w");
3686 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
3689 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
3690 for (j
= 0; j
< server
.dbnum
; j
++) {
3691 redisDb
*db
= server
.db
+j
;
3693 if (dictSize(d
) == 0) continue;
3694 di
= dictGetIterator(d
);
3700 /* Write the SELECT DB opcode */
3701 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
3702 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
3704 /* Iterate this DB writing every entry */
3705 while((de
= dictNext(di
)) != NULL
) {
3706 robj
*key
= dictGetEntryKey(de
);
3707 robj
*o
= dictGetEntryVal(de
);
3708 time_t expiretime
= getExpire(db
,key
);
3710 /* Save the expire time */
3711 if (expiretime
!= -1) {
3712 /* If this key is already expired skip it */
3713 if (expiretime
< now
) continue;
3714 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
;
3715 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
;
3717 /* Save the key and associated value. This requires special
3718 * handling if the value is swapped out. */
3719 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
3720 key
->storage
== REDIS_VM_SWAPPING
) {
3721 /* Save type, key, value */
3722 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
3723 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3724 if (rdbSaveObject(fp
,o
) == -1) goto werr
;
3726 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
3728 /* Get a preview of the object in memory */
3729 po
= vmPreviewObject(key
);
3730 /* Save type, key, value */
3731 if (rdbSaveType(fp
,key
->vtype
) == -1) goto werr
;
3732 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3733 if (rdbSaveObject(fp
,po
) == -1) goto werr
;
3734 /* Remove the loaded object from memory */
3738 dictReleaseIterator(di
);
3741 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
3743 /* Make sure data will not remain on the OS's output buffers */
3748 /* Use RENAME to make sure the DB file is changed atomically only
3749 * if the generate DB file is ok. */
3750 if (rename(tmpfile
,filename
) == -1) {
3751 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destination: %s", strerror(errno
));
3755 redisLog(REDIS_NOTICE
,"DB saved on disk");
3757 server
.lastsave
= time(NULL
);
3763 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
3764 if (di
) dictReleaseIterator(di
);
3768 static int rdbSaveBackground(char *filename
) {
3771 if (server
.bgsavechildpid
!= -1) return REDIS_ERR
;
3772 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
3773 if ((childpid
= fork()) == 0) {
3775 if (server
.vm_enabled
) vmReopenSwapFile();
3777 if (rdbSave(filename
) == REDIS_OK
) {
3784 if (childpid
== -1) {
3785 redisLog(REDIS_WARNING
,"Can't save in background: fork: %s",
3789 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
3790 server
.bgsavechildpid
= childpid
;
3791 updateDictResizePolicy();
3794 return REDIS_OK
; /* unreached */
3797 static void rdbRemoveTempFile(pid_t childpid
) {
3800 snprintf(tmpfile
,256,"temp-%d.rdb", (int) childpid
);
3804 static int rdbLoadType(FILE *fp
) {
3806 if (fread(&type
,1,1,fp
) == 0) return -1;
3810 static time_t rdbLoadTime(FILE *fp
) {
3812 if (fread(&t32
,4,1,fp
) == 0) return -1;
3813 return (time_t) t32
;
3816 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
3817 * of this file for a description of how this are stored on disk.
3819 * isencoded is set to 1 if the readed length is not actually a length but
3820 * an "encoding type", check the above comments for more info */
3821 static uint32_t rdbLoadLen(FILE *fp
, int *isencoded
) {
3822 unsigned char buf
[2];
3826 if (isencoded
) *isencoded
= 0;
3827 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3828 type
= (buf
[0]&0xC0)>>6;
3829 if (type
== REDIS_RDB_6BITLEN
) {
3830 /* Read a 6 bit len */
3832 } else if (type
== REDIS_RDB_ENCVAL
) {
3833 /* Read a 6 bit len encoding type */
3834 if (isencoded
) *isencoded
= 1;
3836 } else if (type
== REDIS_RDB_14BITLEN
) {
3837 /* Read a 14 bit len */
3838 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3839 return ((buf
[0]&0x3F)<<8)|buf
[1];
3841 /* Read a 32 bit len */
3842 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
3847 /* Load an integer-encoded object from file 'fp', with the specified
3848 * encoding type 'enctype'. If encode is true the function may return
3849 * an integer-encoded object as reply, otherwise the returned object
3850 * will always be encoded as a raw string. */
3851 static robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
, int encode
) {
3852 unsigned char enc
[4];
3855 if (enctype
== REDIS_RDB_ENC_INT8
) {
3856 if (fread(enc
,1,1,fp
) == 0) return NULL
;
3857 val
= (signed char)enc
[0];
3858 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
3860 if (fread(enc
,2,1,fp
) == 0) return NULL
;
3861 v
= enc
[0]|(enc
[1]<<8);
3863 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
3865 if (fread(enc
,4,1,fp
) == 0) return NULL
;
3866 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
3869 val
= 0; /* anti-warning */
3870 redisPanic("Unknown RDB integer encoding type");
3873 return createStringObjectFromLongLong(val
);
3875 return createObject(REDIS_STRING
,sdsfromlonglong(val
));
3878 static robj
*rdbLoadLzfStringObject(FILE*fp
) {
3879 unsigned int len
, clen
;
3880 unsigned char *c
= NULL
;
3883 if ((clen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3884 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3885 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
3886 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
3887 if (fread(c
,clen
,1,fp
) == 0) goto err
;
3888 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
3890 return createObject(REDIS_STRING
,val
);
3897 static robj
*rdbGenericLoadStringObject(FILE*fp
, int encode
) {
3902 len
= rdbLoadLen(fp
,&isencoded
);
3905 case REDIS_RDB_ENC_INT8
:
3906 case REDIS_RDB_ENC_INT16
:
3907 case REDIS_RDB_ENC_INT32
:
3908 return rdbLoadIntegerObject(fp
,len
,encode
);
3909 case REDIS_RDB_ENC_LZF
:
3910 return rdbLoadLzfStringObject(fp
);
3912 redisPanic("Unknown RDB encoding type");
3916 if (len
== REDIS_RDB_LENERR
) return NULL
;
3917 val
= sdsnewlen(NULL
,len
);
3918 if (len
&& fread(val
,len
,1,fp
) == 0) {
3922 return createObject(REDIS_STRING
,val
);
3925 static robj
*rdbLoadStringObject(FILE *fp
) {
3926 return rdbGenericLoadStringObject(fp
,0);
3929 static robj
*rdbLoadEncodedStringObject(FILE *fp
) {
3930 return rdbGenericLoadStringObject(fp
,1);
3933 /* For information about double serialization check rdbSaveDoubleValue() */
3934 static int rdbLoadDoubleValue(FILE *fp
, double *val
) {
3938 if (fread(&len
,1,1,fp
) == 0) return -1;
3940 case 255: *val
= R_NegInf
; return 0;
3941 case 254: *val
= R_PosInf
; return 0;
3942 case 253: *val
= R_Nan
; return 0;
3944 if (fread(buf
,len
,1,fp
) == 0) return -1;
3946 sscanf(buf
, "%lg", val
);
3951 /* Load a Redis object of the specified type from the specified file.
3952 * On success a newly allocated object is returned, otherwise NULL. */
3953 static robj
*rdbLoadObject(int type
, FILE *fp
) {
3956 redisLog(REDIS_DEBUG
,"LOADING OBJECT %d (at %d)\n",type
,ftell(fp
));
3957 if (type
== REDIS_STRING
) {
3958 /* Read string value */
3959 if ((o
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
3960 o
= tryObjectEncoding(o
);
3961 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
3962 /* Read list/set value */
3965 if ((listlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3966 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
3967 /* It's faster to expand the dict to the right size asap in order
3968 * to avoid rehashing */
3969 if (type
== REDIS_SET
&& listlen
> DICT_HT_INITIAL_SIZE
)
3970 dictExpand(o
->ptr
,listlen
);
3971 /* Load every single element of the list/set */
3975 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
3976 ele
= tryObjectEncoding(ele
);
3977 if (type
== REDIS_LIST
) {
3978 listAddNodeTail((list
*)o
->ptr
,ele
);
3980 dictAdd((dict
*)o
->ptr
,ele
,NULL
);
3983 } else if (type
== REDIS_ZSET
) {
3984 /* Read list/set value */
3988 if ((zsetlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3989 o
= createZsetObject();
3991 /* Load every single element of the list/set */
3994 double *score
= zmalloc(sizeof(double));
3996 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
3997 ele
= tryObjectEncoding(ele
);
3998 if (rdbLoadDoubleValue(fp
,score
) == -1) return NULL
;
3999 dictAdd(zs
->dict
,ele
,score
);
4000 zslInsert(zs
->zsl
,*score
,ele
);
4001 incrRefCount(ele
); /* added to skiplist */
4003 } else if (type
== REDIS_HASH
) {
4006 if ((hashlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
4007 o
= createHashObject();
4008 /* Too many entries? Use an hash table. */
4009 if (hashlen
> server
.hash_max_zipmap_entries
)
4010 convertToRealHash(o
);
4011 /* Load every key/value, then set it into the zipmap or hash
4012 * table, as needed. */
4016 if ((key
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
4017 if ((val
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
4018 /* If we are using a zipmap and there are too big values
4019 * the object is converted to real hash table encoding. */
4020 if (o
->encoding
!= REDIS_ENCODING_HT
&&
4021 (sdslen(key
->ptr
) > server
.hash_max_zipmap_value
||
4022 sdslen(val
->ptr
) > server
.hash_max_zipmap_value
))
4024 convertToRealHash(o
);
4027 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
4028 unsigned char *zm
= o
->ptr
;
4030 zm
= zipmapSet(zm
,key
->ptr
,sdslen(key
->ptr
),
4031 val
->ptr
,sdslen(val
->ptr
),NULL
);
4036 key
= tryObjectEncoding(key
);
4037 val
= tryObjectEncoding(val
);
4038 dictAdd((dict
*)o
->ptr
,key
,val
);
4042 redisPanic("Unknown object type");
4047 static int rdbLoad(char *filename
) {
4050 int type
, retval
, rdbver
;
4051 int swap_all_values
= 0;
4052 dict
*d
= server
.db
[0].dict
;
4053 redisDb
*db
= server
.db
+0;
4055 time_t expiretime
, now
= time(NULL
);
4056 long long loadedkeys
= 0;
4058 fp
= fopen(filename
,"r");
4059 if (!fp
) return REDIS_ERR
;
4060 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
4062 if (memcmp(buf
,"REDIS",5) != 0) {
4064 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
4067 rdbver
= atoi(buf
+5);
4070 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
4078 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
4079 if (type
== REDIS_EXPIRETIME
) {
4080 if ((expiretime
= rdbLoadTime(fp
)) == -1) goto eoferr
;
4081 /* We read the time so we need to read the object type again */
4082 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
4084 if (type
== REDIS_EOF
) break;
4085 /* Handle SELECT DB opcode as a special case */
4086 if (type
== REDIS_SELECTDB
) {
4087 if ((dbid
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
)
4089 if (dbid
>= (unsigned)server
.dbnum
) {
4090 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
4093 db
= server
.db
+dbid
;
4098 if ((key
= rdbLoadStringObject(fp
)) == NULL
) goto eoferr
;
4100 if ((val
= rdbLoadObject(type
,fp
)) == NULL
) goto eoferr
;
4101 /* Check if the key already expired */
4102 if (expiretime
!= -1 && expiretime
< now
) {
4107 /* Add the new object in the hash table */
4108 retval
= dictAdd(d
,key
,val
);
4109 if (retval
== DICT_ERR
) {
4110 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key
->ptr
);
4114 /* Set the expire time if needed */
4115 if (expiretime
!= -1) setExpire(db
,key
,expiretime
);
4117 /* Handle swapping while loading big datasets when VM is on */
4119 /* If we detecter we are hopeless about fitting something in memory
4120 * we just swap every new key on disk. Directly...
4121 * Note that's important to check for this condition before resorting
4122 * to random sampling, otherwise we may try to swap already
4124 if (swap_all_values
) {
4125 dictEntry
*de
= dictFind(d
,key
);
4127 /* de may be NULL since the key already expired */
4129 key
= dictGetEntryKey(de
);
4130 val
= dictGetEntryVal(de
);
4132 if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
4133 dictGetEntryVal(de
) = NULL
;
4139 /* If we have still some hope of having some value fitting memory
4140 * then we try random sampling. */
4141 if (!swap_all_values
&& server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
4142 while (zmalloc_used_memory() > server
.vm_max_memory
) {
4143 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
4145 if (zmalloc_used_memory() > server
.vm_max_memory
)
4146 swap_all_values
= 1; /* We are already using too much mem */
4152 eoferr
: /* unexpected end of file is handled here with a fatal exit */
4153 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
4155 return REDIS_ERR
; /* Just to avoid warning */
4158 /*================================== Commands =============================== */
4160 static void authCommand(redisClient
*c
) {
4161 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
4162 c
->authenticated
= 1;
4163 addReply(c
,shared
.ok
);
4165 c
->authenticated
= 0;
4166 addReplySds(c
,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
4170 static void pingCommand(redisClient
*c
) {
4171 addReply(c
,shared
.pong
);
4174 static void echoCommand(redisClient
*c
) {
4175 addReplyBulk(c
,c
->argv
[1]);
4178 /*=================================== Strings =============================== */
4180 static void setGenericCommand(redisClient
*c
, int nx
, robj
*key
, robj
*val
, robj
*expire
) {
4182 long seconds
= 0; /* initialized to avoid an harmness warning */
4185 if (getLongFromObjectOrReply(c
, expire
, &seconds
, NULL
) != REDIS_OK
)
4188 addReplySds(c
,sdsnew("-ERR invalid expire time in SETEX\r\n"));
4193 if (nx
) deleteIfVolatile(c
->db
,key
);
4194 retval
= dictAdd(c
->db
->dict
,key
,val
);
4195 if (retval
== DICT_ERR
) {
4197 /* If the key is about a swapped value, we want a new key object
4198 * to overwrite the old. So we delete the old key in the database.
4199 * This will also make sure that swap pages about the old object
4200 * will be marked as free. */
4201 if (server
.vm_enabled
&& deleteIfSwapped(c
->db
,key
))
4203 dictReplace(c
->db
->dict
,key
,val
);
4206 addReply(c
,shared
.czero
);
4214 removeExpire(c
->db
,key
);
4215 if (expire
) setExpire(c
->db
,key
,time(NULL
)+seconds
);
4216 addReply(c
, nx
? shared
.cone
: shared
.ok
);
4219 static void setCommand(redisClient
*c
) {
4220 setGenericCommand(c
,0,c
->argv
[1],c
->argv
[2],NULL
);
4223 static void setnxCommand(redisClient
*c
) {
4224 setGenericCommand(c
,1,c
->argv
[1],c
->argv
[2],NULL
);
4227 static void setexCommand(redisClient
*c
) {
4228 setGenericCommand(c
,0,c
->argv
[1],c
->argv
[3],c
->argv
[2]);
4231 static int getGenericCommand(redisClient
*c
) {
4234 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
)
4237 if (o
->type
!= REDIS_STRING
) {
4238 addReply(c
,shared
.wrongtypeerr
);
4246 static void getCommand(redisClient
*c
) {
4247 getGenericCommand(c
);
4250 static void getsetCommand(redisClient
*c
) {
4251 if (getGenericCommand(c
) == REDIS_ERR
) return;
4252 if (dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]) == DICT_ERR
) {
4253 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
4255 incrRefCount(c
->argv
[1]);
4257 incrRefCount(c
->argv
[2]);
4259 removeExpire(c
->db
,c
->argv
[1]);
4262 static void mgetCommand(redisClient
*c
) {
4265 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
4266 for (j
= 1; j
< c
->argc
; j
++) {
4267 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[j
]);
4269 addReply(c
,shared
.nullbulk
);
4271 if (o
->type
!= REDIS_STRING
) {
4272 addReply(c
,shared
.nullbulk
);
4280 static void msetGenericCommand(redisClient
*c
, int nx
) {
4281 int j
, busykeys
= 0;
4283 if ((c
->argc
% 2) == 0) {
4284 addReplySds(c
,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
4287 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
4288 * set nothing at all if at least one already key exists. */
4290 for (j
= 1; j
< c
->argc
; j
+= 2) {
4291 if (lookupKeyWrite(c
->db
,c
->argv
[j
]) != NULL
) {
4297 addReply(c
, shared
.czero
);
4301 for (j
= 1; j
< c
->argc
; j
+= 2) {
4304 c
->argv
[j
+1] = tryObjectEncoding(c
->argv
[j
+1]);
4305 retval
= dictAdd(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
4306 if (retval
== DICT_ERR
) {
4307 dictReplace(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
4308 incrRefCount(c
->argv
[j
+1]);
4310 incrRefCount(c
->argv
[j
]);
4311 incrRefCount(c
->argv
[j
+1]);
4313 removeExpire(c
->db
,c
->argv
[j
]);
4315 server
.dirty
+= (c
->argc
-1)/2;
4316 addReply(c
, nx
? shared
.cone
: shared
.ok
);
4319 static void msetCommand(redisClient
*c
) {
4320 msetGenericCommand(c
,0);
4323 static void msetnxCommand(redisClient
*c
) {
4324 msetGenericCommand(c
,1);
4327 static void incrDecrCommand(redisClient
*c
, long long incr
) {
4332 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4333 if (o
!= NULL
&& checkType(c
,o
,REDIS_STRING
)) return;
4334 if (getLongLongFromObjectOrReply(c
,o
,&value
,NULL
) != REDIS_OK
) return;
4337 o
= createStringObjectFromLongLong(value
);
4338 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],o
);
4339 if (retval
== DICT_ERR
) {
4340 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
4341 removeExpire(c
->db
,c
->argv
[1]);
4343 incrRefCount(c
->argv
[1]);
4346 addReply(c
,shared
.colon
);
4348 addReply(c
,shared
.crlf
);
4351 static void incrCommand(redisClient
*c
) {
4352 incrDecrCommand(c
,1);
4355 static void decrCommand(redisClient
*c
) {
4356 incrDecrCommand(c
,-1);
4359 static void incrbyCommand(redisClient
*c
) {
4362 if (getLongLongFromObjectOrReply(c
, c
->argv
[2], &incr
, NULL
) != REDIS_OK
) return;
4363 incrDecrCommand(c
,incr
);
4366 static void decrbyCommand(redisClient
*c
) {
4369 if (getLongLongFromObjectOrReply(c
, c
->argv
[2], &incr
, NULL
) != REDIS_OK
) return;
4370 incrDecrCommand(c
,-incr
);
4373 static void appendCommand(redisClient
*c
) {
4378 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4380 /* Create the key */
4381 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
4382 incrRefCount(c
->argv
[1]);
4383 incrRefCount(c
->argv
[2]);
4384 totlen
= stringObjectLen(c
->argv
[2]);
4388 de
= dictFind(c
->db
->dict
,c
->argv
[1]);
4391 o
= dictGetEntryVal(de
);
4392 if (o
->type
!= REDIS_STRING
) {
4393 addReply(c
,shared
.wrongtypeerr
);
4396 /* If the object is specially encoded or shared we have to make
4398 if (o
->refcount
!= 1 || o
->encoding
!= REDIS_ENCODING_RAW
) {
4399 robj
*decoded
= getDecodedObject(o
);
4401 o
= createStringObject(decoded
->ptr
, sdslen(decoded
->ptr
));
4402 decrRefCount(decoded
);
4403 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
4406 if (c
->argv
[2]->encoding
== REDIS_ENCODING_RAW
) {
4407 o
->ptr
= sdscatlen(o
->ptr
,
4408 c
->argv
[2]->ptr
, sdslen(c
->argv
[2]->ptr
));
4410 o
->ptr
= sdscatprintf(o
->ptr
, "%ld",
4411 (unsigned long) c
->argv
[2]->ptr
);
4413 totlen
= sdslen(o
->ptr
);
4416 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",(unsigned long)totlen
));
4419 static void substrCommand(redisClient
*c
) {
4421 long start
= atoi(c
->argv
[2]->ptr
);
4422 long end
= atoi(c
->argv
[3]->ptr
);
4423 size_t rangelen
, strlen
;
4426 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
4427 checkType(c
,o
,REDIS_STRING
)) return;
4429 o
= getDecodedObject(o
);
4430 strlen
= sdslen(o
->ptr
);
4432 /* convert negative indexes */
4433 if (start
< 0) start
= strlen
+start
;
4434 if (end
< 0) end
= strlen
+end
;
4435 if (start
< 0) start
= 0;
4436 if (end
< 0) end
= 0;
4438 /* indexes sanity checks */
4439 if (start
> end
|| (size_t)start
>= strlen
) {
4440 /* Out of range start or start > end result in null reply */
4441 addReply(c
,shared
.nullbulk
);
4445 if ((size_t)end
>= strlen
) end
= strlen
-1;
4446 rangelen
= (end
-start
)+1;
4448 /* Return the result */
4449 addReplySds(c
,sdscatprintf(sdsempty(),"$%zu\r\n",rangelen
));
4450 range
= sdsnewlen((char*)o
->ptr
+start
,rangelen
);
4451 addReplySds(c
,range
);
4452 addReply(c
,shared
.crlf
);
4456 /* ========================= Type agnostic commands ========================= */
4458 static void delCommand(redisClient
*c
) {
4461 for (j
= 1; j
< c
->argc
; j
++) {
4462 if (deleteKey(c
->db
,c
->argv
[j
])) {
4467 addReplyLong(c
,deleted
);
4470 static void existsCommand(redisClient
*c
) {
4471 expireIfNeeded(c
->db
,c
->argv
[1]);
4472 if (dictFind(c
->db
->dict
,c
->argv
[1])) {
4473 addReply(c
, shared
.cone
);
4475 addReply(c
, shared
.czero
);
4479 static void selectCommand(redisClient
*c
) {
4480 int id
= atoi(c
->argv
[1]->ptr
);
4482 if (selectDb(c
,id
) == REDIS_ERR
) {
4483 addReplySds(c
,sdsnew("-ERR invalid DB index\r\n"));
4485 addReply(c
,shared
.ok
);
4489 static void randomkeyCommand(redisClient
*c
) {
4494 de
= dictGetRandomKey(c
->db
->dict
);
4495 if (!de
|| expireIfNeeded(c
->db
,dictGetEntryKey(de
)) == 0) break;
4499 addReply(c
,shared
.nullbulk
);
4503 key
= dictGetEntryKey(de
);
4504 if (server
.vm_enabled
) {
4505 key
= dupStringObject(key
);
4506 addReplyBulk(c
,key
);
4509 addReplyBulk(c
,key
);
4513 static void keysCommand(redisClient
*c
) {
4516 sds pattern
= c
->argv
[1]->ptr
;
4517 int plen
= sdslen(pattern
);
4518 unsigned long numkeys
= 0;
4519 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
4521 di
= dictGetIterator(c
->db
->dict
);
4523 decrRefCount(lenobj
);
4524 while((de
= dictNext(di
)) != NULL
) {
4525 robj
*keyobj
= dictGetEntryKey(de
);
4527 sds key
= keyobj
->ptr
;
4528 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
4529 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
4530 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
4531 addReplyBulk(c
,keyobj
);
4536 dictReleaseIterator(di
);
4537 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",numkeys
);
4540 static void dbsizeCommand(redisClient
*c
) {
4542 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c
->db
->dict
)));
4545 static void lastsaveCommand(redisClient
*c
) {
4547 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
4550 static void typeCommand(redisClient
*c
) {
4554 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4559 case REDIS_STRING
: type
= "+string"; break;
4560 case REDIS_LIST
: type
= "+list"; break;
4561 case REDIS_SET
: type
= "+set"; break;
4562 case REDIS_ZSET
: type
= "+zset"; break;
4563 case REDIS_HASH
: type
= "+hash"; break;
4564 default: type
= "+unknown"; break;
4567 addReplySds(c
,sdsnew(type
));
4568 addReply(c
,shared
.crlf
);
4571 static void saveCommand(redisClient
*c
) {
4572 if (server
.bgsavechildpid
!= -1) {
4573 addReplySds(c
,sdsnew("-ERR background save in progress\r\n"));
4576 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
4577 addReply(c
,shared
.ok
);
4579 addReply(c
,shared
.err
);
4583 static void bgsaveCommand(redisClient
*c
) {
4584 if (server
.bgsavechildpid
!= -1) {
4585 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
4588 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
4589 char *status
= "+Background saving started\r\n";
4590 addReplySds(c
,sdsnew(status
));
4592 addReply(c
,shared
.err
);
4596 static void shutdownCommand(redisClient
*c
) {
4597 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
4598 /* Kill the saving child if there is a background saving in progress.
4599 We want to avoid race conditions, for instance our saving child may
4600 overwrite the synchronous saving did by SHUTDOWN. */
4601 if (server
.bgsavechildpid
!= -1) {
4602 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
4603 kill(server
.bgsavechildpid
,SIGKILL
);
4604 rdbRemoveTempFile(server
.bgsavechildpid
);
4606 if (server
.appendonly
) {
4607 /* Append only file: fsync() the AOF and exit */
4608 fsync(server
.appendfd
);
4609 if (server
.vm_enabled
) unlink(server
.vm_swap_file
);
4612 /* Snapshotting. Perform a SYNC SAVE and exit */
4613 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
4614 if (server
.daemonize
)
4615 unlink(server
.pidfile
);
4616 redisLog(REDIS_WARNING
,"%zu bytes used at exit",zmalloc_used_memory());
4617 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
4620 /* Ooops.. error saving! The best we can do is to continue
4621 * operating. Note that if there was a background saving process,
4622 * in the next cron() Redis will be notified that the background
4623 * saving aborted, handling special stuff like slaves pending for
4624 * synchronization... */
4625 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
4627 sdsnew("-ERR can't quit, problems saving the DB\r\n"));
4632 static void renameGenericCommand(redisClient
*c
, int nx
) {
4635 /* To use the same key as src and dst is probably an error */
4636 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
4637 addReply(c
,shared
.sameobjecterr
);
4641 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
)
4645 deleteIfVolatile(c
->db
,c
->argv
[2]);
4646 if (dictAdd(c
->db
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
4649 addReply(c
,shared
.czero
);
4652 dictReplace(c
->db
->dict
,c
->argv
[2],o
);
4654 incrRefCount(c
->argv
[2]);
4656 deleteKey(c
->db
,c
->argv
[1]);
4658 addReply(c
,nx
? shared
.cone
: shared
.ok
);
4661 static void renameCommand(redisClient
*c
) {
4662 renameGenericCommand(c
,0);
4665 static void renamenxCommand(redisClient
*c
) {
4666 renameGenericCommand(c
,1);
4669 static void moveCommand(redisClient
*c
) {
4674 /* Obtain source and target DB pointers */
4677 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
4678 addReply(c
,shared
.outofrangeerr
);
4682 selectDb(c
,srcid
); /* Back to the source DB */
4684 /* If the user is moving using as target the same
4685 * DB as the source DB it is probably an error. */
4687 addReply(c
,shared
.sameobjecterr
);
4691 /* Check if the element exists and get a reference */
4692 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4694 addReply(c
,shared
.czero
);
4698 /* Try to add the element to the target DB */
4699 deleteIfVolatile(dst
,c
->argv
[1]);
4700 if (dictAdd(dst
->dict
,c
->argv
[1],o
) == DICT_ERR
) {
4701 addReply(c
,shared
.czero
);
4704 incrRefCount(c
->argv
[1]);
4707 /* OK! key moved, free the entry in the source DB */
4708 deleteKey(src
,c
->argv
[1]);
4710 addReply(c
,shared
.cone
);
4713 /* =================================== Lists ================================ */
4714 static void pushGenericCommand(redisClient
*c
, int where
) {
4718 lobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4720 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
4721 addReply(c
,shared
.cone
);
4724 lobj
= createListObject();
4726 if (where
== REDIS_HEAD
) {
4727 listAddNodeHead(list
,c
->argv
[2]);
4729 listAddNodeTail(list
,c
->argv
[2]);
4731 dictAdd(c
->db
->dict
,c
->argv
[1],lobj
);
4732 incrRefCount(c
->argv
[1]);
4733 incrRefCount(c
->argv
[2]);
4735 if (lobj
->type
!= REDIS_LIST
) {
4736 addReply(c
,shared
.wrongtypeerr
);
4739 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
4740 addReply(c
,shared
.cone
);
4744 if (where
== REDIS_HEAD
) {
4745 listAddNodeHead(list
,c
->argv
[2]);
4747 listAddNodeTail(list
,c
->argv
[2]);
4749 incrRefCount(c
->argv
[2]);
4752 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(list
)));
4755 static void lpushCommand(redisClient
*c
) {
4756 pushGenericCommand(c
,REDIS_HEAD
);
4759 static void rpushCommand(redisClient
*c
) {
4760 pushGenericCommand(c
,REDIS_TAIL
);
4763 static void llenCommand(redisClient
*c
) {
4767 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
4768 checkType(c
,o
,REDIS_LIST
)) return;
4771 addReplyUlong(c
,listLength(l
));
4774 static void lindexCommand(redisClient
*c
) {
4776 int index
= atoi(c
->argv
[2]->ptr
);
4780 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
4781 checkType(c
,o
,REDIS_LIST
)) return;
4784 ln
= listIndex(list
, index
);
4786 addReply(c
,shared
.nullbulk
);
4788 robj
*ele
= listNodeValue(ln
);
4789 addReplyBulk(c
,ele
);
4793 static void lsetCommand(redisClient
*c
) {
4795 int index
= atoi(c
->argv
[2]->ptr
);
4799 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
||
4800 checkType(c
,o
,REDIS_LIST
)) return;
4803 ln
= listIndex(list
, index
);
4805 addReply(c
,shared
.outofrangeerr
);
4807 robj
*ele
= listNodeValue(ln
);
4810 listNodeValue(ln
) = c
->argv
[3];
4811 incrRefCount(c
->argv
[3]);
4812 addReply(c
,shared
.ok
);
4817 static void popGenericCommand(redisClient
*c
, int where
) {
4822 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
4823 checkType(c
,o
,REDIS_LIST
)) return;
4826 if (where
== REDIS_HEAD
)
4827 ln
= listFirst(list
);
4829 ln
= listLast(list
);
4832 addReply(c
,shared
.nullbulk
);
4834 robj
*ele
= listNodeValue(ln
);
4835 addReplyBulk(c
,ele
);
4836 listDelNode(list
,ln
);
4837 if (listLength(list
) == 0) deleteKey(c
->db
,c
->argv
[1]);
4842 static void lpopCommand(redisClient
*c
) {
4843 popGenericCommand(c
,REDIS_HEAD
);
4846 static void rpopCommand(redisClient
*c
) {
4847 popGenericCommand(c
,REDIS_TAIL
);
4850 static void lrangeCommand(redisClient
*c
) {
4852 int start
= atoi(c
->argv
[2]->ptr
);
4853 int end
= atoi(c
->argv
[3]->ptr
);
4860 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.emptymultibulk
)) == NULL
4861 || checkType(c
,o
,REDIS_LIST
)) return;
4863 llen
= listLength(list
);
4865 /* convert negative indexes */
4866 if (start
< 0) start
= llen
+start
;
4867 if (end
< 0) end
= llen
+end
;
4868 if (start
< 0) start
= 0;
4869 if (end
< 0) end
= 0;
4871 /* indexes sanity checks */
4872 if (start
> end
|| start
>= llen
) {
4873 /* Out of range start or start > end result in empty list */
4874 addReply(c
,shared
.emptymultibulk
);
4877 if (end
>= llen
) end
= llen
-1;
4878 rangelen
= (end
-start
)+1;
4880 /* Return the result in form of a multi-bulk reply */
4881 ln
= listIndex(list
, start
);
4882 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
4883 for (j
= 0; j
< rangelen
; j
++) {
4884 ele
= listNodeValue(ln
);
4885 addReplyBulk(c
,ele
);
4890 static void ltrimCommand(redisClient
*c
) {
4892 int start
= atoi(c
->argv
[2]->ptr
);
4893 int end
= atoi(c
->argv
[3]->ptr
);
4895 int j
, ltrim
, rtrim
;
4899 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.ok
)) == NULL
||
4900 checkType(c
,o
,REDIS_LIST
)) return;
4902 llen
= listLength(list
);
4904 /* convert negative indexes */
4905 if (start
< 0) start
= llen
+start
;
4906 if (end
< 0) end
= llen
+end
;
4907 if (start
< 0) start
= 0;
4908 if (end
< 0) end
= 0;
4910 /* indexes sanity checks */
4911 if (start
> end
|| start
>= llen
) {
4912 /* Out of range start or start > end result in empty list */
4916 if (end
>= llen
) end
= llen
-1;
4921 /* Remove list elements to perform the trim */
4922 for (j
= 0; j
< ltrim
; j
++) {
4923 ln
= listFirst(list
);
4924 listDelNode(list
,ln
);
4926 for (j
= 0; j
< rtrim
; j
++) {
4927 ln
= listLast(list
);
4928 listDelNode(list
,ln
);
4930 if (listLength(list
) == 0) deleteKey(c
->db
,c
->argv
[1]);
4932 addReply(c
,shared
.ok
);
4935 static void lremCommand(redisClient
*c
) {
4938 listNode
*ln
, *next
;
4939 int toremove
= atoi(c
->argv
[2]->ptr
);
4943 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
4944 checkType(c
,o
,REDIS_LIST
)) return;
4948 toremove
= -toremove
;
4951 ln
= fromtail
? list
->tail
: list
->head
;
4953 robj
*ele
= listNodeValue(ln
);
4955 next
= fromtail
? ln
->prev
: ln
->next
;
4956 if (equalStringObjects(ele
,c
->argv
[3])) {
4957 listDelNode(list
,ln
);
4960 if (toremove
&& removed
== toremove
) break;
4964 if (listLength(list
) == 0) deleteKey(c
->db
,c
->argv
[1]);
4965 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
4968 /* This is the semantic of this command:
4969 * RPOPLPUSH srclist dstlist:
4970 * IF LLEN(srclist) > 0
4971 * element = RPOP srclist
4972 * LPUSH dstlist element
4979 * The idea is to be able to get an element from a list in a reliable way
4980 * since the element is not just returned but pushed against another list
4981 * as well. This command was originally proposed by Ezra Zygmuntowicz.
4983 static void rpoplpushcommand(redisClient
*c
) {
4988 if ((sobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
4989 checkType(c
,sobj
,REDIS_LIST
)) return;
4990 srclist
= sobj
->ptr
;
4991 ln
= listLast(srclist
);
4994 addReply(c
,shared
.nullbulk
);
4996 robj
*dobj
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4997 robj
*ele
= listNodeValue(ln
);
5000 if (dobj
&& dobj
->type
!= REDIS_LIST
) {
5001 addReply(c
,shared
.wrongtypeerr
);
5005 /* Add the element to the target list (unless it's directly
5006 * passed to some BLPOP-ing client */
5007 if (!handleClientsWaitingListPush(c
,c
->argv
[2],ele
)) {
5009 /* Create the list if the key does not exist */
5010 dobj
= createListObject();
5011 dictAdd(c
->db
->dict
,c
->argv
[2],dobj
);
5012 incrRefCount(c
->argv
[2]);
5014 dstlist
= dobj
->ptr
;
5015 listAddNodeHead(dstlist
,ele
);
5019 /* Send the element to the client as reply as well */
5020 addReplyBulk(c
,ele
);
5022 /* Finally remove the element from the source list */
5023 listDelNode(srclist
,ln
);
5024 if (listLength(srclist
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5029 /* ==================================== Sets ================================ */
5031 static void saddCommand(redisClient
*c
) {
5034 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
5036 set
= createSetObject();
5037 dictAdd(c
->db
->dict
,c
->argv
[1],set
);
5038 incrRefCount(c
->argv
[1]);
5040 if (set
->type
!= REDIS_SET
) {
5041 addReply(c
,shared
.wrongtypeerr
);
5045 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
5046 incrRefCount(c
->argv
[2]);
5048 addReply(c
,shared
.cone
);
5050 addReply(c
,shared
.czero
);
5054 static void sremCommand(redisClient
*c
) {
5057 if ((set
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5058 checkType(c
,set
,REDIS_SET
)) return;
5060 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
5062 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
5063 if (dictSize((dict
*)set
->ptr
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5064 addReply(c
,shared
.cone
);
5066 addReply(c
,shared
.czero
);
5070 static void smoveCommand(redisClient
*c
) {
5071 robj
*srcset
, *dstset
;
5073 srcset
= lookupKeyWrite(c
->db
,c
->argv
[1]);
5074 dstset
= lookupKeyWrite(c
->db
,c
->argv
[2]);
5076 /* If the source key does not exist return 0, if it's of the wrong type
5078 if (srcset
== NULL
|| srcset
->type
!= REDIS_SET
) {
5079 addReply(c
, srcset
? shared
.wrongtypeerr
: shared
.czero
);
5082 /* Error if the destination key is not a set as well */
5083 if (dstset
&& dstset
->type
!= REDIS_SET
) {
5084 addReply(c
,shared
.wrongtypeerr
);
5087 /* Remove the element from the source set */
5088 if (dictDelete(srcset
->ptr
,c
->argv
[3]) == DICT_ERR
) {
5089 /* Key not found in the src set! return zero */
5090 addReply(c
,shared
.czero
);
5093 if (dictSize((dict
*)srcset
->ptr
) == 0 && srcset
!= dstset
)
5094 deleteKey(c
->db
,c
->argv
[1]);
5096 /* Add the element to the destination set */
5098 dstset
= createSetObject();
5099 dictAdd(c
->db
->dict
,c
->argv
[2],dstset
);
5100 incrRefCount(c
->argv
[2]);
5102 if (dictAdd(dstset
->ptr
,c
->argv
[3],NULL
) == DICT_OK
)
5103 incrRefCount(c
->argv
[3]);
5104 addReply(c
,shared
.cone
);
5107 static void sismemberCommand(redisClient
*c
) {
5110 if ((set
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5111 checkType(c
,set
,REDIS_SET
)) return;
5113 if (dictFind(set
->ptr
,c
->argv
[2]))
5114 addReply(c
,shared
.cone
);
5116 addReply(c
,shared
.czero
);
5119 static void scardCommand(redisClient
*c
) {
5123 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5124 checkType(c
,o
,REDIS_SET
)) return;
5127 addReplyUlong(c
,dictSize(s
));
5130 static void spopCommand(redisClient
*c
) {
5134 if ((set
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
5135 checkType(c
,set
,REDIS_SET
)) return;
5137 de
= dictGetRandomKey(set
->ptr
);
5139 addReply(c
,shared
.nullbulk
);
5141 robj
*ele
= dictGetEntryKey(de
);
5143 addReplyBulk(c
,ele
);
5144 dictDelete(set
->ptr
,ele
);
5145 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
5146 if (dictSize((dict
*)set
->ptr
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5151 static void srandmemberCommand(redisClient
*c
) {
5155 if ((set
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
5156 checkType(c
,set
,REDIS_SET
)) return;
5158 de
= dictGetRandomKey(set
->ptr
);
5160 addReply(c
,shared
.nullbulk
);
5162 robj
*ele
= dictGetEntryKey(de
);
5164 addReplyBulk(c
,ele
);
5168 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
5169 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
5171 return dictSize(*d1
)-dictSize(*d2
);
5174 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, unsigned long setsnum
, robj
*dstkey
) {
5175 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
5178 robj
*lenobj
= NULL
, *dstset
= NULL
;
5179 unsigned long j
, cardinality
= 0;
5181 for (j
= 0; j
< setsnum
; j
++) {
5185 lookupKeyWrite(c
->db
,setskeys
[j
]) :
5186 lookupKeyRead(c
->db
,setskeys
[j
]);
5190 if (deleteKey(c
->db
,dstkey
))
5192 addReply(c
,shared
.czero
);
5194 addReply(c
,shared
.emptymultibulk
);
5198 if (setobj
->type
!= REDIS_SET
) {
5200 addReply(c
,shared
.wrongtypeerr
);
5203 dv
[j
] = setobj
->ptr
;
5205 /* Sort sets from the smallest to largest, this will improve our
5206 * algorithm's performace */
5207 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
5209 /* The first thing we should output is the total number of elements...
5210 * since this is a multi-bulk write, but at this stage we don't know
5211 * the intersection set size, so we use a trick, append an empty object
5212 * to the output list and save the pointer to later modify it with the
5215 lenobj
= createObject(REDIS_STRING
,NULL
);
5217 decrRefCount(lenobj
);
5219 /* If we have a target key where to store the resulting set
5220 * create this key with an empty set inside */
5221 dstset
= createSetObject();
5224 /* Iterate all the elements of the first (smallest) set, and test
5225 * the element against all the other sets, if at least one set does
5226 * not include the element it is discarded */
5227 di
= dictGetIterator(dv
[0]);
5229 while((de
= dictNext(di
)) != NULL
) {
5232 for (j
= 1; j
< setsnum
; j
++)
5233 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
5235 continue; /* at least one set does not contain the member */
5236 ele
= dictGetEntryKey(de
);
5238 addReplyBulk(c
,ele
);
5241 dictAdd(dstset
->ptr
,ele
,NULL
);
5245 dictReleaseIterator(di
);
5248 /* Store the resulting set into the target, if the intersection
5249 * is not an empty set. */
5250 deleteKey(c
->db
,dstkey
);
5251 if (dictSize((dict
*)dstset
->ptr
) > 0) {
5252 dictAdd(c
->db
->dict
,dstkey
,dstset
);
5253 incrRefCount(dstkey
);
5254 addReplyLong(c
,dictSize((dict
*)dstset
->ptr
));
5256 decrRefCount(dstset
);
5257 addReply(c
,shared
.czero
);
5261 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",cardinality
);
5266 static void sinterCommand(redisClient
*c
) {
5267 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
5270 static void sinterstoreCommand(redisClient
*c
) {
5271 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
5274 #define REDIS_OP_UNION 0
5275 #define REDIS_OP_DIFF 1
5276 #define REDIS_OP_INTER 2
5278 static void sunionDiffGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
, int op
) {
5279 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
5282 robj
*dstset
= NULL
;
5283 int j
, cardinality
= 0;
5285 for (j
= 0; j
< setsnum
; j
++) {
5289 lookupKeyWrite(c
->db
,setskeys
[j
]) :
5290 lookupKeyRead(c
->db
,setskeys
[j
]);
5295 if (setobj
->type
!= REDIS_SET
) {
5297 addReply(c
,shared
.wrongtypeerr
);
5300 dv
[j
] = setobj
->ptr
;
5303 /* We need a temp set object to store our union. If the dstkey
5304 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
5305 * this set object will be the resulting object to set into the target key*/
5306 dstset
= createSetObject();
5308 /* Iterate all the elements of all the sets, add every element a single
5309 * time to the result set */
5310 for (j
= 0; j
< setsnum
; j
++) {
5311 if (op
== REDIS_OP_DIFF
&& j
== 0 && !dv
[j
]) break; /* result set is empty */
5312 if (!dv
[j
]) continue; /* non existing keys are like empty sets */
5314 di
= dictGetIterator(dv
[j
]);
5316 while((de
= dictNext(di
)) != NULL
) {
5319 /* dictAdd will not add the same element multiple times */
5320 ele
= dictGetEntryKey(de
);
5321 if (op
== REDIS_OP_UNION
|| j
== 0) {
5322 if (dictAdd(dstset
->ptr
,ele
,NULL
) == DICT_OK
) {
5326 } else if (op
== REDIS_OP_DIFF
) {
5327 if (dictDelete(dstset
->ptr
,ele
) == DICT_OK
) {
5332 dictReleaseIterator(di
);
5334 /* result set is empty? Exit asap. */
5335 if (op
== REDIS_OP_DIFF
&& cardinality
== 0) break;
5338 /* Output the content of the resulting set, if not in STORE mode */
5340 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",cardinality
));
5341 di
= dictGetIterator(dstset
->ptr
);
5342 while((de
= dictNext(di
)) != NULL
) {
5345 ele
= dictGetEntryKey(de
);
5346 addReplyBulk(c
,ele
);
5348 dictReleaseIterator(di
);
5349 decrRefCount(dstset
);
5351 /* If we have a target key where to store the resulting set
5352 * create this key with the result set inside */
5353 deleteKey(c
->db
,dstkey
);
5354 if (dictSize((dict
*)dstset
->ptr
) > 0) {
5355 dictAdd(c
->db
->dict
,dstkey
,dstset
);
5356 incrRefCount(dstkey
);
5357 addReplyLong(c
,dictSize((dict
*)dstset
->ptr
));
5359 decrRefCount(dstset
);
5360 addReply(c
,shared
.czero
);
5367 static void sunionCommand(redisClient
*c
) {
5368 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_UNION
);
5371 static void sunionstoreCommand(redisClient
*c
) {
5372 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_UNION
);
5375 static void sdiffCommand(redisClient
*c
) {
5376 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_DIFF
);
5379 static void sdiffstoreCommand(redisClient
*c
) {
5380 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_DIFF
);
5383 /* ==================================== ZSets =============================== */
5385 /* ZSETs are ordered sets using two data structures to hold the same elements
5386 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
5389 * The elements are added to an hash table mapping Redis objects to scores.
5390 * At the same time the elements are added to a skip list mapping scores
5391 * to Redis objects (so objects are sorted by scores in this "view"). */
5393 /* This skiplist implementation is almost a C translation of the original
5394 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
5395 * Alternative to Balanced Trees", modified in three ways:
5396 * a) this implementation allows for repeated values.
5397 * b) the comparison is not just by key (our 'score') but by satellite data.
5398 * c) there is a back pointer, so it's a doubly linked list with the back
5399 * pointers being only at "level 1". This allows to traverse the list
5400 * from tail to head, useful for ZREVRANGE. */
5402 static zskiplistNode
*zslCreateNode(int level
, double score
, robj
*obj
) {
5403 zskiplistNode
*zn
= zmalloc(sizeof(*zn
));
5405 zn
->forward
= zmalloc(sizeof(zskiplistNode
*) * level
);
5407 zn
->span
= zmalloc(sizeof(unsigned int) * (level
- 1));
5413 static zskiplist
*zslCreate(void) {
5417 zsl
= zmalloc(sizeof(*zsl
));
5420 zsl
->header
= zslCreateNode(ZSKIPLIST_MAXLEVEL
,0,NULL
);
5421 for (j
= 0; j
< ZSKIPLIST_MAXLEVEL
; j
++) {
5422 zsl
->header
->forward
[j
] = NULL
;
5424 /* span has space for ZSKIPLIST_MAXLEVEL-1 elements */
5425 if (j
< ZSKIPLIST_MAXLEVEL
-1)
5426 zsl
->header
->span
[j
] = 0;
5428 zsl
->header
->backward
= NULL
;
5433 static void zslFreeNode(zskiplistNode
*node
) {
5434 decrRefCount(node
->obj
);
5435 zfree(node
->forward
);
5440 static void zslFree(zskiplist
*zsl
) {
5441 zskiplistNode
*node
= zsl
->header
->forward
[0], *next
;
5443 zfree(zsl
->header
->forward
);
5444 zfree(zsl
->header
->span
);
5447 next
= node
->forward
[0];
5454 static int zslRandomLevel(void) {
5456 while ((random()&0xFFFF) < (ZSKIPLIST_P
* 0xFFFF))
5458 return (level
<ZSKIPLIST_MAXLEVEL
) ? level
: ZSKIPLIST_MAXLEVEL
;
5461 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
) {
5462 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5463 unsigned int rank
[ZSKIPLIST_MAXLEVEL
];
5467 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5468 /* store rank that is crossed to reach the insert position */
5469 rank
[i
] = i
== (zsl
->level
-1) ? 0 : rank
[i
+1];
5471 while (x
->forward
[i
] &&
5472 (x
->forward
[i
]->score
< score
||
5473 (x
->forward
[i
]->score
== score
&&
5474 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0))) {
5475 rank
[i
] += i
> 0 ? x
->span
[i
-1] : 1;
5480 /* we assume the key is not already inside, since we allow duplicated
5481 * scores, and the re-insertion of score and redis object should never
5482 * happpen since the caller of zslInsert() should test in the hash table
5483 * if the element is already inside or not. */
5484 level
= zslRandomLevel();
5485 if (level
> zsl
->level
) {
5486 for (i
= zsl
->level
; i
< level
; i
++) {
5488 update
[i
] = zsl
->header
;
5489 update
[i
]->span
[i
-1] = zsl
->length
;
5493 x
= zslCreateNode(level
,score
,obj
);
5494 for (i
= 0; i
< level
; i
++) {
5495 x
->forward
[i
] = update
[i
]->forward
[i
];
5496 update
[i
]->forward
[i
] = x
;
5498 /* update span covered by update[i] as x is inserted here */
5500 x
->span
[i
-1] = update
[i
]->span
[i
-1] - (rank
[0] - rank
[i
]);
5501 update
[i
]->span
[i
-1] = (rank
[0] - rank
[i
]) + 1;
5505 /* increment span for untouched levels */
5506 for (i
= level
; i
< zsl
->level
; i
++) {
5507 update
[i
]->span
[i
-1]++;
5510 x
->backward
= (update
[0] == zsl
->header
) ? NULL
: update
[0];
5512 x
->forward
[0]->backward
= x
;
5518 /* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
5519 void zslDeleteNode(zskiplist
*zsl
, zskiplistNode
*x
, zskiplistNode
**update
) {
5521 for (i
= 0; i
< zsl
->level
; i
++) {
5522 if (update
[i
]->forward
[i
] == x
) {
5524 update
[i
]->span
[i
-1] += x
->span
[i
-1] - 1;
5526 update
[i
]->forward
[i
] = x
->forward
[i
];
5528 /* invariant: i > 0, because update[0]->forward[0]
5529 * is always equal to x */
5530 update
[i
]->span
[i
-1] -= 1;
5533 if (x
->forward
[0]) {
5534 x
->forward
[0]->backward
= x
->backward
;
5536 zsl
->tail
= x
->backward
;
5538 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
5543 /* Delete an element with matching score/object from the skiplist. */
5544 static int zslDelete(zskiplist
*zsl
, double score
, robj
*obj
) {
5545 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5549 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5550 while (x
->forward
[i
] &&
5551 (x
->forward
[i
]->score
< score
||
5552 (x
->forward
[i
]->score
== score
&&
5553 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
5557 /* We may have multiple elements with the same score, what we need
5558 * is to find the element with both the right score and object. */
5560 if (x
&& score
== x
->score
&& equalStringObjects(x
->obj
,obj
)) {
5561 zslDeleteNode(zsl
, x
, update
);
5565 return 0; /* not found */
5567 return 0; /* not found */
5570 /* Delete all the elements with score between min and max from the skiplist.
5571 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
5572 * Note that this function takes the reference to the hash table view of the
5573 * sorted set, in order to remove the elements from the hash table too. */
5574 static unsigned long zslDeleteRangeByScore(zskiplist
*zsl
, double min
, double max
, dict
*dict
) {
5575 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5576 unsigned long removed
= 0;
5580 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5581 while (x
->forward
[i
] && x
->forward
[i
]->score
< min
)
5585 /* We may have multiple elements with the same score, what we need
5586 * is to find the element with both the right score and object. */
5588 while (x
&& x
->score
<= max
) {
5589 zskiplistNode
*next
= x
->forward
[0];
5590 zslDeleteNode(zsl
, x
, update
);
5591 dictDelete(dict
,x
->obj
);
5596 return removed
; /* not found */
5599 /* Delete all the elements with rank between start and end from the skiplist.
5600 * Start and end are inclusive. Note that start and end need to be 1-based */
5601 static unsigned long zslDeleteRangeByRank(zskiplist
*zsl
, unsigned int start
, unsigned int end
, dict
*dict
) {
5602 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5603 unsigned long traversed
= 0, removed
= 0;
5607 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5608 while (x
->forward
[i
] && (traversed
+ (i
> 0 ? x
->span
[i
-1] : 1)) < start
) {
5609 traversed
+= i
> 0 ? x
->span
[i
-1] : 1;
5617 while (x
&& traversed
<= end
) {
5618 zskiplistNode
*next
= x
->forward
[0];
5619 zslDeleteNode(zsl
, x
, update
);
5620 dictDelete(dict
,x
->obj
);
5629 /* Find the first node having a score equal or greater than the specified one.
5630 * Returns NULL if there is no match. */
5631 static zskiplistNode
*zslFirstWithScore(zskiplist
*zsl
, double score
) {
5636 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5637 while (x
->forward
[i
] && x
->forward
[i
]->score
< score
)
5640 /* We may have multiple elements with the same score, what we need
5641 * is to find the element with both the right score and object. */
5642 return x
->forward
[0];
5645 /* Find the rank for an element by both score and key.
5646 * Returns 0 when the element cannot be found, rank otherwise.
5647 * Note that the rank is 1-based due to the span of zsl->header to the
5649 static unsigned long zslGetRank(zskiplist
*zsl
, double score
, robj
*o
) {
5651 unsigned long rank
= 0;
5655 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5656 while (x
->forward
[i
] &&
5657 (x
->forward
[i
]->score
< score
||
5658 (x
->forward
[i
]->score
== score
&&
5659 compareStringObjects(x
->forward
[i
]->obj
,o
) <= 0))) {
5660 rank
+= i
> 0 ? x
->span
[i
-1] : 1;
5664 /* x might be equal to zsl->header, so test if obj is non-NULL */
5665 if (x
->obj
&& equalStringObjects(x
->obj
,o
)) {
5672 /* Finds an element by its rank. The rank argument needs to be 1-based. */
5673 zskiplistNode
* zslGetElementByRank(zskiplist
*zsl
, unsigned long rank
) {
5675 unsigned long traversed
= 0;
5679 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5680 while (x
->forward
[i
] && (traversed
+ (i
>0 ? x
->span
[i
-1] : 1)) <= rank
)
5682 traversed
+= i
> 0 ? x
->span
[i
-1] : 1;
5685 if (traversed
== rank
) {
5692 /* The actual Z-commands implementations */
5694 /* This generic command implements both ZADD and ZINCRBY.
5695 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
5696 * the increment if the operation is a ZINCRBY (doincrement == 1). */
5697 static void zaddGenericCommand(redisClient
*c
, robj
*key
, robj
*ele
, double scoreval
, int doincrement
) {
5702 zsetobj
= lookupKeyWrite(c
->db
,key
);
5703 if (zsetobj
== NULL
) {
5704 zsetobj
= createZsetObject();
5705 dictAdd(c
->db
->dict
,key
,zsetobj
);
5708 if (zsetobj
->type
!= REDIS_ZSET
) {
5709 addReply(c
,shared
.wrongtypeerr
);
5715 /* Ok now since we implement both ZADD and ZINCRBY here the code
5716 * needs to handle the two different conditions. It's all about setting
5717 * '*score', that is, the new score to set, to the right value. */
5718 score
= zmalloc(sizeof(double));
5722 /* Read the old score. If the element was not present starts from 0 */
5723 de
= dictFind(zs
->dict
,ele
);
5725 double *oldscore
= dictGetEntryVal(de
);
5726 *score
= *oldscore
+ scoreval
;
5734 /* What follows is a simple remove and re-insert operation that is common
5735 * to both ZADD and ZINCRBY... */
5736 if (dictAdd(zs
->dict
,ele
,score
) == DICT_OK
) {
5737 /* case 1: New element */
5738 incrRefCount(ele
); /* added to hash */
5739 zslInsert(zs
->zsl
,*score
,ele
);
5740 incrRefCount(ele
); /* added to skiplist */
5743 addReplyDouble(c
,*score
);
5745 addReply(c
,shared
.cone
);
5750 /* case 2: Score update operation */
5751 de
= dictFind(zs
->dict
,ele
);
5752 redisAssert(de
!= NULL
);
5753 oldscore
= dictGetEntryVal(de
);
5754 if (*score
!= *oldscore
) {
5757 /* Remove and insert the element in the skip list with new score */
5758 deleted
= zslDelete(zs
->zsl
,*oldscore
,ele
);
5759 redisAssert(deleted
!= 0);
5760 zslInsert(zs
->zsl
,*score
,ele
);
5762 /* Update the score in the hash table */
5763 dictReplace(zs
->dict
,ele
,score
);
5769 addReplyDouble(c
,*score
);
5771 addReply(c
,shared
.czero
);
5775 static void zaddCommand(redisClient
*c
) {
5778 if (getDoubleFromObjectOrReply(c
, c
->argv
[2], &scoreval
, NULL
) != REDIS_OK
) return;
5779 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,0);
5782 static void zincrbyCommand(redisClient
*c
) {
5785 if (getDoubleFromObjectOrReply(c
, c
->argv
[2], &scoreval
, NULL
) != REDIS_OK
) return;
5786 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,1);
5789 static void zremCommand(redisClient
*c
) {
5796 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5797 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
5800 de
= dictFind(zs
->dict
,c
->argv
[2]);
5802 addReply(c
,shared
.czero
);
5805 /* Delete from the skiplist */
5806 oldscore
= dictGetEntryVal(de
);
5807 deleted
= zslDelete(zs
->zsl
,*oldscore
,c
->argv
[2]);
5808 redisAssert(deleted
!= 0);
5810 /* Delete from the hash table */
5811 dictDelete(zs
->dict
,c
->argv
[2]);
5812 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
5813 if (dictSize(zs
->dict
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5815 addReply(c
,shared
.cone
);
5818 static void zremrangebyscoreCommand(redisClient
*c
) {
5825 if ((getDoubleFromObjectOrReply(c
, c
->argv
[2], &min
, NULL
) != REDIS_OK
) ||
5826 (getDoubleFromObjectOrReply(c
, c
->argv
[3], &max
, NULL
) != REDIS_OK
)) return;
5828 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5829 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
5832 deleted
= zslDeleteRangeByScore(zs
->zsl
,min
,max
,zs
->dict
);
5833 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
5834 if (dictSize(zs
->dict
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5835 server
.dirty
+= deleted
;
5836 addReplyLong(c
,deleted
);
5839 static void zremrangebyrankCommand(redisClient
*c
) {
5847 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
5848 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
5850 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5851 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
5853 llen
= zs
->zsl
->length
;
5855 /* convert negative indexes */
5856 if (start
< 0) start
= llen
+start
;
5857 if (end
< 0) end
= llen
+end
;
5858 if (start
< 0) start
= 0;
5859 if (end
< 0) end
= 0;
5861 /* indexes sanity checks */
5862 if (start
> end
|| start
>= llen
) {
5863 addReply(c
,shared
.czero
);
5866 if (end
>= llen
) end
= llen
-1;
5868 /* increment start and end because zsl*Rank functions
5869 * use 1-based rank */
5870 deleted
= zslDeleteRangeByRank(zs
->zsl
,start
+1,end
+1,zs
->dict
);
5871 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
5872 if (dictSize(zs
->dict
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5873 server
.dirty
+= deleted
;
5874 addReplyLong(c
, deleted
);
5882 static int qsortCompareZsetopsrcByCardinality(const void *s1
, const void *s2
) {
5883 zsetopsrc
*d1
= (void*) s1
, *d2
= (void*) s2
;
5884 unsigned long size1
, size2
;
5885 size1
= d1
->dict
? dictSize(d1
->dict
) : 0;
5886 size2
= d2
->dict
? dictSize(d2
->dict
) : 0;
5887 return size1
- size2
;
5890 #define REDIS_AGGR_SUM 1
5891 #define REDIS_AGGR_MIN 2
5892 #define REDIS_AGGR_MAX 3
5894 inline static void zunionInterAggregate(double *target
, double val
, int aggregate
) {
5895 if (aggregate
== REDIS_AGGR_SUM
) {
5896 *target
= *target
+ val
;
5897 } else if (aggregate
== REDIS_AGGR_MIN
) {
5898 *target
= val
< *target
? val
: *target
;
5899 } else if (aggregate
== REDIS_AGGR_MAX
) {
5900 *target
= val
> *target
? val
: *target
;
5903 redisPanic("Unknown ZUNION/INTER aggregate type");
5907 static void zunionInterGenericCommand(redisClient
*c
, robj
*dstkey
, int op
) {
5909 int aggregate
= REDIS_AGGR_SUM
;
5916 /* expect zsetnum input keys to be given */
5917 zsetnum
= atoi(c
->argv
[2]->ptr
);
5919 addReplySds(c
,sdsnew("-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE\r\n"));
5923 /* test if the expected number of keys would overflow */
5924 if (3+zsetnum
> c
->argc
) {
5925 addReply(c
,shared
.syntaxerr
);
5929 /* read keys to be used for input */
5930 src
= zmalloc(sizeof(zsetopsrc
) * zsetnum
);
5931 for (i
= 0, j
= 3; i
< zsetnum
; i
++, j
++) {
5932 robj
*zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
5936 if (zsetobj
->type
!= REDIS_ZSET
) {
5938 addReply(c
,shared
.wrongtypeerr
);
5941 src
[i
].dict
= ((zset
*)zsetobj
->ptr
)->dict
;
5944 /* default all weights to 1 */
5945 src
[i
].weight
= 1.0;
5948 /* parse optional extra arguments */
5950 int remaining
= c
->argc
- j
;
5953 if (remaining
>= (zsetnum
+ 1) && !strcasecmp(c
->argv
[j
]->ptr
,"weights")) {
5955 for (i
= 0; i
< zsetnum
; i
++, j
++, remaining
--) {
5956 if (getDoubleFromObjectOrReply(c
, c
->argv
[j
], &src
[i
].weight
, NULL
) != REDIS_OK
)
5959 } else if (remaining
>= 2 && !strcasecmp(c
->argv
[j
]->ptr
,"aggregate")) {
5961 if (!strcasecmp(c
->argv
[j
]->ptr
,"sum")) {
5962 aggregate
= REDIS_AGGR_SUM
;
5963 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"min")) {
5964 aggregate
= REDIS_AGGR_MIN
;
5965 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"max")) {
5966 aggregate
= REDIS_AGGR_MAX
;
5969 addReply(c
,shared
.syntaxerr
);
5975 addReply(c
,shared
.syntaxerr
);
5981 /* sort sets from the smallest to largest, this will improve our
5982 * algorithm's performance */
5983 qsort(src
,zsetnum
,sizeof(zsetopsrc
), qsortCompareZsetopsrcByCardinality
);
5985 dstobj
= createZsetObject();
5986 dstzset
= dstobj
->ptr
;
5988 if (op
== REDIS_OP_INTER
) {
5989 /* skip going over all entries if the smallest zset is NULL or empty */
5990 if (src
[0].dict
&& dictSize(src
[0].dict
) > 0) {
5991 /* precondition: as src[0].dict is non-empty and the zsets are ordered
5992 * from small to large, all src[i > 0].dict are non-empty too */
5993 di
= dictGetIterator(src
[0].dict
);
5994 while((de
= dictNext(di
)) != NULL
) {
5995 double *score
= zmalloc(sizeof(double)), value
;
5996 *score
= src
[0].weight
* (*(double*)dictGetEntryVal(de
));
5998 for (j
= 1; j
< zsetnum
; j
++) {
5999 dictEntry
*other
= dictFind(src
[j
].dict
,dictGetEntryKey(de
));
6001 value
= src
[j
].weight
* (*(double*)dictGetEntryVal(other
));
6002 zunionInterAggregate(score
, value
, aggregate
);
6008 /* skip entry when not present in every source dict */
6012 robj
*o
= dictGetEntryKey(de
);
6013 dictAdd(dstzset
->dict
,o
,score
);
6014 incrRefCount(o
); /* added to dictionary */
6015 zslInsert(dstzset
->zsl
,*score
,o
);
6016 incrRefCount(o
); /* added to skiplist */
6019 dictReleaseIterator(di
);
6021 } else if (op
== REDIS_OP_UNION
) {
6022 for (i
= 0; i
< zsetnum
; i
++) {
6023 if (!src
[i
].dict
) continue;
6025 di
= dictGetIterator(src
[i
].dict
);
6026 while((de
= dictNext(di
)) != NULL
) {
6027 /* skip key when already processed */
6028 if (dictFind(dstzset
->dict
,dictGetEntryKey(de
)) != NULL
) continue;
6030 double *score
= zmalloc(sizeof(double)), value
;
6031 *score
= src
[i
].weight
* (*(double*)dictGetEntryVal(de
));
6033 /* because the zsets are sorted by size, its only possible
6034 * for sets at larger indices to hold this entry */
6035 for (j
= (i
+1); j
< zsetnum
; j
++) {
6036 dictEntry
*other
= dictFind(src
[j
].dict
,dictGetEntryKey(de
));
6038 value
= src
[j
].weight
* (*(double*)dictGetEntryVal(other
));
6039 zunionInterAggregate(score
, value
, aggregate
);
6043 robj
*o
= dictGetEntryKey(de
);
6044 dictAdd(dstzset
->dict
,o
,score
);
6045 incrRefCount(o
); /* added to dictionary */
6046 zslInsert(dstzset
->zsl
,*score
,o
);
6047 incrRefCount(o
); /* added to skiplist */
6049 dictReleaseIterator(di
);
6052 /* unknown operator */
6053 redisAssert(op
== REDIS_OP_INTER
|| op
== REDIS_OP_UNION
);
6056 deleteKey(c
->db
,dstkey
);
6057 if (dstzset
->zsl
->length
) {
6058 dictAdd(c
->db
->dict
,dstkey
,dstobj
);
6059 incrRefCount(dstkey
);
6060 addReplyLong(c
, dstzset
->zsl
->length
);
6063 decrRefCount(dstobj
);
6064 addReply(c
, shared
.czero
);
6069 static void zunionstoreCommand(redisClient
*c
) {
6070 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_UNION
);
6073 static void zinterstoreCommand(redisClient
*c
) {
6074 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_INTER
);
6077 static void zrangeGenericCommand(redisClient
*c
, int reverse
) {
6089 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
6090 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
6092 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
6094 } else if (c
->argc
>= 5) {
6095 addReply(c
,shared
.syntaxerr
);
6099 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.emptymultibulk
)) == NULL
6100 || checkType(c
,o
,REDIS_ZSET
)) return;
6105 /* convert negative indexes */
6106 if (start
< 0) start
= llen
+start
;
6107 if (end
< 0) end
= llen
+end
;
6108 if (start
< 0) start
= 0;
6109 if (end
< 0) end
= 0;
6111 /* indexes sanity checks */
6112 if (start
> end
|| start
>= llen
) {
6113 /* Out of range start or start > end result in empty list */
6114 addReply(c
,shared
.emptymultibulk
);
6117 if (end
>= llen
) end
= llen
-1;
6118 rangelen
= (end
-start
)+1;
6120 /* check if starting point is trivial, before searching
6121 * the element in log(N) time */
6123 ln
= start
== 0 ? zsl
->tail
: zslGetElementByRank(zsl
, llen
-start
);
6126 zsl
->header
->forward
[0] : zslGetElementByRank(zsl
, start
+1);
6129 /* Return the result in form of a multi-bulk reply */
6130 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",
6131 withscores
? (rangelen
*2) : rangelen
));
6132 for (j
= 0; j
< rangelen
; j
++) {
6134 addReplyBulk(c
,ele
);
6136 addReplyDouble(c
,ln
->score
);
6137 ln
= reverse
? ln
->backward
: ln
->forward
[0];
6141 static void zrangeCommand(redisClient
*c
) {
6142 zrangeGenericCommand(c
,0);
6145 static void zrevrangeCommand(redisClient
*c
) {
6146 zrangeGenericCommand(c
,1);
6149 /* This command implements both ZRANGEBYSCORE and ZCOUNT.
6150 * If justcount is non-zero, just the count is returned. */
6151 static void genericZrangebyscoreCommand(redisClient
*c
, int justcount
) {
6154 int minex
= 0, maxex
= 0; /* are min or max exclusive? */
6155 int offset
= 0, limit
= -1;
6159 /* Parse the min-max interval. If one of the values is prefixed
6160 * by the "(" character, it's considered "open". For instance
6161 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
6162 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
6163 if (((char*)c
->argv
[2]->ptr
)[0] == '(') {
6164 min
= strtod((char*)c
->argv
[2]->ptr
+1,NULL
);
6167 min
= strtod(c
->argv
[2]->ptr
,NULL
);
6169 if (((char*)c
->argv
[3]->ptr
)[0] == '(') {
6170 max
= strtod((char*)c
->argv
[3]->ptr
+1,NULL
);
6173 max
= strtod(c
->argv
[3]->ptr
,NULL
);
6176 /* Parse "WITHSCORES": note that if the command was called with
6177 * the name ZCOUNT then we are sure that c->argc == 4, so we'll never
6178 * enter the following paths to parse WITHSCORES and LIMIT. */
6179 if (c
->argc
== 5 || c
->argc
== 8) {
6180 if (strcasecmp(c
->argv
[c
->argc
-1]->ptr
,"withscores") == 0)
6185 if (c
->argc
!= (4 + withscores
) && c
->argc
!= (7 + withscores
))
6189 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
6194 if (c
->argc
== (7 + withscores
) && strcasecmp(c
->argv
[4]->ptr
,"limit")) {
6195 addReply(c
,shared
.syntaxerr
);
6197 } else if (c
->argc
== (7 + withscores
)) {
6198 offset
= atoi(c
->argv
[5]->ptr
);
6199 limit
= atoi(c
->argv
[6]->ptr
);
6200 if (offset
< 0) offset
= 0;
6203 /* Ok, lookup the key and get the range */
6204 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
6206 addReply(c
,justcount
? shared
.czero
: shared
.emptymultibulk
);
6208 if (o
->type
!= REDIS_ZSET
) {
6209 addReply(c
,shared
.wrongtypeerr
);
6211 zset
*zsetobj
= o
->ptr
;
6212 zskiplist
*zsl
= zsetobj
->zsl
;
6214 robj
*ele
, *lenobj
= NULL
;
6215 unsigned long rangelen
= 0;
6217 /* Get the first node with the score >= min, or with
6218 * score > min if 'minex' is true. */
6219 ln
= zslFirstWithScore(zsl
,min
);
6220 while (minex
&& ln
&& ln
->score
== min
) ln
= ln
->forward
[0];
6223 /* No element matching the speciifed interval */
6224 addReply(c
,justcount
? shared
.czero
: shared
.emptymultibulk
);
6228 /* We don't know in advance how many matching elements there
6229 * are in the list, so we push this object that will represent
6230 * the multi-bulk length in the output buffer, and will "fix"
6233 lenobj
= createObject(REDIS_STRING
,NULL
);
6235 decrRefCount(lenobj
);
6238 while(ln
&& (maxex
? (ln
->score
< max
) : (ln
->score
<= max
))) {
6241 ln
= ln
->forward
[0];
6244 if (limit
== 0) break;
6247 addReplyBulk(c
,ele
);
6249 addReplyDouble(c
,ln
->score
);
6251 ln
= ln
->forward
[0];
6253 if (limit
> 0) limit
--;
6256 addReplyLong(c
,(long)rangelen
);
6258 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",
6259 withscores
? (rangelen
*2) : rangelen
);
6265 static void zrangebyscoreCommand(redisClient
*c
) {
6266 genericZrangebyscoreCommand(c
,0);
6269 static void zcountCommand(redisClient
*c
) {
6270 genericZrangebyscoreCommand(c
,1);
6273 static void zcardCommand(redisClient
*c
) {
6277 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
6278 checkType(c
,o
,REDIS_ZSET
)) return;
6281 addReplyUlong(c
,zs
->zsl
->length
);
6284 static void zscoreCommand(redisClient
*c
) {
6289 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
6290 checkType(c
,o
,REDIS_ZSET
)) return;
6293 de
= dictFind(zs
->dict
,c
->argv
[2]);
6295 addReply(c
,shared
.nullbulk
);
6297 double *score
= dictGetEntryVal(de
);
6299 addReplyDouble(c
,*score
);
6303 static void zrankGenericCommand(redisClient
*c
, int reverse
) {
6311 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
6312 checkType(c
,o
,REDIS_ZSET
)) return;
6316 de
= dictFind(zs
->dict
,c
->argv
[2]);
6318 addReply(c
,shared
.nullbulk
);
6322 score
= dictGetEntryVal(de
);
6323 rank
= zslGetRank(zsl
, *score
, c
->argv
[2]);
6326 addReplyLong(c
, zsl
->length
- rank
);
6328 addReplyLong(c
, rank
-1);
6331 addReply(c
,shared
.nullbulk
);
6335 static void zrankCommand(redisClient
*c
) {
6336 zrankGenericCommand(c
, 0);
6339 static void zrevrankCommand(redisClient
*c
) {
6340 zrankGenericCommand(c
, 1);
6343 /* ========================= Hashes utility functions ======================= */
6344 #define REDIS_HASH_KEY 1
6345 #define REDIS_HASH_VALUE 2
6347 /* Check the length of a number of objects to see if we need to convert a
6348 * zipmap to a real hash. Note that we only check string encoded objects
6349 * as their string length can be queried in constant time. */
6350 static void hashTryConversion(robj
*subject
, robj
**argv
, int start
, int end
) {
6352 if (subject
->encoding
!= REDIS_ENCODING_ZIPMAP
) return;
6354 for (i
= start
; i
<= end
; i
++) {
6355 if (argv
[i
]->encoding
== REDIS_ENCODING_RAW
&&
6356 sdslen(argv
[i
]->ptr
) > server
.hash_max_zipmap_value
)
6358 convertToRealHash(subject
);
6364 /* Encode given objects in-place when the hash uses a dict. */
6365 static void hashTryObjectEncoding(robj
*subject
, robj
**o1
, robj
**o2
) {
6366 if (subject
->encoding
== REDIS_ENCODING_HT
) {
6367 if (o1
) *o1
= tryObjectEncoding(*o1
);
6368 if (o2
) *o2
= tryObjectEncoding(*o2
);
6372 /* Get the value from a hash identified by key. Returns either a string
6373 * object or NULL if the value cannot be found. The refcount of the object
6374 * is always increased by 1 when the value was found. */
6375 static robj
*hashGet(robj
*o
, robj
*key
) {
6377 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6380 key
= getDecodedObject(key
);
6381 if (zipmapGet(o
->ptr
,key
->ptr
,sdslen(key
->ptr
),&v
,&vlen
)) {
6382 value
= createStringObject((char*)v
,vlen
);
6386 dictEntry
*de
= dictFind(o
->ptr
,key
);
6388 value
= dictGetEntryVal(de
);
6389 incrRefCount(value
);
6395 /* Test if the key exists in the given hash. Returns 1 if the key
6396 * exists and 0 when it doesn't. */
6397 static int hashExists(robj
*o
, robj
*key
) {
6398 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6399 key
= getDecodedObject(key
);
6400 if (zipmapExists(o
->ptr
,key
->ptr
,sdslen(key
->ptr
))) {
6406 if (dictFind(o
->ptr
,key
) != NULL
) {
6413 /* Add an element, discard the old if the key already exists.
6414 * Return 0 on insert and 1 on update. */
6415 static int hashSet(robj
*o
, robj
*key
, robj
*value
) {
6417 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6418 key
= getDecodedObject(key
);
6419 value
= getDecodedObject(value
);
6420 o
->ptr
= zipmapSet(o
->ptr
,
6421 key
->ptr
,sdslen(key
->ptr
),
6422 value
->ptr
,sdslen(value
->ptr
), &update
);
6424 decrRefCount(value
);
6426 /* Check if the zipmap needs to be upgraded to a real hash table */
6427 if (zipmapLen(o
->ptr
) > server
.hash_max_zipmap_entries
)
6428 convertToRealHash(o
);
6430 if (dictReplace(o
->ptr
,key
,value
)) {
6437 incrRefCount(value
);
6442 /* Delete an element from a hash.
6443 * Return 1 on deleted and 0 on not found. */
6444 static int hashDelete(robj
*o
, robj
*key
) {
6446 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6447 key
= getDecodedObject(key
);
6448 o
->ptr
= zipmapDel(o
->ptr
,key
->ptr
,sdslen(key
->ptr
), &deleted
);
6451 deleted
= dictDelete((dict
*)o
->ptr
,key
) == DICT_OK
;
6452 /* Always check if the dictionary needs a resize after a delete. */
6453 if (deleted
&& htNeedsResize(o
->ptr
)) dictResize(o
->ptr
);
6458 /* Return the number of elements in a hash. */
6459 static unsigned long hashLength(robj
*o
) {
6460 return (o
->encoding
== REDIS_ENCODING_ZIPMAP
) ?
6461 zipmapLen((unsigned char*)o
->ptr
) : dictSize((dict
*)o
->ptr
);
6464 /* Structure to hold hash iteration abstration. Note that iteration over
6465 * hashes involves both fields and values. Because it is possible that
6466 * not both are required, store pointers in the iterator to avoid
6467 * unnecessary memory allocation for fields/values. */
6471 unsigned char *zk
, *zv
;
6472 unsigned int zklen
, zvlen
;
6478 static hashIterator
*hashInitIterator(robj
*subject
) {
6479 hashIterator
*hi
= zmalloc(sizeof(hashIterator
));
6480 hi
->encoding
= subject
->encoding
;
6481 if (hi
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6482 hi
->zi
= zipmapRewind(subject
->ptr
);
6483 } else if (hi
->encoding
== REDIS_ENCODING_HT
) {
6484 hi
->di
= dictGetIterator(subject
->ptr
);
6491 static void hashReleaseIterator(hashIterator
*hi
) {
6492 if (hi
->encoding
== REDIS_ENCODING_HT
) {
6493 dictReleaseIterator(hi
->di
);
6498 /* Move to the next entry in the hash. Return REDIS_OK when the next entry
6499 * could be found and REDIS_ERR when the iterator reaches the end. */
6500 static int hashNext(hashIterator
*hi
) {
6501 if (hi
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6502 if ((hi
->zi
= zipmapNext(hi
->zi
, &hi
->zk
, &hi
->zklen
,
6503 &hi
->zv
, &hi
->zvlen
)) == NULL
) return REDIS_ERR
;
6505 if ((hi
->de
= dictNext(hi
->di
)) == NULL
) return REDIS_ERR
;
6510 /* Get key or value object at current iteration position.
6511 * This increases the refcount of the field object by 1. */
6512 static robj
*hashCurrent(hashIterator
*hi
, int what
) {
6514 if (hi
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6515 if (what
& REDIS_HASH_KEY
) {
6516 o
= createStringObject((char*)hi
->zk
,hi
->zklen
);
6518 o
= createStringObject((char*)hi
->zv
,hi
->zvlen
);
6521 if (what
& REDIS_HASH_KEY
) {
6522 o
= dictGetEntryKey(hi
->de
);
6524 o
= dictGetEntryVal(hi
->de
);
6531 static robj
*hashLookupWriteOrCreate(redisClient
*c
, robj
*key
) {
6532 robj
*o
= lookupKeyWrite(c
->db
,key
);
6534 o
= createHashObject();
6535 dictAdd(c
->db
->dict
,key
,o
);
6538 if (o
->type
!= REDIS_HASH
) {
6539 addReply(c
,shared
.wrongtypeerr
);
6546 /* ============================= Hash commands ============================== */
6547 static void hsetCommand(redisClient
*c
) {
6551 if ((o
= hashLookupWriteOrCreate(c
,c
->argv
[1])) == NULL
) return;
6552 hashTryConversion(o
,c
->argv
,2,3);
6553 hashTryObjectEncoding(o
,&c
->argv
[2], &c
->argv
[3]);
6554 update
= hashSet(o
,c
->argv
[2],c
->argv
[3]);
6555 addReply(c
, update
? shared
.czero
: shared
.cone
);
6559 static void hsetnxCommand(redisClient
*c
) {
6561 if ((o
= hashLookupWriteOrCreate(c
,c
->argv
[1])) == NULL
) return;
6562 hashTryConversion(o
,c
->argv
,2,3);
6564 if (hashExists(o
, c
->argv
[2])) {
6565 addReply(c
, shared
.czero
);
6567 hashTryObjectEncoding(o
,&c
->argv
[2], &c
->argv
[3]);
6568 hashSet(o
,c
->argv
[2],c
->argv
[3]);
6569 addReply(c
, shared
.cone
);
6574 static void hmsetCommand(redisClient
*c
) {
6578 if ((c
->argc
% 2) == 1) {
6579 addReplySds(c
,sdsnew("-ERR wrong number of arguments for HMSET\r\n"));
6583 if ((o
= hashLookupWriteOrCreate(c
,c
->argv
[1])) == NULL
) return;
6584 hashTryConversion(o
,c
->argv
,2,c
->argc
-1);
6585 for (i
= 2; i
< c
->argc
; i
+= 2) {
6586 hashTryObjectEncoding(o
,&c
->argv
[i
], &c
->argv
[i
+1]);
6587 hashSet(o
,c
->argv
[i
],c
->argv
[i
+1]);
6589 addReply(c
, shared
.ok
);
6593 static void hincrbyCommand(redisClient
*c
) {
6594 long long value
, incr
;
6595 robj
*o
, *current
, *new;
6597 if (getLongLongFromObjectOrReply(c
,c
->argv
[3],&incr
,NULL
) != REDIS_OK
) return;
6598 if ((o
= hashLookupWriteOrCreate(c
,c
->argv
[1])) == NULL
) return;
6599 if ((current
= hashGet(o
,c
->argv
[2])) != NULL
) {
6600 if (getLongLongFromObjectOrReply(c
,current
,&value
,
6601 "hash value is not an integer") != REDIS_OK
) {
6602 decrRefCount(current
);
6605 decrRefCount(current
);
6611 new = createStringObjectFromLongLong(value
);
6612 hashTryObjectEncoding(o
,&c
->argv
[2],NULL
);
6613 hashSet(o
,c
->argv
[2],new);
6615 addReplyLongLong(c
,value
);
6619 static void hgetCommand(redisClient
*c
) {
6621 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
6622 checkType(c
,o
,REDIS_HASH
)) return;
6624 if ((value
= hashGet(o
,c
->argv
[2])) != NULL
) {
6625 addReplyBulk(c
,value
);
6626 decrRefCount(value
);
6628 addReply(c
,shared
.nullbulk
);
6632 static void hmgetCommand(redisClient
*c
) {
6635 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
6636 if (o
!= NULL
&& o
->type
!= REDIS_HASH
) {
6637 addReply(c
,shared
.wrongtypeerr
);
6640 /* Note the check for o != NULL happens inside the loop. This is
6641 * done because objects that cannot be found are considered to be
6642 * an empty hash. The reply should then be a series of NULLs. */
6643 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-2));
6644 for (i
= 2; i
< c
->argc
; i
++) {
6645 if (o
!= NULL
&& (value
= hashGet(o
,c
->argv
[i
])) != NULL
) {
6646 addReplyBulk(c
,value
);
6647 decrRefCount(value
);
6649 addReply(c
,shared
.nullbulk
);
6654 static void hdelCommand(redisClient
*c
) {
6656 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
6657 checkType(c
,o
,REDIS_HASH
)) return;
6659 if (hashDelete(o
,c
->argv
[2])) {
6660 if (hashLength(o
) == 0) deleteKey(c
->db
,c
->argv
[1]);
6661 addReply(c
,shared
.cone
);
6664 addReply(c
,shared
.czero
);
6668 static void hlenCommand(redisClient
*c
) {
6670 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
6671 checkType(c
,o
,REDIS_HASH
)) return;
6673 addReplyUlong(c
,hashLength(o
));
6676 static void genericHgetallCommand(redisClient
*c
, int flags
) {
6677 robj
*o
, *lenobj
, *obj
;
6678 unsigned long count
= 0;
6681 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.emptymultibulk
)) == NULL
6682 || checkType(c
,o
,REDIS_HASH
)) return;
6684 lenobj
= createObject(REDIS_STRING
,NULL
);
6686 decrRefCount(lenobj
);
6688 hi
= hashInitIterator(o
);
6689 while (hashNext(hi
) != REDIS_ERR
) {
6690 if (flags
& REDIS_HASH_KEY
) {
6691 obj
= hashCurrent(hi
,REDIS_HASH_KEY
);
6692 addReplyBulk(c
,obj
);
6696 if (flags
& REDIS_HASH_VALUE
) {
6697 obj
= hashCurrent(hi
,REDIS_HASH_VALUE
);
6698 addReplyBulk(c
,obj
);
6703 hashReleaseIterator(hi
);
6705 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",count
);
6708 static void hkeysCommand(redisClient
*c
) {
6709 genericHgetallCommand(c
,REDIS_HASH_KEY
);
6712 static void hvalsCommand(redisClient
*c
) {
6713 genericHgetallCommand(c
,REDIS_HASH_VALUE
);
6716 static void hgetallCommand(redisClient
*c
) {
6717 genericHgetallCommand(c
,REDIS_HASH_KEY
|REDIS_HASH_VALUE
);
6720 static void hexistsCommand(redisClient
*c
) {
6722 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
6723 checkType(c
,o
,REDIS_HASH
)) return;
6725 addReply(c
, hashExists(o
,c
->argv
[2]) ? shared
.cone
: shared
.czero
);
6728 static void convertToRealHash(robj
*o
) {
6729 unsigned char *key
, *val
, *p
, *zm
= o
->ptr
;
6730 unsigned int klen
, vlen
;
6731 dict
*dict
= dictCreate(&hashDictType
,NULL
);
6733 assert(o
->type
== REDIS_HASH
&& o
->encoding
!= REDIS_ENCODING_HT
);
6734 p
= zipmapRewind(zm
);
6735 while((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) != NULL
) {
6736 robj
*keyobj
, *valobj
;
6738 keyobj
= createStringObject((char*)key
,klen
);
6739 valobj
= createStringObject((char*)val
,vlen
);
6740 keyobj
= tryObjectEncoding(keyobj
);
6741 valobj
= tryObjectEncoding(valobj
);
6742 dictAdd(dict
,keyobj
,valobj
);
6744 o
->encoding
= REDIS_ENCODING_HT
;
6749 /* ========================= Non type-specific commands ==================== */
6751 static void flushdbCommand(redisClient
*c
) {
6752 server
.dirty
+= dictSize(c
->db
->dict
);
6753 dictEmpty(c
->db
->dict
);
6754 dictEmpty(c
->db
->expires
);
6755 addReply(c
,shared
.ok
);
6758 static void flushallCommand(redisClient
*c
) {
6759 server
.dirty
+= emptyDb();
6760 addReply(c
,shared
.ok
);
6761 if (server
.bgsavechildpid
!= -1) {
6762 kill(server
.bgsavechildpid
,SIGKILL
);
6763 rdbRemoveTempFile(server
.bgsavechildpid
);
6765 rdbSave(server
.dbfilename
);
6769 static redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
6770 redisSortOperation
*so
= zmalloc(sizeof(*so
));
6772 so
->pattern
= pattern
;
6776 /* Return the value associated to the key with a name obtained
6777 * substituting the first occurence of '*' in 'pattern' with 'subst'.
6778 * The returned object will always have its refcount increased by 1
6779 * when it is non-NULL. */
6780 static robj
*lookupKeyByPattern(redisDb
*db
, robj
*pattern
, robj
*subst
) {
6783 robj keyobj
, fieldobj
, *o
;
6784 int prefixlen
, sublen
, postfixlen
, fieldlen
;
6785 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
6789 char buf
[REDIS_SORTKEY_MAX
+1];
6790 } keyname
, fieldname
;
6792 /* If the pattern is "#" return the substitution object itself in order
6793 * to implement the "SORT ... GET #" feature. */
6794 spat
= pattern
->ptr
;
6795 if (spat
[0] == '#' && spat
[1] == '\0') {
6796 incrRefCount(subst
);
6800 /* The substitution object may be specially encoded. If so we create
6801 * a decoded object on the fly. Otherwise getDecodedObject will just
6802 * increment the ref count, that we'll decrement later. */
6803 subst
= getDecodedObject(subst
);
6806 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
6807 p
= strchr(spat
,'*');
6809 decrRefCount(subst
);
6813 /* Find out if we're dealing with a hash dereference. */
6814 if ((f
= strstr(p
+1, "->")) != NULL
) {
6815 fieldlen
= sdslen(spat
)-(f
-spat
);
6816 /* this also copies \0 character */
6817 memcpy(fieldname
.buf
,f
+2,fieldlen
-1);
6818 fieldname
.len
= fieldlen
-2;
6824 sublen
= sdslen(ssub
);
6825 postfixlen
= sdslen(spat
)-(prefixlen
+1)-fieldlen
;
6826 memcpy(keyname
.buf
,spat
,prefixlen
);
6827 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
6828 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
6829 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
6830 keyname
.len
= prefixlen
+sublen
+postfixlen
;
6831 decrRefCount(subst
);
6833 /* Lookup substituted key */
6834 initStaticStringObject(keyobj
,((char*)&keyname
)+(sizeof(long)*2));
6835 o
= lookupKeyRead(db
,&keyobj
);
6836 if (o
== NULL
) return NULL
;
6839 if (o
->type
!= REDIS_HASH
|| fieldname
.len
< 1) return NULL
;
6841 /* Retrieve value from hash by the field name. This operation
6842 * already increases the refcount of the returned object. */
6843 initStaticStringObject(fieldobj
,((char*)&fieldname
)+(sizeof(long)*2));
6844 o
= hashGet(o
, &fieldobj
);
6846 if (o
->type
!= REDIS_STRING
) return NULL
;
6848 /* Every object that this function returns needs to have its refcount
6849 * increased. sortCommand decreases it again. */
6856 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
6857 * the additional parameter is not standard but a BSD-specific we have to
6858 * pass sorting parameters via the global 'server' structure */
6859 static int sortCompare(const void *s1
, const void *s2
) {
6860 const redisSortObject
*so1
= s1
, *so2
= s2
;
6863 if (!server
.sort_alpha
) {
6864 /* Numeric sorting. Here it's trivial as we precomputed scores */
6865 if (so1
->u
.score
> so2
->u
.score
) {
6867 } else if (so1
->u
.score
< so2
->u
.score
) {
6873 /* Alphanumeric sorting */
6874 if (server
.sort_bypattern
) {
6875 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
6876 /* At least one compare object is NULL */
6877 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
6879 else if (so1
->u
.cmpobj
== NULL
)
6884 /* We have both the objects, use strcoll */
6885 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
6888 /* Compare elements directly. */
6889 cmp
= compareStringObjects(so1
->obj
,so2
->obj
);
6892 return server
.sort_desc
? -cmp
: cmp
;
6895 /* The SORT command is the most complex command in Redis. Warning: this code
6896 * is optimized for speed and a bit less for readability */
6897 static void sortCommand(redisClient
*c
) {
6900 int desc
= 0, alpha
= 0;
6901 int limit_start
= 0, limit_count
= -1, start
, end
;
6902 int j
, dontsort
= 0, vectorlen
;
6903 int getop
= 0; /* GET operation counter */
6904 robj
*sortval
, *sortby
= NULL
, *storekey
= NULL
;
6905 redisSortObject
*vector
; /* Resulting vector to sort */
6907 /* Lookup the key to sort. It must be of the right types */
6908 sortval
= lookupKeyRead(c
->db
,c
->argv
[1]);
6909 if (sortval
== NULL
) {
6910 addReply(c
,shared
.emptymultibulk
);
6913 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
&&
6914 sortval
->type
!= REDIS_ZSET
)
6916 addReply(c
,shared
.wrongtypeerr
);
6920 /* Create a list of operations to perform for every sorted element.
6921 * Operations can be GET/DEL/INCR/DECR */
6922 operations
= listCreate();
6923 listSetFreeMethod(operations
,zfree
);
6926 /* Now we need to protect sortval incrementing its count, in the future
6927 * SORT may have options able to overwrite/delete keys during the sorting
6928 * and the sorted key itself may get destroied */
6929 incrRefCount(sortval
);
6931 /* The SORT command has an SQL-alike syntax, parse it */
6932 while(j
< c
->argc
) {
6933 int leftargs
= c
->argc
-j
-1;
6934 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
6936 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
6938 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
6940 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
6941 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
6942 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
6944 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"store") && leftargs
>= 1) {
6945 storekey
= c
->argv
[j
+1];
6947 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
6948 sortby
= c
->argv
[j
+1];
6949 /* If the BY pattern does not contain '*', i.e. it is constant,
6950 * we don't need to sort nor to lookup the weight keys. */
6951 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
6953 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
6954 listAddNodeTail(operations
,createSortOperation(
6955 REDIS_SORT_GET
,c
->argv
[j
+1]));
6959 decrRefCount(sortval
);
6960 listRelease(operations
);
6961 addReply(c
,shared
.syntaxerr
);
6967 /* Load the sorting vector with all the objects to sort */
6968 switch(sortval
->type
) {
6969 case REDIS_LIST
: vectorlen
= listLength((list
*)sortval
->ptr
); break;
6970 case REDIS_SET
: vectorlen
= dictSize((dict
*)sortval
->ptr
); break;
6971 case REDIS_ZSET
: vectorlen
= dictSize(((zset
*)sortval
->ptr
)->dict
); break;
6972 default: vectorlen
= 0; redisPanic("Bad SORT type"); /* Avoid GCC warning */
6974 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
6977 if (sortval
->type
== REDIS_LIST
) {
6978 list
*list
= sortval
->ptr
;
6982 listRewind(list
,&li
);
6983 while((ln
= listNext(&li
))) {
6984 robj
*ele
= ln
->value
;
6985 vector
[j
].obj
= ele
;
6986 vector
[j
].u
.score
= 0;
6987 vector
[j
].u
.cmpobj
= NULL
;
6995 if (sortval
->type
== REDIS_SET
) {
6998 zset
*zs
= sortval
->ptr
;
7002 di
= dictGetIterator(set
);
7003 while((setele
= dictNext(di
)) != NULL
) {
7004 vector
[j
].obj
= dictGetEntryKey(setele
);
7005 vector
[j
].u
.score
= 0;
7006 vector
[j
].u
.cmpobj
= NULL
;
7009 dictReleaseIterator(di
);
7011 redisAssert(j
== vectorlen
);
7013 /* Now it's time to load the right scores in the sorting vector */
7014 if (dontsort
== 0) {
7015 for (j
= 0; j
< vectorlen
; j
++) {
7018 /* lookup value to sort by */
7019 byval
= lookupKeyByPattern(c
->db
,sortby
,vector
[j
].obj
);
7020 if (!byval
) continue;
7022 /* use object itself to sort by */
7023 byval
= vector
[j
].obj
;
7027 if (sortby
) vector
[j
].u
.cmpobj
= getDecodedObject(byval
);
7029 if (byval
->encoding
== REDIS_ENCODING_RAW
) {
7030 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
7031 } else if (byval
->encoding
== REDIS_ENCODING_INT
) {
7032 /* Don't need to decode the object if it's
7033 * integer-encoded (the only encoding supported) so
7034 * far. We can just cast it */
7035 vector
[j
].u
.score
= (long)byval
->ptr
;
7037 redisAssert(1 != 1);
7041 /* when the object was retrieved using lookupKeyByPattern,
7042 * its refcount needs to be decreased. */
7044 decrRefCount(byval
);
7049 /* We are ready to sort the vector... perform a bit of sanity check
7050 * on the LIMIT option too. We'll use a partial version of quicksort. */
7051 start
= (limit_start
< 0) ? 0 : limit_start
;
7052 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
7053 if (start
>= vectorlen
) {
7054 start
= vectorlen
-1;
7057 if (end
>= vectorlen
) end
= vectorlen
-1;
7059 if (dontsort
== 0) {
7060 server
.sort_desc
= desc
;
7061 server
.sort_alpha
= alpha
;
7062 server
.sort_bypattern
= sortby
? 1 : 0;
7063 if (sortby
&& (start
!= 0 || end
!= vectorlen
-1))
7064 pqsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
, start
,end
);
7066 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
7069 /* Send command output to the output buffer, performing the specified
7070 * GET/DEL/INCR/DECR operations if any. */
7071 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
7072 if (storekey
== NULL
) {
7073 /* STORE option not specified, sent the sorting result to client */
7074 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
7075 for (j
= start
; j
<= end
; j
++) {
7079 if (!getop
) addReplyBulk(c
,vector
[j
].obj
);
7080 listRewind(operations
,&li
);
7081 while((ln
= listNext(&li
))) {
7082 redisSortOperation
*sop
= ln
->value
;
7083 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
7086 if (sop
->type
== REDIS_SORT_GET
) {
7088 addReply(c
,shared
.nullbulk
);
7090 addReplyBulk(c
,val
);
7094 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
7099 robj
*listObject
= createListObject();
7100 list
*listPtr
= (list
*) listObject
->ptr
;
7102 /* STORE option specified, set the sorting result as a List object */
7103 for (j
= start
; j
<= end
; j
++) {
7108 listAddNodeTail(listPtr
,vector
[j
].obj
);
7109 incrRefCount(vector
[j
].obj
);
7111 listRewind(operations
,&li
);
7112 while((ln
= listNext(&li
))) {
7113 redisSortOperation
*sop
= ln
->value
;
7114 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
7117 if (sop
->type
== REDIS_SORT_GET
) {
7119 listAddNodeTail(listPtr
,createStringObject("",0));
7121 /* We should do a incrRefCount on val because it is
7122 * added to the list, but also a decrRefCount because
7123 * it is returned by lookupKeyByPattern. This results
7124 * in doing nothing at all. */
7125 listAddNodeTail(listPtr
,val
);
7128 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
7132 if (dictReplace(c
->db
->dict
,storekey
,listObject
)) {
7133 incrRefCount(storekey
);
7135 /* Note: we add 1 because the DB is dirty anyway since even if the
7136 * SORT result is empty a new key is set and maybe the old content
7138 server
.dirty
+= 1+outputlen
;
7139 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",outputlen
));
7143 decrRefCount(sortval
);
7144 listRelease(operations
);
7145 for (j
= 0; j
< vectorlen
; j
++) {
7146 if (alpha
&& vector
[j
].u
.cmpobj
)
7147 decrRefCount(vector
[j
].u
.cmpobj
);
7152 /* Convert an amount of bytes into a human readable string in the form
7153 * of 100B, 2G, 100M, 4K, and so forth. */
7154 static void bytesToHuman(char *s
, unsigned long long n
) {
7159 sprintf(s
,"%lluB",n
);
7161 } else if (n
< (1024*1024)) {
7162 d
= (double)n
/(1024);
7163 sprintf(s
,"%.2fK",d
);
7164 } else if (n
< (1024LL*1024*1024)) {
7165 d
= (double)n
/(1024*1024);
7166 sprintf(s
,"%.2fM",d
);
7167 } else if (n
< (1024LL*1024*1024*1024)) {
7168 d
= (double)n
/(1024LL*1024*1024);
7169 sprintf(s
,"%.2fG",d
);
7173 /* Create the string returned by the INFO command. This is decoupled
7174 * by the INFO command itself as we need to report the same information
7175 * on memory corruption problems. */
7176 static sds
genRedisInfoString(void) {
7178 time_t uptime
= time(NULL
)-server
.stat_starttime
;
7182 bytesToHuman(hmem
,zmalloc_used_memory());
7183 info
= sdscatprintf(sdsempty(),
7184 "redis_version:%s\r\n"
7186 "multiplexing_api:%s\r\n"
7187 "process_id:%ld\r\n"
7188 "uptime_in_seconds:%ld\r\n"
7189 "uptime_in_days:%ld\r\n"
7190 "connected_clients:%d\r\n"
7191 "connected_slaves:%d\r\n"
7192 "blocked_clients:%d\r\n"
7193 "used_memory:%zu\r\n"
7194 "used_memory_human:%s\r\n"
7195 "changes_since_last_save:%lld\r\n"
7196 "bgsave_in_progress:%d\r\n"
7197 "last_save_time:%ld\r\n"
7198 "bgrewriteaof_in_progress:%d\r\n"
7199 "total_connections_received:%lld\r\n"
7200 "total_commands_processed:%lld\r\n"
7201 "expired_keys:%lld\r\n"
7202 "hash_max_zipmap_entries:%zu\r\n"
7203 "hash_max_zipmap_value:%zu\r\n"
7204 "pubsub_channels:%ld\r\n"
7205 "pubsub_patterns:%u\r\n"
7209 (sizeof(long) == 8) ? "64" : "32",
7214 listLength(server
.clients
)-listLength(server
.slaves
),
7215 listLength(server
.slaves
),
7216 server
.blpop_blocked_clients
,
7217 zmalloc_used_memory(),
7220 server
.bgsavechildpid
!= -1,
7222 server
.bgrewritechildpid
!= -1,
7223 server
.stat_numconnections
,
7224 server
.stat_numcommands
,
7225 server
.stat_expiredkeys
,
7226 server
.hash_max_zipmap_entries
,
7227 server
.hash_max_zipmap_value
,
7228 dictSize(server
.pubsub_channels
),
7229 listLength(server
.pubsub_patterns
),
7230 server
.vm_enabled
!= 0,
7231 server
.masterhost
== NULL
? "master" : "slave"
7233 if (server
.masterhost
) {
7234 info
= sdscatprintf(info
,
7235 "master_host:%s\r\n"
7236 "master_port:%d\r\n"
7237 "master_link_status:%s\r\n"
7238 "master_last_io_seconds_ago:%d\r\n"
7241 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
7243 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1
7246 if (server
.vm_enabled
) {
7248 info
= sdscatprintf(info
,
7249 "vm_conf_max_memory:%llu\r\n"
7250 "vm_conf_page_size:%llu\r\n"
7251 "vm_conf_pages:%llu\r\n"
7252 "vm_stats_used_pages:%llu\r\n"
7253 "vm_stats_swapped_objects:%llu\r\n"
7254 "vm_stats_swappin_count:%llu\r\n"
7255 "vm_stats_swappout_count:%llu\r\n"
7256 "vm_stats_io_newjobs_len:%lu\r\n"
7257 "vm_stats_io_processing_len:%lu\r\n"
7258 "vm_stats_io_processed_len:%lu\r\n"
7259 "vm_stats_io_active_threads:%lu\r\n"
7260 "vm_stats_blocked_clients:%lu\r\n"
7261 ,(unsigned long long) server
.vm_max_memory
,
7262 (unsigned long long) server
.vm_page_size
,
7263 (unsigned long long) server
.vm_pages
,
7264 (unsigned long long) server
.vm_stats_used_pages
,
7265 (unsigned long long) server
.vm_stats_swapped_objects
,
7266 (unsigned long long) server
.vm_stats_swapins
,
7267 (unsigned long long) server
.vm_stats_swapouts
,
7268 (unsigned long) listLength(server
.io_newjobs
),
7269 (unsigned long) listLength(server
.io_processing
),
7270 (unsigned long) listLength(server
.io_processed
),
7271 (unsigned long) server
.io_active_threads
,
7272 (unsigned long) server
.vm_blocked_clients
7276 for (j
= 0; j
< server
.dbnum
; j
++) {
7277 long long keys
, vkeys
;
7279 keys
= dictSize(server
.db
[j
].dict
);
7280 vkeys
= dictSize(server
.db
[j
].expires
);
7281 if (keys
|| vkeys
) {
7282 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
7289 static void infoCommand(redisClient
*c
) {
7290 sds info
= genRedisInfoString();
7291 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
7292 (unsigned long)sdslen(info
)));
7293 addReplySds(c
,info
);
7294 addReply(c
,shared
.crlf
);
7297 static void monitorCommand(redisClient
*c
) {
7298 /* ignore MONITOR if aleady slave or in monitor mode */
7299 if (c
->flags
& REDIS_SLAVE
) return;
7301 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
7303 listAddNodeTail(server
.monitors
,c
);
7304 addReply(c
,shared
.ok
);
7307 /* ================================= Expire ================================= */
7308 static int removeExpire(redisDb
*db
, robj
*key
) {
7309 if (dictDelete(db
->expires
,key
) == DICT_OK
) {
7316 static int setExpire(redisDb
*db
, robj
*key
, time_t when
) {
7317 if (dictAdd(db
->expires
,key
,(void*)when
) == DICT_ERR
) {
7325 /* Return the expire time of the specified key, or -1 if no expire
7326 * is associated with this key (i.e. the key is non volatile) */
7327 static time_t getExpire(redisDb
*db
, robj
*key
) {
7330 /* No expire? return ASAP */
7331 if (dictSize(db
->expires
) == 0 ||
7332 (de
= dictFind(db
->expires
,key
)) == NULL
) return -1;
7334 return (time_t) dictGetEntryVal(de
);
7337 static int expireIfNeeded(redisDb
*db
, robj
*key
) {
7341 /* No expire? return ASAP */
7342 if (dictSize(db
->expires
) == 0 ||
7343 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
7345 /* Lookup the expire */
7346 when
= (time_t) dictGetEntryVal(de
);
7347 if (time(NULL
) <= when
) return 0;
7349 /* Delete the key */
7350 dictDelete(db
->expires
,key
);
7351 server
.stat_expiredkeys
++;
7352 return dictDelete(db
->dict
,key
) == DICT_OK
;
7355 static int deleteIfVolatile(redisDb
*db
, robj
*key
) {
7358 /* No expire? return ASAP */
7359 if (dictSize(db
->expires
) == 0 ||
7360 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
7362 /* Delete the key */
7364 server
.stat_expiredkeys
++;
7365 dictDelete(db
->expires
,key
);
7366 return dictDelete(db
->dict
,key
) == DICT_OK
;
7369 static void expireGenericCommand(redisClient
*c
, robj
*key
, robj
*param
, long offset
) {
7373 if (getLongFromObjectOrReply(c
, param
, &seconds
, NULL
) != REDIS_OK
) return;
7377 de
= dictFind(c
->db
->dict
,key
);
7379 addReply(c
,shared
.czero
);
7383 if (deleteKey(c
->db
,key
)) server
.dirty
++;
7384 addReply(c
, shared
.cone
);
7387 time_t when
= time(NULL
)+seconds
;
7388 if (setExpire(c
->db
,key
,when
)) {
7389 addReply(c
,shared
.cone
);
7392 addReply(c
,shared
.czero
);
7398 static void expireCommand(redisClient
*c
) {
7399 expireGenericCommand(c
,c
->argv
[1],c
->argv
[2],0);
7402 static void expireatCommand(redisClient
*c
) {
7403 expireGenericCommand(c
,c
->argv
[1],c
->argv
[2],time(NULL
));
7406 static void ttlCommand(redisClient
*c
) {
7410 expire
= getExpire(c
->db
,c
->argv
[1]);
7412 ttl
= (int) (expire
-time(NULL
));
7413 if (ttl
< 0) ttl
= -1;
7415 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",ttl
));
7418 /* ================================ MULTI/EXEC ============================== */
7420 /* Client state initialization for MULTI/EXEC */
7421 static void initClientMultiState(redisClient
*c
) {
7422 c
->mstate
.commands
= NULL
;
7423 c
->mstate
.count
= 0;
7426 /* Release all the resources associated with MULTI/EXEC state */
7427 static void freeClientMultiState(redisClient
*c
) {
7430 for (j
= 0; j
< c
->mstate
.count
; j
++) {
7432 multiCmd
*mc
= c
->mstate
.commands
+j
;
7434 for (i
= 0; i
< mc
->argc
; i
++)
7435 decrRefCount(mc
->argv
[i
]);
7438 zfree(c
->mstate
.commands
);
7441 /* Add a new command into the MULTI commands queue */
7442 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
) {
7446 c
->mstate
.commands
= zrealloc(c
->mstate
.commands
,
7447 sizeof(multiCmd
)*(c
->mstate
.count
+1));
7448 mc
= c
->mstate
.commands
+c
->mstate
.count
;
7451 mc
->argv
= zmalloc(sizeof(robj
*)*c
->argc
);
7452 memcpy(mc
->argv
,c
->argv
,sizeof(robj
*)*c
->argc
);
7453 for (j
= 0; j
< c
->argc
; j
++)
7454 incrRefCount(mc
->argv
[j
]);
7458 static void multiCommand(redisClient
*c
) {
7459 c
->flags
|= REDIS_MULTI
;
7460 addReply(c
,shared
.ok
);
7463 static void discardCommand(redisClient
*c
) {
7464 if (!(c
->flags
& REDIS_MULTI
)) {
7465 addReplySds(c
,sdsnew("-ERR DISCARD without MULTI\r\n"));
7469 freeClientMultiState(c
);
7470 initClientMultiState(c
);
7471 c
->flags
&= (~REDIS_MULTI
);
7472 addReply(c
,shared
.ok
);
7475 /* Send a MULTI command to all the slaves and AOF file. Check the execCommand
7476 * implememntation for more information. */
7477 static void execCommandReplicateMulti(redisClient
*c
) {
7478 struct redisCommand
*cmd
;
7479 robj
*multistring
= createStringObject("MULTI",5);
7481 cmd
= lookupCommand("multi");
7482 if (server
.appendonly
)
7483 feedAppendOnlyFile(cmd
,c
->db
->id
,&multistring
,1);
7484 if (listLength(server
.slaves
))
7485 replicationFeedSlaves(server
.slaves
,c
->db
->id
,&multistring
,1);
7486 decrRefCount(multistring
);
7489 static void execCommand(redisClient
*c
) {
7494 if (!(c
->flags
& REDIS_MULTI
)) {
7495 addReplySds(c
,sdsnew("-ERR EXEC without MULTI\r\n"));
7499 /* Replicate a MULTI request now that we are sure the block is executed.
7500 * This way we'll deliver the MULTI/..../EXEC block as a whole and
7501 * both the AOF and the replication link will have the same consistency
7502 * and atomicity guarantees. */
7503 execCommandReplicateMulti(c
);
7505 /* Exec all the queued commands */
7506 orig_argv
= c
->argv
;
7507 orig_argc
= c
->argc
;
7508 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->mstate
.count
));
7509 for (j
= 0; j
< c
->mstate
.count
; j
++) {
7510 c
->argc
= c
->mstate
.commands
[j
].argc
;
7511 c
->argv
= c
->mstate
.commands
[j
].argv
;
7512 call(c
,c
->mstate
.commands
[j
].cmd
);
7514 c
->argv
= orig_argv
;
7515 c
->argc
= orig_argc
;
7516 freeClientMultiState(c
);
7517 initClientMultiState(c
);
7518 c
->flags
&= (~REDIS_MULTI
);
7519 /* Make sure the EXEC command is always replicated / AOF, since we
7520 * always send the MULTI command (we can't know beforehand if the
7521 * next operations will contain at least a modification to the DB). */
7525 /* =========================== Blocking Operations ========================= */
7527 /* Currently Redis blocking operations support is limited to list POP ops,
7528 * so the current implementation is not fully generic, but it is also not
7529 * completely specific so it will not require a rewrite to support new
7530 * kind of blocking operations in the future.
7532 * Still it's important to note that list blocking operations can be already
7533 * used as a notification mechanism in order to implement other blocking
7534 * operations at application level, so there must be a very strong evidence
7535 * of usefulness and generality before new blocking operations are implemented.
7537 * This is how the current blocking POP works, we use BLPOP as example:
7538 * - If the user calls BLPOP and the key exists and contains a non empty list
7539 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
7540 * if there is not to block.
7541 * - If instead BLPOP is called and the key does not exists or the list is
7542 * empty we need to block. In order to do so we remove the notification for
7543 * new data to read in the client socket (so that we'll not serve new
7544 * requests if the blocking request is not served). Also we put the client
7545 * in a dictionary (db->blockingkeys) mapping keys to a list of clients
7546 * blocking for this keys.
7547 * - If a PUSH operation against a key with blocked clients waiting is
7548 * performed, we serve the first in the list: basically instead to push
7549 * the new element inside the list we return it to the (first / oldest)
7550 * blocking client, unblock the client, and remove it form the list.
7552 * The above comment and the source code should be enough in order to understand
7553 * the implementation and modify / fix it later.
7556 /* Set a client in blocking mode for the specified key, with the specified
7558 static void blockForKeys(redisClient
*c
, robj
**keys
, int numkeys
, time_t timeout
) {
7563 c
->blockingkeys
= zmalloc(sizeof(robj
*)*numkeys
);
7564 c
->blockingkeysnum
= numkeys
;
7565 c
->blockingto
= timeout
;
7566 for (j
= 0; j
< numkeys
; j
++) {
7567 /* Add the key in the client structure, to map clients -> keys */
7568 c
->blockingkeys
[j
] = keys
[j
];
7569 incrRefCount(keys
[j
]);
7571 /* And in the other "side", to map keys -> clients */
7572 de
= dictFind(c
->db
->blockingkeys
,keys
[j
]);
7576 /* For every key we take a list of clients blocked for it */
7578 retval
= dictAdd(c
->db
->blockingkeys
,keys
[j
],l
);
7579 incrRefCount(keys
[j
]);
7580 assert(retval
== DICT_OK
);
7582 l
= dictGetEntryVal(de
);
7584 listAddNodeTail(l
,c
);
7586 /* Mark the client as a blocked client */
7587 c
->flags
|= REDIS_BLOCKED
;
7588 server
.blpop_blocked_clients
++;
7591 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
7592 static void unblockClientWaitingData(redisClient
*c
) {
7597 assert(c
->blockingkeys
!= NULL
);
7598 /* The client may wait for multiple keys, so unblock it for every key. */
7599 for (j
= 0; j
< c
->blockingkeysnum
; j
++) {
7600 /* Remove this client from the list of clients waiting for this key. */
7601 de
= dictFind(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
7603 l
= dictGetEntryVal(de
);
7604 listDelNode(l
,listSearchKey(l
,c
));
7605 /* If the list is empty we need to remove it to avoid wasting memory */
7606 if (listLength(l
) == 0)
7607 dictDelete(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
7608 decrRefCount(c
->blockingkeys
[j
]);
7610 /* Cleanup the client structure */
7611 zfree(c
->blockingkeys
);
7612 c
->blockingkeys
= NULL
;
7613 c
->flags
&= (~REDIS_BLOCKED
);
7614 server
.blpop_blocked_clients
--;
7615 /* We want to process data if there is some command waiting
7616 * in the input buffer. Note that this is safe even if
7617 * unblockClientWaitingData() gets called from freeClient() because
7618 * freeClient() will be smart enough to call this function
7619 * *after* c->querybuf was set to NULL. */
7620 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0) processInputBuffer(c
);
7623 /* This should be called from any function PUSHing into lists.
7624 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
7625 * 'ele' is the element pushed.
7627 * If the function returns 0 there was no client waiting for a list push
7630 * If the function returns 1 there was a client waiting for a list push
7631 * against this key, the element was passed to this client thus it's not
7632 * needed to actually add it to the list and the caller should return asap. */
7633 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
) {
7634 struct dictEntry
*de
;
7635 redisClient
*receiver
;
7639 de
= dictFind(c
->db
->blockingkeys
,key
);
7640 if (de
== NULL
) return 0;
7641 l
= dictGetEntryVal(de
);
7644 receiver
= ln
->value
;
7646 addReplySds(receiver
,sdsnew("*2\r\n"));
7647 addReplyBulk(receiver
,key
);
7648 addReplyBulk(receiver
,ele
);
7649 unblockClientWaitingData(receiver
);
7653 /* Blocking RPOP/LPOP */
7654 static void blockingPopGenericCommand(redisClient
*c
, int where
) {
7659 for (j
= 1; j
< c
->argc
-1; j
++) {
7660 o
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
7662 if (o
->type
!= REDIS_LIST
) {
7663 addReply(c
,shared
.wrongtypeerr
);
7666 list
*list
= o
->ptr
;
7667 if (listLength(list
) != 0) {
7668 /* If the list contains elements fall back to the usual
7669 * non-blocking POP operation */
7670 robj
*argv
[2], **orig_argv
;
7673 /* We need to alter the command arguments before to call
7674 * popGenericCommand() as the command takes a single key. */
7675 orig_argv
= c
->argv
;
7676 orig_argc
= c
->argc
;
7677 argv
[1] = c
->argv
[j
];
7681 /* Also the return value is different, we need to output
7682 * the multi bulk reply header and the key name. The
7683 * "real" command will add the last element (the value)
7684 * for us. If this souds like an hack to you it's just
7685 * because it is... */
7686 addReplySds(c
,sdsnew("*2\r\n"));
7687 addReplyBulk(c
,argv
[1]);
7688 popGenericCommand(c
,where
);
7690 /* Fix the client structure with the original stuff */
7691 c
->argv
= orig_argv
;
7692 c
->argc
= orig_argc
;
7698 /* If the list is empty or the key does not exists we must block */
7699 timeout
= strtol(c
->argv
[c
->argc
-1]->ptr
,NULL
,10);
7700 if (timeout
> 0) timeout
+= time(NULL
);
7701 blockForKeys(c
,c
->argv
+1,c
->argc
-2,timeout
);
7704 static void blpopCommand(redisClient
*c
) {
7705 blockingPopGenericCommand(c
,REDIS_HEAD
);
7708 static void brpopCommand(redisClient
*c
) {
7709 blockingPopGenericCommand(c
,REDIS_TAIL
);
7712 /* =============================== Replication ============================= */
7714 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) {
7715 ssize_t nwritten
, ret
= size
;
7716 time_t start
= time(NULL
);
7720 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
7721 nwritten
= write(fd
,ptr
,size
);
7722 if (nwritten
== -1) return -1;
7726 if ((time(NULL
)-start
) > timeout
) {
7734 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) {
7735 ssize_t nread
, totread
= 0;
7736 time_t start
= time(NULL
);
7740 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
7741 nread
= read(fd
,ptr
,size
);
7742 if (nread
== -1) return -1;
7747 if ((time(NULL
)-start
) > timeout
) {
7755 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
7762 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
7765 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
7776 static void syncCommand(redisClient
*c
) {
7777 /* ignore SYNC if aleady slave or in monitor mode */
7778 if (c
->flags
& REDIS_SLAVE
) return;
7780 /* SYNC can't be issued when the server has pending data to send to
7781 * the client about already issued commands. We need a fresh reply
7782 * buffer registering the differences between the BGSAVE and the current
7783 * dataset, so that we can copy to other slaves if needed. */
7784 if (listLength(c
->reply
) != 0) {
7785 addReplySds(c
,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
7789 redisLog(REDIS_NOTICE
,"Slave ask for synchronization");
7790 /* Here we need to check if there is a background saving operation
7791 * in progress, or if it is required to start one */
7792 if (server
.bgsavechildpid
!= -1) {
7793 /* Ok a background save is in progress. Let's check if it is a good
7794 * one for replication, i.e. if there is another slave that is
7795 * registering differences since the server forked to save */
7800 listRewind(server
.slaves
,&li
);
7801 while((ln
= listNext(&li
))) {
7803 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) break;
7806 /* Perfect, the server is already registering differences for
7807 * another slave. Set the right state, and copy the buffer. */
7808 listRelease(c
->reply
);
7809 c
->reply
= listDup(slave
->reply
);
7810 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
7811 redisLog(REDIS_NOTICE
,"Waiting for end of BGSAVE for SYNC");
7813 /* No way, we need to wait for the next BGSAVE in order to
7814 * register differences */
7815 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
7816 redisLog(REDIS_NOTICE
,"Waiting for next BGSAVE for SYNC");
7819 /* Ok we don't have a BGSAVE in progress, let's start one */
7820 redisLog(REDIS_NOTICE
,"Starting BGSAVE for SYNC");
7821 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
7822 redisLog(REDIS_NOTICE
,"Replication failed, can't BGSAVE");
7823 addReplySds(c
,sdsnew("-ERR Unalbe to perform background save\r\n"));
7826 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
7829 c
->flags
|= REDIS_SLAVE
;
7831 listAddNodeTail(server
.slaves
,c
);
7835 static void sendBulkToSlave(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
7836 redisClient
*slave
= privdata
;
7838 REDIS_NOTUSED(mask
);
7839 char buf
[REDIS_IOBUF_LEN
];
7840 ssize_t nwritten
, buflen
;
7842 if (slave
->repldboff
== 0) {
7843 /* Write the bulk write count before to transfer the DB. In theory here
7844 * we don't know how much room there is in the output buffer of the
7845 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
7846 * operations) will never be smaller than the few bytes we need. */
7849 bulkcount
= sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
7851 if (write(fd
,bulkcount
,sdslen(bulkcount
)) != (signed)sdslen(bulkcount
))
7859 lseek(slave
->repldbfd
,slave
->repldboff
,SEEK_SET
);
7860 buflen
= read(slave
->repldbfd
,buf
,REDIS_IOBUF_LEN
);
7862 redisLog(REDIS_WARNING
,"Read error sending DB to slave: %s",
7863 (buflen
== 0) ? "premature EOF" : strerror(errno
));
7867 if ((nwritten
= write(fd
,buf
,buflen
)) == -1) {
7868 redisLog(REDIS_VERBOSE
,"Write error sending DB to slave: %s",
7873 slave
->repldboff
+= nwritten
;
7874 if (slave
->repldboff
== slave
->repldbsize
) {
7875 close(slave
->repldbfd
);
7876 slave
->repldbfd
= -1;
7877 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
7878 slave
->replstate
= REDIS_REPL_ONLINE
;
7879 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
,
7880 sendReplyToClient
, slave
) == AE_ERR
) {
7884 addReplySds(slave
,sdsempty());
7885 redisLog(REDIS_NOTICE
,"Synchronization with slave succeeded");
7889 /* This function is called at the end of every backgrond saving.
7890 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
7891 * otherwise REDIS_ERR is passed to the function.
7893 * The goal of this function is to handle slaves waiting for a successful
7894 * background saving in order to perform non-blocking synchronization. */
7895 static void updateSlavesWaitingBgsave(int bgsaveerr
) {
7897 int startbgsave
= 0;
7900 listRewind(server
.slaves
,&li
);
7901 while((ln
= listNext(&li
))) {
7902 redisClient
*slave
= ln
->value
;
7904 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) {
7906 slave
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
7907 } else if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) {
7908 struct redis_stat buf
;
7910 if (bgsaveerr
!= REDIS_OK
) {
7912 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE child returned an error");
7915 if ((slave
->repldbfd
= open(server
.dbfilename
,O_RDONLY
)) == -1 ||
7916 redis_fstat(slave
->repldbfd
,&buf
) == -1) {
7918 redisLog(REDIS_WARNING
,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno
));
7921 slave
->repldboff
= 0;
7922 slave
->repldbsize
= buf
.st_size
;
7923 slave
->replstate
= REDIS_REPL_SEND_BULK
;
7924 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
7925 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
, sendBulkToSlave
, slave
) == AE_ERR
) {
7932 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
7935 listRewind(server
.slaves
,&li
);
7936 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE failed");
7937 while((ln
= listNext(&li
))) {
7938 redisClient
*slave
= ln
->value
;
7940 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
)
7947 static int syncWithMaster(void) {
7948 char buf
[1024], tmpfile
[256], authcmd
[1024];
7950 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
7951 int dfd
, maxtries
= 5;
7954 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
7959 /* AUTH with the master if required. */
7960 if(server
.masterauth
) {
7961 snprintf(authcmd
, 1024, "AUTH %s\r\n", server
.masterauth
);
7962 if (syncWrite(fd
, authcmd
, strlen(server
.masterauth
)+7, 5) == -1) {
7964 redisLog(REDIS_WARNING
,"Unable to AUTH to MASTER: %s",
7968 /* Read the AUTH result. */
7969 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
7971 redisLog(REDIS_WARNING
,"I/O error reading auth result from MASTER: %s",
7975 if (buf
[0] != '+') {
7977 redisLog(REDIS_WARNING
,"Cannot AUTH to MASTER, is the masterauth password correct?");
7982 /* Issue the SYNC command */
7983 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
7985 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
7989 /* Read the bulk write count */
7990 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
7992 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
7996 if (buf
[0] != '$') {
7998 redisLog(REDIS_WARNING
,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
8001 dumpsize
= strtol(buf
+1,NULL
,10);
8002 redisLog(REDIS_NOTICE
,"Receiving %ld bytes data dump from MASTER",dumpsize
);
8003 /* Read the bulk write data on a temp file */
8005 snprintf(tmpfile
,256,
8006 "temp-%d.%ld.rdb",(int)time(NULL
),(long int)getpid());
8007 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
|O_EXCL
,0644);
8008 if (dfd
!= -1) break;
8013 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
8017 int nread
, nwritten
;
8019 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
8021 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
8027 nwritten
= write(dfd
,buf
,nread
);
8028 if (nwritten
== -1) {
8029 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
8037 if (rename(tmpfile
,server
.dbfilename
) == -1) {
8038 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
8044 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
8045 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
8049 server
.master
= createClient(fd
);
8050 server
.master
->flags
|= REDIS_MASTER
;
8051 server
.master
->authenticated
= 1;
8052 server
.replstate
= REDIS_REPL_CONNECTED
;
8056 static void slaveofCommand(redisClient
*c
) {
8057 if (!strcasecmp(c
->argv
[1]->ptr
,"no") &&
8058 !strcasecmp(c
->argv
[2]->ptr
,"one")) {
8059 if (server
.masterhost
) {
8060 sdsfree(server
.masterhost
);
8061 server
.masterhost
= NULL
;
8062 if (server
.master
) freeClient(server
.master
);
8063 server
.replstate
= REDIS_REPL_NONE
;
8064 redisLog(REDIS_NOTICE
,"MASTER MODE enabled (user request)");
8067 sdsfree(server
.masterhost
);
8068 server
.masterhost
= sdsdup(c
->argv
[1]->ptr
);
8069 server
.masterport
= atoi(c
->argv
[2]->ptr
);
8070 if (server
.master
) freeClient(server
.master
);
8071 server
.replstate
= REDIS_REPL_CONNECT
;
8072 redisLog(REDIS_NOTICE
,"SLAVE OF %s:%d enabled (user request)",
8073 server
.masterhost
, server
.masterport
);
8075 addReply(c
,shared
.ok
);
8078 /* ============================ Maxmemory directive ======================== */
8080 /* Try to free one object form the pre-allocated objects free list.
8081 * This is useful under low mem conditions as by default we take 1 million
8082 * free objects allocated. On success REDIS_OK is returned, otherwise
8084 static int tryFreeOneObjectFromFreelist(void) {
8087 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
8088 if (listLength(server
.objfreelist
)) {
8089 listNode
*head
= listFirst(server
.objfreelist
);
8090 o
= listNodeValue(head
);
8091 listDelNode(server
.objfreelist
,head
);
8092 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
8096 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
8101 /* This function gets called when 'maxmemory' is set on the config file to limit
8102 * the max memory used by the server, and we are out of memory.
8103 * This function will try to, in order:
8105 * - Free objects from the free list
8106 * - Try to remove keys with an EXPIRE set
8108 * It is not possible to free enough memory to reach used-memory < maxmemory
8109 * the server will start refusing commands that will enlarge even more the
8112 static void freeMemoryIfNeeded(void) {
8113 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
8114 int j
, k
, freed
= 0;
8116 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
8117 for (j
= 0; j
< server
.dbnum
; j
++) {
8119 robj
*minkey
= NULL
;
8120 struct dictEntry
*de
;
8122 if (dictSize(server
.db
[j
].expires
)) {
8124 /* From a sample of three keys drop the one nearest to
8125 * the natural expire */
8126 for (k
= 0; k
< 3; k
++) {
8129 de
= dictGetRandomKey(server
.db
[j
].expires
);
8130 t
= (time_t) dictGetEntryVal(de
);
8131 if (minttl
== -1 || t
< minttl
) {
8132 minkey
= dictGetEntryKey(de
);
8136 deleteKey(server
.db
+j
,minkey
);
8139 if (!freed
) return; /* nothing to free... */
8143 /* ============================== Append Only file ========================== */
8145 /* Write the append only file buffer on disk.
8147 * Since we are required to write the AOF before replying to the client,
8148 * and the only way the client socket can get a write is entering when the
8149 * the event loop, we accumulate all the AOF writes in a memory
8150 * buffer and write it on disk using this function just before entering
8151 * the event loop again. */
8152 static void flushAppendOnlyFile(void) {
8156 if (sdslen(server
.aofbuf
) == 0) return;
8158 /* We want to perform a single write. This should be guaranteed atomic
8159 * at least if the filesystem we are writing is a real physical one.
8160 * While this will save us against the server being killed I don't think
8161 * there is much to do about the whole server stopping for power problems
8163 nwritten
= write(server
.appendfd
,server
.aofbuf
,sdslen(server
.aofbuf
));
8164 if (nwritten
!= (signed)sdslen(server
.aofbuf
)) {
8165 /* Ooops, we are in troubles. The best thing to do for now is
8166 * aborting instead of giving the illusion that everything is
8167 * working as expected. */
8168 if (nwritten
== -1) {
8169 redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
));
8171 redisLog(REDIS_WARNING
,"Exiting on short write while writing to the append-only file: %s",strerror(errno
));
8175 sdsfree(server
.aofbuf
);
8176 server
.aofbuf
= sdsempty();
8178 /* Fsync if needed */
8180 if (server
.appendfsync
== APPENDFSYNC_ALWAYS
||
8181 (server
.appendfsync
== APPENDFSYNC_EVERYSEC
&&
8182 now
-server
.lastfsync
> 1))
8184 /* aof_fsync is defined as fdatasync() for Linux in order to avoid
8185 * flushing metadata. */
8186 aof_fsync(server
.appendfd
); /* Let's try to get this data on the disk */
8187 server
.lastfsync
= now
;
8191 static sds
catAppendOnlyGenericCommand(sds buf
, int argc
, robj
**argv
) {
8193 buf
= sdscatprintf(buf
,"*%d\r\n",argc
);
8194 for (j
= 0; j
< argc
; j
++) {
8195 robj
*o
= getDecodedObject(argv
[j
]);
8196 buf
= sdscatprintf(buf
,"$%lu\r\n",(unsigned long)sdslen(o
->ptr
));
8197 buf
= sdscatlen(buf
,o
->ptr
,sdslen(o
->ptr
));
8198 buf
= sdscatlen(buf
,"\r\n",2);
8204 static sds
catAppendOnlyExpireAtCommand(sds buf
, robj
*key
, robj
*seconds
) {
8209 /* Make sure we can use strtol */
8210 seconds
= getDecodedObject(seconds
);
8211 when
= time(NULL
)+strtol(seconds
->ptr
,NULL
,10);
8212 decrRefCount(seconds
);
8214 argv
[0] = createStringObject("EXPIREAT",8);
8216 argv
[2] = createObject(REDIS_STRING
,
8217 sdscatprintf(sdsempty(),"%ld",when
));
8218 buf
= catAppendOnlyGenericCommand(buf
, argc
, argv
);
8219 decrRefCount(argv
[0]);
8220 decrRefCount(argv
[2]);
8224 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
8225 sds buf
= sdsempty();
8228 /* The DB this command was targetting is not the same as the last command
8229 * we appendend. To issue a SELECT command is needed. */
8230 if (dictid
!= server
.appendseldb
) {
8233 snprintf(seldb
,sizeof(seldb
),"%d",dictid
);
8234 buf
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
8235 (unsigned long)strlen(seldb
),seldb
);
8236 server
.appendseldb
= dictid
;
8239 if (cmd
->proc
== expireCommand
) {
8240 /* Translate EXPIRE into EXPIREAT */
8241 buf
= catAppendOnlyExpireAtCommand(buf
,argv
[1],argv
[2]);
8242 } else if (cmd
->proc
== setexCommand
) {
8243 /* Translate SETEX to SET and EXPIREAT */
8244 tmpargv
[0] = createStringObject("SET",3);
8245 tmpargv
[1] = argv
[1];
8246 tmpargv
[2] = argv
[3];
8247 buf
= catAppendOnlyGenericCommand(buf
,3,tmpargv
);
8248 decrRefCount(tmpargv
[0]);
8249 buf
= catAppendOnlyExpireAtCommand(buf
,argv
[1],argv
[2]);
8251 buf
= catAppendOnlyGenericCommand(buf
,argc
,argv
);
8254 /* Append to the AOF buffer. This will be flushed on disk just before
8255 * of re-entering the event loop, so before the client will get a
8256 * positive reply about the operation performed. */
8257 server
.aofbuf
= sdscatlen(server
.aofbuf
,buf
,sdslen(buf
));
8259 /* If a background append only file rewriting is in progress we want to
8260 * accumulate the differences between the child DB and the current one
8261 * in a buffer, so that when the child process will do its work we
8262 * can append the differences to the new append only file. */
8263 if (server
.bgrewritechildpid
!= -1)
8264 server
.bgrewritebuf
= sdscatlen(server
.bgrewritebuf
,buf
,sdslen(buf
));
8269 /* In Redis commands are always executed in the context of a client, so in
8270 * order to load the append only file we need to create a fake client. */
8271 static struct redisClient
*createFakeClient(void) {
8272 struct redisClient
*c
= zmalloc(sizeof(*c
));
8276 c
->querybuf
= sdsempty();
8280 /* We set the fake client as a slave waiting for the synchronization
8281 * so that Redis will not try to send replies to this client. */
8282 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
8283 c
->reply
= listCreate();
8284 listSetFreeMethod(c
->reply
,decrRefCount
);
8285 listSetDupMethod(c
->reply
,dupClientReplyValue
);
8286 initClientMultiState(c
);
8290 static void freeFakeClient(struct redisClient
*c
) {
8291 sdsfree(c
->querybuf
);
8292 listRelease(c
->reply
);
8293 freeClientMultiState(c
);
8297 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
8298 * error (the append only file is zero-length) REDIS_ERR is returned. On
8299 * fatal error an error message is logged and the program exists. */
8300 int loadAppendOnlyFile(char *filename
) {
8301 struct redisClient
*fakeClient
;
8302 FILE *fp
= fopen(filename
,"r");
8303 struct redis_stat sb
;
8304 unsigned long long loadedkeys
= 0;
8305 int appendonly
= server
.appendonly
;
8307 if (redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0)
8311 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
8315 /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
8316 * to the same file we're about to read. */
8317 server
.appendonly
= 0;
8319 fakeClient
= createFakeClient();
8326 struct redisCommand
*cmd
;
8328 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
8334 if (buf
[0] != '*') goto fmterr
;
8336 argv
= zmalloc(sizeof(robj
*)*argc
);
8337 for (j
= 0; j
< argc
; j
++) {
8338 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
8339 if (buf
[0] != '$') goto fmterr
;
8340 len
= strtol(buf
+1,NULL
,10);
8341 argsds
= sdsnewlen(NULL
,len
);
8342 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
8343 argv
[j
] = createObject(REDIS_STRING
,argsds
);
8344 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
8347 /* Command lookup */
8348 cmd
= lookupCommand(argv
[0]->ptr
);
8350 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
8353 /* Try object encoding */
8354 if (cmd
->flags
& REDIS_CMD_BULK
)
8355 argv
[argc
-1] = tryObjectEncoding(argv
[argc
-1]);
8356 /* Run the command in the context of a fake client */
8357 fakeClient
->argc
= argc
;
8358 fakeClient
->argv
= argv
;
8359 cmd
->proc(fakeClient
);
8360 /* Discard the reply objects list from the fake client */
8361 while(listLength(fakeClient
->reply
))
8362 listDelNode(fakeClient
->reply
,listFirst(fakeClient
->reply
));
8363 /* Clean up, ready for the next command */
8364 for (j
= 0; j
< argc
; j
++) decrRefCount(argv
[j
]);
8366 /* Handle swapping while loading big datasets when VM is on */
8368 if (server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
8369 while (zmalloc_used_memory() > server
.vm_max_memory
) {
8370 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
8375 /* This point can only be reached when EOF is reached without errors.
8376 * If the client is in the middle of a MULTI/EXEC, log error and quit. */
8377 if (fakeClient
->flags
& REDIS_MULTI
) goto readerr
;
8380 freeFakeClient(fakeClient
);
8381 server
.appendonly
= appendonly
;
8386 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
8388 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
8392 redisLog(REDIS_WARNING
,"Bad file format reading the append only file");
8396 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
8397 static int fwriteBulkObject(FILE *fp
, robj
*obj
) {
8401 /* Avoid the incr/decr ref count business if possible to help
8402 * copy-on-write (we are often in a child process when this function
8404 * Also makes sure that key objects don't get incrRefCount-ed when VM
8406 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
8407 obj
= getDecodedObject(obj
);
8410 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(long)sdslen(obj
->ptr
));
8411 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) goto err
;
8412 if (sdslen(obj
->ptr
) && fwrite(obj
->ptr
,sdslen(obj
->ptr
),1,fp
) == 0)
8414 if (fwrite("\r\n",2,1,fp
) == 0) goto err
;
8415 if (decrrc
) decrRefCount(obj
);
8418 if (decrrc
) decrRefCount(obj
);
8422 /* Write binary-safe string into a file in the bulkformat
8423 * $<count>\r\n<payload>\r\n */
8424 static int fwriteBulkString(FILE *fp
, char *s
, unsigned long len
) {
8427 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(unsigned long)len
);
8428 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
8429 if (len
&& fwrite(s
,len
,1,fp
) == 0) return 0;
8430 if (fwrite("\r\n",2,1,fp
) == 0) return 0;
8434 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
8435 static int fwriteBulkDouble(FILE *fp
, double d
) {
8436 char buf
[128], dbuf
[128];
8438 snprintf(dbuf
,sizeof(dbuf
),"%.17g\r\n",d
);
8439 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(dbuf
)-2);
8440 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
8441 if (fwrite(dbuf
,strlen(dbuf
),1,fp
) == 0) return 0;
8445 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
8446 static int fwriteBulkLong(FILE *fp
, long l
) {
8447 char buf
[128], lbuf
[128];
8449 snprintf(lbuf
,sizeof(lbuf
),"%ld\r\n",l
);
8450 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(lbuf
)-2);
8451 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
8452 if (fwrite(lbuf
,strlen(lbuf
),1,fp
) == 0) return 0;
8456 /* Write a sequence of commands able to fully rebuild the dataset into
8457 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
8458 static int rewriteAppendOnlyFile(char *filename
) {
8459 dictIterator
*di
= NULL
;
8464 time_t now
= time(NULL
);
8466 /* Note that we have to use a different temp name here compared to the
8467 * one used by rewriteAppendOnlyFileBackground() function. */
8468 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
8469 fp
= fopen(tmpfile
,"w");
8471 redisLog(REDIS_WARNING
, "Failed rewriting the append only file: %s", strerror(errno
));
8474 for (j
= 0; j
< server
.dbnum
; j
++) {
8475 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
8476 redisDb
*db
= server
.db
+j
;
8478 if (dictSize(d
) == 0) continue;
8479 di
= dictGetIterator(d
);
8485 /* SELECT the new DB */
8486 if (fwrite(selectcmd
,sizeof(selectcmd
)-1,1,fp
) == 0) goto werr
;
8487 if (fwriteBulkLong(fp
,j
) == 0) goto werr
;
8489 /* Iterate this DB writing every entry */
8490 while((de
= dictNext(di
)) != NULL
) {
8495 key
= dictGetEntryKey(de
);
8496 /* If the value for this key is swapped, load a preview in memory.
8497 * We use a "swapped" flag to remember if we need to free the
8498 * value object instead to just increment the ref count anyway
8499 * in order to avoid copy-on-write of pages if we are forked() */
8500 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
8501 key
->storage
== REDIS_VM_SWAPPING
) {
8502 o
= dictGetEntryVal(de
);
8505 o
= vmPreviewObject(key
);
8508 expiretime
= getExpire(db
,key
);
8510 /* Save the key and associated value */
8511 if (o
->type
== REDIS_STRING
) {
8512 /* Emit a SET command */
8513 char cmd
[]="*3\r\n$3\r\nSET\r\n";
8514 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8516 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8517 if (fwriteBulkObject(fp
,o
) == 0) goto werr
;
8518 } else if (o
->type
== REDIS_LIST
) {
8519 /* Emit the RPUSHes needed to rebuild the list */
8520 list
*list
= o
->ptr
;
8524 listRewind(list
,&li
);
8525 while((ln
= listNext(&li
))) {
8526 char cmd
[]="*3\r\n$5\r\nRPUSH\r\n";
8527 robj
*eleobj
= listNodeValue(ln
);
8529 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8530 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8531 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
8533 } else if (o
->type
== REDIS_SET
) {
8534 /* Emit the SADDs needed to rebuild the set */
8536 dictIterator
*di
= dictGetIterator(set
);
8539 while((de
= dictNext(di
)) != NULL
) {
8540 char cmd
[]="*3\r\n$4\r\nSADD\r\n";
8541 robj
*eleobj
= dictGetEntryKey(de
);
8543 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8544 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8545 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
8547 dictReleaseIterator(di
);
8548 } else if (o
->type
== REDIS_ZSET
) {
8549 /* Emit the ZADDs needed to rebuild the sorted set */
8551 dictIterator
*di
= dictGetIterator(zs
->dict
);
8554 while((de
= dictNext(di
)) != NULL
) {
8555 char cmd
[]="*4\r\n$4\r\nZADD\r\n";
8556 robj
*eleobj
= dictGetEntryKey(de
);
8557 double *score
= dictGetEntryVal(de
);
8559 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8560 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8561 if (fwriteBulkDouble(fp
,*score
) == 0) goto werr
;
8562 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
8564 dictReleaseIterator(di
);
8565 } else if (o
->type
== REDIS_HASH
) {
8566 char cmd
[]="*4\r\n$4\r\nHSET\r\n";
8568 /* Emit the HSETs needed to rebuild the hash */
8569 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
8570 unsigned char *p
= zipmapRewind(o
->ptr
);
8571 unsigned char *field
, *val
;
8572 unsigned int flen
, vlen
;
8574 while((p
= zipmapNext(p
,&field
,&flen
,&val
,&vlen
)) != NULL
) {
8575 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8576 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8577 if (fwriteBulkString(fp
,(char*)field
,flen
) == -1)
8579 if (fwriteBulkString(fp
,(char*)val
,vlen
) == -1)
8583 dictIterator
*di
= dictGetIterator(o
->ptr
);
8586 while((de
= dictNext(di
)) != NULL
) {
8587 robj
*field
= dictGetEntryKey(de
);
8588 robj
*val
= dictGetEntryVal(de
);
8590 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8591 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8592 if (fwriteBulkObject(fp
,field
) == -1) return -1;
8593 if (fwriteBulkObject(fp
,val
) == -1) return -1;
8595 dictReleaseIterator(di
);
8598 redisPanic("Unknown object type");
8600 /* Save the expire time */
8601 if (expiretime
!= -1) {
8602 char cmd
[]="*3\r\n$8\r\nEXPIREAT\r\n";
8603 /* If this key is already expired skip it */
8604 if (expiretime
< now
) continue;
8605 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8606 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8607 if (fwriteBulkLong(fp
,expiretime
) == 0) goto werr
;
8609 if (swapped
) decrRefCount(o
);
8611 dictReleaseIterator(di
);
8614 /* Make sure data will not remain on the OS's output buffers */
8619 /* Use RENAME to make sure the DB file is changed atomically only
8620 * if the generate DB file is ok. */
8621 if (rename(tmpfile
,filename
) == -1) {
8622 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
8626 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
8632 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
8633 if (di
) dictReleaseIterator(di
);
8637 /* This is how rewriting of the append only file in background works:
8639 * 1) The user calls BGREWRITEAOF
8640 * 2) Redis calls this function, that forks():
8641 * 2a) the child rewrite the append only file in a temp file.
8642 * 2b) the parent accumulates differences in server.bgrewritebuf.
8643 * 3) When the child finished '2a' exists.
8644 * 4) The parent will trap the exit code, if it's OK, will append the
8645 * data accumulated into server.bgrewritebuf into the temp file, and
8646 * finally will rename(2) the temp file in the actual file name.
8647 * The the new file is reopened as the new append only file. Profit!
8649 static int rewriteAppendOnlyFileBackground(void) {
8652 if (server
.bgrewritechildpid
!= -1) return REDIS_ERR
;
8653 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
8654 if ((childpid
= fork()) == 0) {
8658 if (server
.vm_enabled
) vmReopenSwapFile();
8660 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
8661 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
8668 if (childpid
== -1) {
8669 redisLog(REDIS_WARNING
,
8670 "Can't rewrite append only file in background: fork: %s",
8674 redisLog(REDIS_NOTICE
,
8675 "Background append only file rewriting started by pid %d",childpid
);
8676 server
.bgrewritechildpid
= childpid
;
8677 updateDictResizePolicy();
8678 /* We set appendseldb to -1 in order to force the next call to the
8679 * feedAppendOnlyFile() to issue a SELECT command, so the differences
8680 * accumulated by the parent into server.bgrewritebuf will start
8681 * with a SELECT statement and it will be safe to merge. */
8682 server
.appendseldb
= -1;
8685 return REDIS_OK
; /* unreached */
8688 static void bgrewriteaofCommand(redisClient
*c
) {
8689 if (server
.bgrewritechildpid
!= -1) {
8690 addReplySds(c
,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
8693 if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
8694 char *status
= "+Background append only file rewriting started\r\n";
8695 addReplySds(c
,sdsnew(status
));
8697 addReply(c
,shared
.err
);
8701 static void aofRemoveTempFile(pid_t childpid
) {
8704 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
8708 /* Virtual Memory is composed mainly of two subsystems:
8709 * - Blocking Virutal Memory
8710 * - Threaded Virtual Memory I/O
8711 * The two parts are not fully decoupled, but functions are split among two
8712 * different sections of the source code (delimited by comments) in order to
8713 * make more clear what functionality is about the blocking VM and what about
8714 * the threaded (not blocking) VM.
8718 * Redis VM is a blocking VM (one that blocks reading swapped values from
8719 * disk into memory when a value swapped out is needed in memory) that is made
8720 * unblocking by trying to examine the command argument vector in order to
8721 * load in background values that will likely be needed in order to exec
8722 * the command. The command is executed only once all the relevant keys
8723 * are loaded into memory.
8725 * This basically is almost as simple of a blocking VM, but almost as parallel
8726 * as a fully non-blocking VM.
8729 /* =================== Virtual Memory - Blocking Side ====================== */
8731 static void vmInit(void) {
8737 if (server
.vm_max_threads
!= 0)
8738 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
8740 redisLog(REDIS_NOTICE
,"Using '%s' as swap file",server
.vm_swap_file
);
8741 /* Try to open the old swap file, otherwise create it */
8742 if ((server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b")) == NULL
) {
8743 server
.vm_fp
= fopen(server
.vm_swap_file
,"w+b");
8745 if (server
.vm_fp
== NULL
) {
8746 redisLog(REDIS_WARNING
,
8747 "Can't open the swap file: %s. Exiting.",
8751 server
.vm_fd
= fileno(server
.vm_fp
);
8752 /* Lock the swap file for writing, this is useful in order to avoid
8753 * another instance to use the same swap file for a config error. */
8754 fl
.l_type
= F_WRLCK
;
8755 fl
.l_whence
= SEEK_SET
;
8756 fl
.l_start
= fl
.l_len
= 0;
8757 if (fcntl(server
.vm_fd
,F_SETLK
,&fl
) == -1) {
8758 redisLog(REDIS_WARNING
,
8759 "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
));
8763 server
.vm_next_page
= 0;
8764 server
.vm_near_pages
= 0;
8765 server
.vm_stats_used_pages
= 0;
8766 server
.vm_stats_swapped_objects
= 0;
8767 server
.vm_stats_swapouts
= 0;
8768 server
.vm_stats_swapins
= 0;
8769 totsize
= server
.vm_pages
*server
.vm_page_size
;
8770 redisLog(REDIS_NOTICE
,"Allocating %lld bytes of swap file",totsize
);
8771 if (ftruncate(server
.vm_fd
,totsize
) == -1) {
8772 redisLog(REDIS_WARNING
,"Can't ftruncate swap file: %s. Exiting.",
8776 redisLog(REDIS_NOTICE
,"Swap file allocated with success");
8778 server
.vm_bitmap
= zmalloc((server
.vm_pages
+7)/8);
8779 redisLog(REDIS_VERBOSE
,"Allocated %lld bytes page table for %lld pages",
8780 (long long) (server
.vm_pages
+7)/8, server
.vm_pages
);
8781 memset(server
.vm_bitmap
,0,(server
.vm_pages
+7)/8);
8783 /* Initialize threaded I/O (used by Virtual Memory) */
8784 server
.io_newjobs
= listCreate();
8785 server
.io_processing
= listCreate();
8786 server
.io_processed
= listCreate();
8787 server
.io_ready_clients
= listCreate();
8788 pthread_mutex_init(&server
.io_mutex
,NULL
);
8789 pthread_mutex_init(&server
.obj_freelist_mutex
,NULL
);
8790 pthread_mutex_init(&server
.io_swapfile_mutex
,NULL
);
8791 server
.io_active_threads
= 0;
8792 if (pipe(pipefds
) == -1) {
8793 redisLog(REDIS_WARNING
,"Unable to intialized VM: pipe(2): %s. Exiting."
8797 server
.io_ready_pipe_read
= pipefds
[0];
8798 server
.io_ready_pipe_write
= pipefds
[1];
8799 redisAssert(anetNonBlock(NULL
,server
.io_ready_pipe_read
) != ANET_ERR
);
8800 /* LZF requires a lot of stack */
8801 pthread_attr_init(&server
.io_threads_attr
);
8802 pthread_attr_getstacksize(&server
.io_threads_attr
, &stacksize
);
8803 while (stacksize
< REDIS_THREAD_STACK_SIZE
) stacksize
*= 2;
8804 pthread_attr_setstacksize(&server
.io_threads_attr
, stacksize
);
8805 /* Listen for events in the threaded I/O pipe */
8806 if (aeCreateFileEvent(server
.el
, server
.io_ready_pipe_read
, AE_READABLE
,
8807 vmThreadedIOCompletedJob
, NULL
) == AE_ERR
)
8808 oom("creating file event");
8811 /* Mark the page as used */
8812 static void vmMarkPageUsed(off_t page
) {
8813 off_t byte
= page
/8;
8815 redisAssert(vmFreePage(page
) == 1);
8816 server
.vm_bitmap
[byte
] |= 1<<bit
;
8819 /* Mark N contiguous pages as used, with 'page' being the first. */
8820 static void vmMarkPagesUsed(off_t page
, off_t count
) {
8823 for (j
= 0; j
< count
; j
++)
8824 vmMarkPageUsed(page
+j
);
8825 server
.vm_stats_used_pages
+= count
;
8826 redisLog(REDIS_DEBUG
,"Mark USED pages: %lld pages at %lld\n",
8827 (long long)count
, (long long)page
);
8830 /* Mark the page as free */
8831 static void vmMarkPageFree(off_t page
) {
8832 off_t byte
= page
/8;
8834 redisAssert(vmFreePage(page
) == 0);
8835 server
.vm_bitmap
[byte
] &= ~(1<<bit
);
8838 /* Mark N contiguous pages as free, with 'page' being the first. */
8839 static void vmMarkPagesFree(off_t page
, off_t count
) {
8842 for (j
= 0; j
< count
; j
++)
8843 vmMarkPageFree(page
+j
);
8844 server
.vm_stats_used_pages
-= count
;
8845 redisLog(REDIS_DEBUG
,"Mark FREE pages: %lld pages at %lld\n",
8846 (long long)count
, (long long)page
);
8849 /* Test if the page is free */
8850 static int vmFreePage(off_t page
) {
8851 off_t byte
= page
/8;
8853 return (server
.vm_bitmap
[byte
] & (1<<bit
)) == 0;
8856 /* Find N contiguous free pages storing the first page of the cluster in *first.
8857 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
8858 * REDIS_ERR is returned.
8860 * This function uses a simple algorithm: we try to allocate
8861 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
8862 * again from the start of the swap file searching for free spaces.
8864 * If it looks pretty clear that there are no free pages near our offset
8865 * we try to find less populated places doing a forward jump of
8866 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
8867 * without hurry, and then we jump again and so forth...
8869 * This function can be improved using a free list to avoid to guess
8870 * too much, since we could collect data about freed pages.
8872 * note: I implemented this function just after watching an episode of
8873 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
8875 static int vmFindContiguousPages(off_t
*first
, off_t n
) {
8876 off_t base
, offset
= 0, since_jump
= 0, numfree
= 0;
8878 if (server
.vm_near_pages
== REDIS_VM_MAX_NEAR_PAGES
) {
8879 server
.vm_near_pages
= 0;
8880 server
.vm_next_page
= 0;
8882 server
.vm_near_pages
++; /* Yet another try for pages near to the old ones */
8883 base
= server
.vm_next_page
;
8885 while(offset
< server
.vm_pages
) {
8886 off_t
this = base
+offset
;
8888 /* If we overflow, restart from page zero */
8889 if (this >= server
.vm_pages
) {
8890 this -= server
.vm_pages
;
8892 /* Just overflowed, what we found on tail is no longer
8893 * interesting, as it's no longer contiguous. */
8897 if (vmFreePage(this)) {
8898 /* This is a free page */
8900 /* Already got N free pages? Return to the caller, with success */
8902 *first
= this-(n
-1);
8903 server
.vm_next_page
= this+1;
8904 redisLog(REDIS_DEBUG
, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n
, (long long) *first
);
8908 /* The current one is not a free page */
8912 /* Fast-forward if the current page is not free and we already
8913 * searched enough near this place. */
8915 if (!numfree
&& since_jump
>= REDIS_VM_MAX_RANDOM_JUMP
/4) {
8916 offset
+= random() % REDIS_VM_MAX_RANDOM_JUMP
;
8918 /* Note that even if we rewind after the jump, we are don't need
8919 * to make sure numfree is set to zero as we only jump *if* it
8920 * is set to zero. */
8922 /* Otherwise just check the next page */
8929 /* Write the specified object at the specified page of the swap file */
8930 static int vmWriteObjectOnSwap(robj
*o
, off_t page
) {
8931 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
8932 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
8933 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
8934 redisLog(REDIS_WARNING
,
8935 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
8939 rdbSaveObject(server
.vm_fp
,o
);
8940 fflush(server
.vm_fp
);
8941 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
8945 /* Swap the 'val' object relative to 'key' into disk. Store all the information
8946 * needed to later retrieve the object into the key object.
8947 * If we can't find enough contiguous empty pages to swap the object on disk
8948 * REDIS_ERR is returned. */
8949 static int vmSwapObjectBlocking(robj
*key
, robj
*val
) {
8950 off_t pages
= rdbSavedObjectPages(val
,NULL
);
8953 assert(key
->storage
== REDIS_VM_MEMORY
);
8954 assert(key
->refcount
== 1);
8955 if (vmFindContiguousPages(&page
,pages
) == REDIS_ERR
) return REDIS_ERR
;
8956 if (vmWriteObjectOnSwap(val
,page
) == REDIS_ERR
) return REDIS_ERR
;
8957 key
->vm
.page
= page
;
8958 key
->vm
.usedpages
= pages
;
8959 key
->storage
= REDIS_VM_SWAPPED
;
8960 key
->vtype
= val
->type
;
8961 decrRefCount(val
); /* Deallocate the object from memory. */
8962 vmMarkPagesUsed(page
,pages
);
8963 redisLog(REDIS_DEBUG
,"VM: object %s swapped out at %lld (%lld pages)",
8964 (unsigned char*) key
->ptr
,
8965 (unsigned long long) page
, (unsigned long long) pages
);
8966 server
.vm_stats_swapped_objects
++;
8967 server
.vm_stats_swapouts
++;
8971 static robj
*vmReadObjectFromSwap(off_t page
, int type
) {
8974 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
8975 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
8976 redisLog(REDIS_WARNING
,
8977 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
8981 o
= rdbLoadObject(type
,server
.vm_fp
);
8983 redisLog(REDIS_WARNING
, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno
));
8986 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
8990 /* Load the value object relative to the 'key' object from swap to memory.
8991 * The newly allocated object is returned.
8993 * If preview is true the unserialized object is returned to the caller but
8994 * no changes are made to the key object, nor the pages are marked as freed */
8995 static robj
*vmGenericLoadObject(robj
*key
, int preview
) {
8998 redisAssert(key
->storage
== REDIS_VM_SWAPPED
|| key
->storage
== REDIS_VM_LOADING
);
8999 val
= vmReadObjectFromSwap(key
->vm
.page
,key
->vtype
);
9001 key
->storage
= REDIS_VM_MEMORY
;
9002 key
->vm
.atime
= server
.unixtime
;
9003 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
9004 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk",
9005 (unsigned char*) key
->ptr
);
9006 server
.vm_stats_swapped_objects
--;
9008 redisLog(REDIS_DEBUG
, "VM: object %s previewed from disk",
9009 (unsigned char*) key
->ptr
);
9011 server
.vm_stats_swapins
++;
9015 /* Plain object loading, from swap to memory */
9016 static robj
*vmLoadObject(robj
*key
) {
9017 /* If we are loading the object in background, stop it, we
9018 * need to load this object synchronously ASAP. */
9019 if (key
->storage
== REDIS_VM_LOADING
)
9020 vmCancelThreadedIOJob(key
);
9021 return vmGenericLoadObject(key
,0);
9024 /* Just load the value on disk, without to modify the key.
9025 * This is useful when we want to perform some operation on the value
9026 * without to really bring it from swap to memory, like while saving the
9027 * dataset or rewriting the append only log. */
9028 static robj
*vmPreviewObject(robj
*key
) {
9029 return vmGenericLoadObject(key
,1);
9032 /* How a good candidate is this object for swapping?
9033 * The better candidate it is, the greater the returned value.
9035 * Currently we try to perform a fast estimation of the object size in
9036 * memory, and combine it with aging informations.
9038 * Basically swappability = idle-time * log(estimated size)
9040 * Bigger objects are preferred over smaller objects, but not
9041 * proportionally, this is why we use the logarithm. This algorithm is
9042 * just a first try and will probably be tuned later. */
9043 static double computeObjectSwappability(robj
*o
) {
9044 time_t age
= server
.unixtime
- o
->vm
.atime
;
9048 struct dictEntry
*de
;
9051 if (age
<= 0) return 0;
9054 if (o
->encoding
!= REDIS_ENCODING_RAW
) {
9057 asize
= sdslen(o
->ptr
)+sizeof(*o
)+sizeof(long)*2;
9062 listNode
*ln
= listFirst(l
);
9064 asize
= sizeof(list
);
9066 robj
*ele
= ln
->value
;
9069 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
9070 (sizeof(*o
)+sdslen(ele
->ptr
)) :
9072 asize
+= (sizeof(listNode
)+elesize
)*listLength(l
);
9077 z
= (o
->type
== REDIS_ZSET
);
9078 d
= z
? ((zset
*)o
->ptr
)->dict
: o
->ptr
;
9080 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
9081 if (z
) asize
+= sizeof(zset
)-sizeof(dict
);
9086 de
= dictGetRandomKey(d
);
9087 ele
= dictGetEntryKey(de
);
9088 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
9089 (sizeof(*o
)+sdslen(ele
->ptr
)) :
9091 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
9092 if (z
) asize
+= sizeof(zskiplistNode
)*dictSize(d
);
9096 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
9097 unsigned char *p
= zipmapRewind((unsigned char*)o
->ptr
);
9098 unsigned int len
= zipmapLen((unsigned char*)o
->ptr
);
9099 unsigned int klen
, vlen
;
9100 unsigned char *key
, *val
;
9102 if ((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) == NULL
) {
9106 asize
= len
*(klen
+vlen
+3);
9107 } else if (o
->encoding
== REDIS_ENCODING_HT
) {
9109 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
9114 de
= dictGetRandomKey(d
);
9115 ele
= dictGetEntryKey(de
);
9116 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
9117 (sizeof(*o
)+sdslen(ele
->ptr
)) :
9119 ele
= dictGetEntryVal(de
);
9120 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
9121 (sizeof(*o
)+sdslen(ele
->ptr
)) :
9123 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
9128 return (double)age
*log(1+asize
);
9131 /* Try to swap an object that's a good candidate for swapping.
9132 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
9133 * to swap any object at all.
9135 * If 'usethreaded' is true, Redis will try to swap the object in background
9136 * using I/O threads. */
9137 static int vmSwapOneObject(int usethreads
) {
9139 struct dictEntry
*best
= NULL
;
9140 double best_swappability
= 0;
9141 redisDb
*best_db
= NULL
;
9144 for (j
= 0; j
< server
.dbnum
; j
++) {
9145 redisDb
*db
= server
.db
+j
;
9146 /* Why maxtries is set to 100?
9147 * Because this way (usually) we'll find 1 object even if just 1% - 2%
9148 * are swappable objects */
9151 if (dictSize(db
->dict
) == 0) continue;
9152 for (i
= 0; i
< 5; i
++) {
9154 double swappability
;
9156 if (maxtries
) maxtries
--;
9157 de
= dictGetRandomKey(db
->dict
);
9158 key
= dictGetEntryKey(de
);
9159 val
= dictGetEntryVal(de
);
9160 /* Only swap objects that are currently in memory.
9162 * Also don't swap shared objects if threaded VM is on, as we
9163 * try to ensure that the main thread does not touch the
9164 * object while the I/O thread is using it, but we can't
9165 * control other keys without adding additional mutex. */
9166 if (key
->storage
!= REDIS_VM_MEMORY
||
9167 (server
.vm_max_threads
!= 0 && val
->refcount
!= 1)) {
9168 if (maxtries
) i
--; /* don't count this try */
9171 swappability
= computeObjectSwappability(val
);
9172 if (!best
|| swappability
> best_swappability
) {
9174 best_swappability
= swappability
;
9179 if (best
== NULL
) return REDIS_ERR
;
9180 key
= dictGetEntryKey(best
);
9181 val
= dictGetEntryVal(best
);
9183 redisLog(REDIS_DEBUG
,"Key with best swappability: %s, %f",
9184 key
->ptr
, best_swappability
);
9186 /* Unshare the key if needed */
9187 if (key
->refcount
> 1) {
9188 robj
*newkey
= dupStringObject(key
);
9190 key
= dictGetEntryKey(best
) = newkey
;
9194 vmSwapObjectThreaded(key
,val
,best_db
);
9197 if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
9198 dictGetEntryVal(best
) = NULL
;
9206 static int vmSwapOneObjectBlocking() {
9207 return vmSwapOneObject(0);
9210 static int vmSwapOneObjectThreaded() {
9211 return vmSwapOneObject(1);
9214 /* Return true if it's safe to swap out objects in a given moment.
9215 * Basically we don't want to swap objects out while there is a BGSAVE
9216 * or a BGAEOREWRITE running in backgroud. */
9217 static int vmCanSwapOut(void) {
9218 return (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1);
9221 /* Delete a key if swapped. Returns 1 if the key was found, was swapped
9222 * and was deleted. Otherwise 0 is returned. */
9223 static int deleteIfSwapped(redisDb
*db
, robj
*key
) {
9227 if ((de
= dictFind(db
->dict
,key
)) == NULL
) return 0;
9228 foundkey
= dictGetEntryKey(de
);
9229 if (foundkey
->storage
== REDIS_VM_MEMORY
) return 0;
9234 /* =================== Virtual Memory - Threaded I/O ======================= */
9236 static void freeIOJob(iojob
*j
) {
9237 if ((j
->type
== REDIS_IOJOB_PREPARE_SWAP
||
9238 j
->type
== REDIS_IOJOB_DO_SWAP
||
9239 j
->type
== REDIS_IOJOB_LOAD
) && j
->val
!= NULL
)
9240 decrRefCount(j
->val
);
9241 /* We don't decrRefCount the j->key field as we did't incremented
9242 * the count creating IO Jobs. This is because the key field here is
9243 * just used as an indentifier and if a key is removed the Job should
9244 * never be touched again. */
9248 /* Every time a thread finished a Job, it writes a byte into the write side
9249 * of an unix pipe in order to "awake" the main thread, and this function
9251 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
,
9255 int retval
, processed
= 0, toprocess
= -1, trytoswap
= 1;
9257 REDIS_NOTUSED(mask
);
9258 REDIS_NOTUSED(privdata
);
9260 /* For every byte we read in the read side of the pipe, there is one
9261 * I/O job completed to process. */
9262 while((retval
= read(fd
,buf
,1)) == 1) {
9266 struct dictEntry
*de
;
9268 redisLog(REDIS_DEBUG
,"Processing I/O completed job");
9270 /* Get the processed element (the oldest one) */
9272 assert(listLength(server
.io_processed
) != 0);
9273 if (toprocess
== -1) {
9274 toprocess
= (listLength(server
.io_processed
)*REDIS_MAX_COMPLETED_JOBS_PROCESSED
)/100;
9275 if (toprocess
<= 0) toprocess
= 1;
9277 ln
= listFirst(server
.io_processed
);
9279 listDelNode(server
.io_processed
,ln
);
9281 /* If this job is marked as canceled, just ignore it */
9286 /* Post process it in the main thread, as there are things we
9287 * can do just here to avoid race conditions and/or invasive locks */
9288 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
);
9289 de
= dictFind(j
->db
->dict
,j
->key
);
9291 key
= dictGetEntryKey(de
);
9292 if (j
->type
== REDIS_IOJOB_LOAD
) {
9295 /* Key loaded, bring it at home */
9296 key
->storage
= REDIS_VM_MEMORY
;
9297 key
->vm
.atime
= server
.unixtime
;
9298 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
9299 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk (threaded)",
9300 (unsigned char*) key
->ptr
);
9301 server
.vm_stats_swapped_objects
--;
9302 server
.vm_stats_swapins
++;
9303 dictGetEntryVal(de
) = j
->val
;
9304 incrRefCount(j
->val
);
9307 /* Handle clients waiting for this key to be loaded. */
9308 handleClientsBlockedOnSwappedKey(db
,key
);
9309 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
9310 /* Now we know the amount of pages required to swap this object.
9311 * Let's find some space for it, and queue this task again
9312 * rebranded as REDIS_IOJOB_DO_SWAP. */
9313 if (!vmCanSwapOut() ||
9314 vmFindContiguousPages(&j
->page
,j
->pages
) == REDIS_ERR
)
9316 /* Ooops... no space or we can't swap as there is
9317 * a fork()ed Redis trying to save stuff on disk. */
9319 key
->storage
= REDIS_VM_MEMORY
; /* undo operation */
9321 /* Note that we need to mark this pages as used now,
9322 * if the job will be canceled, we'll mark them as freed
9324 vmMarkPagesUsed(j
->page
,j
->pages
);
9325 j
->type
= REDIS_IOJOB_DO_SWAP
;
9330 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
9333 /* Key swapped. We can finally free some memory. */
9334 if (key
->storage
!= REDIS_VM_SWAPPING
) {
9335 printf("key->storage: %d\n",key
->storage
);
9336 printf("key->name: %s\n",(char*)key
->ptr
);
9337 printf("key->refcount: %d\n",key
->refcount
);
9338 printf("val: %p\n",(void*)j
->val
);
9339 printf("val->type: %d\n",j
->val
->type
);
9340 printf("val->ptr: %s\n",(char*)j
->val
->ptr
);
9342 redisAssert(key
->storage
== REDIS_VM_SWAPPING
);
9343 val
= dictGetEntryVal(de
);
9344 key
->vm
.page
= j
->page
;
9345 key
->vm
.usedpages
= j
->pages
;
9346 key
->storage
= REDIS_VM_SWAPPED
;
9347 key
->vtype
= j
->val
->type
;
9348 decrRefCount(val
); /* Deallocate the object from memory. */
9349 dictGetEntryVal(de
) = NULL
;
9350 redisLog(REDIS_DEBUG
,
9351 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
9352 (unsigned char*) key
->ptr
,
9353 (unsigned long long) j
->page
, (unsigned long long) j
->pages
);
9354 server
.vm_stats_swapped_objects
++;
9355 server
.vm_stats_swapouts
++;
9357 /* Put a few more swap requests in queue if we are still
9359 if (trytoswap
&& vmCanSwapOut() &&
9360 zmalloc_used_memory() > server
.vm_max_memory
)
9365 more
= listLength(server
.io_newjobs
) <
9366 (unsigned) server
.vm_max_threads
;
9368 /* Don't waste CPU time if swappable objects are rare. */
9369 if (vmSwapOneObjectThreaded() == REDIS_ERR
) {
9377 if (processed
== toprocess
) return;
9379 if (retval
< 0 && errno
!= EAGAIN
) {
9380 redisLog(REDIS_WARNING
,
9381 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
9386 static void lockThreadedIO(void) {
9387 pthread_mutex_lock(&server
.io_mutex
);
9390 static void unlockThreadedIO(void) {
9391 pthread_mutex_unlock(&server
.io_mutex
);
9394 /* Remove the specified object from the threaded I/O queue if still not
9395 * processed, otherwise make sure to flag it as canceled. */
9396 static void vmCancelThreadedIOJob(robj
*o
) {
9398 server
.io_newjobs
, /* 0 */
9399 server
.io_processing
, /* 1 */
9400 server
.io_processed
/* 2 */
9404 assert(o
->storage
== REDIS_VM_LOADING
|| o
->storage
== REDIS_VM_SWAPPING
);
9407 /* Search for a matching key in one of the queues */
9408 for (i
= 0; i
< 3; i
++) {
9412 listRewind(lists
[i
],&li
);
9413 while ((ln
= listNext(&li
)) != NULL
) {
9414 iojob
*job
= ln
->value
;
9416 if (job
->canceled
) continue; /* Skip this, already canceled. */
9417 if (job
->key
== o
) {
9418 redisLog(REDIS_DEBUG
,"*** CANCELED %p (%s) (type %d) (LIST ID %d)\n",
9419 (void*)job
, (char*)o
->ptr
, job
->type
, i
);
9420 /* Mark the pages as free since the swap didn't happened
9421 * or happened but is now discarded. */
9422 if (i
!= 1 && job
->type
== REDIS_IOJOB_DO_SWAP
)
9423 vmMarkPagesFree(job
->page
,job
->pages
);
9424 /* Cancel the job. It depends on the list the job is
9427 case 0: /* io_newjobs */
9428 /* If the job was yet not processed the best thing to do
9429 * is to remove it from the queue at all */
9431 listDelNode(lists
[i
],ln
);
9433 case 1: /* io_processing */
9434 /* Oh Shi- the thread is messing with the Job:
9436 * Probably it's accessing the object if this is a
9437 * PREPARE_SWAP or DO_SWAP job.
9438 * If it's a LOAD job it may be reading from disk and
9439 * if we don't wait for the job to terminate before to
9440 * cancel it, maybe in a few microseconds data can be
9441 * corrupted in this pages. So the short story is:
9443 * Better to wait for the job to move into the
9444 * next queue (processed)... */
9446 /* We try again and again until the job is completed. */
9448 /* But let's wait some time for the I/O thread
9449 * to finish with this job. After all this condition
9450 * should be very rare. */
9453 case 2: /* io_processed */
9454 /* The job was already processed, that's easy...
9455 * just mark it as canceled so that we'll ignore it
9456 * when processing completed jobs. */
9460 /* Finally we have to adjust the storage type of the object
9461 * in order to "UNDO" the operaiton. */
9462 if (o
->storage
== REDIS_VM_LOADING
)
9463 o
->storage
= REDIS_VM_SWAPPED
;
9464 else if (o
->storage
== REDIS_VM_SWAPPING
)
9465 o
->storage
= REDIS_VM_MEMORY
;
9472 assert(1 != 1); /* We should never reach this */
9475 static void *IOThreadEntryPoint(void *arg
) {
9480 pthread_detach(pthread_self());
9482 /* Get a new job to process */
9484 if (listLength(server
.io_newjobs
) == 0) {
9485 /* No new jobs in queue, exit. */
9486 redisLog(REDIS_DEBUG
,"Thread %ld exiting, nothing to do",
9487 (long) pthread_self());
9488 server
.io_active_threads
--;
9492 ln
= listFirst(server
.io_newjobs
);
9494 listDelNode(server
.io_newjobs
,ln
);
9495 /* Add the job in the processing queue */
9496 j
->thread
= pthread_self();
9497 listAddNodeTail(server
.io_processing
,j
);
9498 ln
= listLast(server
.io_processing
); /* We use ln later to remove it */
9500 redisLog(REDIS_DEBUG
,"Thread %ld got a new job (type %d): %p about key '%s'",
9501 (long) pthread_self(), j
->type
, (void*)j
, (char*)j
->key
->ptr
);
9503 /* Process the Job */
9504 if (j
->type
== REDIS_IOJOB_LOAD
) {
9505 j
->val
= vmReadObjectFromSwap(j
->page
,j
->key
->vtype
);
9506 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
9507 FILE *fp
= fopen("/dev/null","w+");
9508 j
->pages
= rdbSavedObjectPages(j
->val
,fp
);
9510 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
9511 if (vmWriteObjectOnSwap(j
->val
,j
->page
) == REDIS_ERR
)
9515 /* Done: insert the job into the processed queue */
9516 redisLog(REDIS_DEBUG
,"Thread %ld completed the job: %p (key %s)",
9517 (long) pthread_self(), (void*)j
, (char*)j
->key
->ptr
);
9519 listDelNode(server
.io_processing
,ln
);
9520 listAddNodeTail(server
.io_processed
,j
);
9523 /* Signal the main thread there is new stuff to process */
9524 assert(write(server
.io_ready_pipe_write
,"x",1) == 1);
9526 return NULL
; /* never reached */
9529 static void spawnIOThread(void) {
9531 sigset_t mask
, omask
;
9535 sigaddset(&mask
,SIGCHLD
);
9536 sigaddset(&mask
,SIGHUP
);
9537 sigaddset(&mask
,SIGPIPE
);
9538 pthread_sigmask(SIG_SETMASK
, &mask
, &omask
);
9539 while ((err
= pthread_create(&thread
,&server
.io_threads_attr
,IOThreadEntryPoint
,NULL
)) != 0) {
9540 redisLog(REDIS_WARNING
,"Unable to spawn an I/O thread: %s",
9544 pthread_sigmask(SIG_SETMASK
, &omask
, NULL
);
9545 server
.io_active_threads
++;
9548 /* We need to wait for the last thread to exit before we are able to
9549 * fork() in order to BGSAVE or BGREWRITEAOF. */
9550 static void waitEmptyIOJobsQueue(void) {
9552 int io_processed_len
;
9555 if (listLength(server
.io_newjobs
) == 0 &&
9556 listLength(server
.io_processing
) == 0 &&
9557 server
.io_active_threads
== 0)
9562 /* While waiting for empty jobs queue condition we post-process some
9563 * finshed job, as I/O threads may be hanging trying to write against
9564 * the io_ready_pipe_write FD but there are so much pending jobs that
9566 io_processed_len
= listLength(server
.io_processed
);
9568 if (io_processed_len
) {
9569 vmThreadedIOCompletedJob(NULL
,server
.io_ready_pipe_read
,NULL
,0);
9570 usleep(1000); /* 1 millisecond */
9572 usleep(10000); /* 10 milliseconds */
9577 static void vmReopenSwapFile(void) {
9578 /* Note: we don't close the old one as we are in the child process
9579 * and don't want to mess at all with the original file object. */
9580 server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b");
9581 if (server
.vm_fp
== NULL
) {
9582 redisLog(REDIS_WARNING
,"Can't re-open the VM swap file: %s. Exiting.",
9583 server
.vm_swap_file
);
9586 server
.vm_fd
= fileno(server
.vm_fp
);
9589 /* This function must be called while with threaded IO locked */
9590 static void queueIOJob(iojob
*j
) {
9591 redisLog(REDIS_DEBUG
,"Queued IO Job %p type %d about key '%s'\n",
9592 (void*)j
, j
->type
, (char*)j
->key
->ptr
);
9593 listAddNodeTail(server
.io_newjobs
,j
);
9594 if (server
.io_active_threads
< server
.vm_max_threads
)
9598 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
) {
9601 assert(key
->storage
== REDIS_VM_MEMORY
);
9602 assert(key
->refcount
== 1);
9604 j
= zmalloc(sizeof(*j
));
9605 j
->type
= REDIS_IOJOB_PREPARE_SWAP
;
9611 j
->thread
= (pthread_t
) -1;
9612 key
->storage
= REDIS_VM_SWAPPING
;
9620 /* ============ Virtual Memory - Blocking clients on missing keys =========== */
9622 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
9623 * If there is not already a job loading the key, it is craeted.
9624 * The key is added to the io_keys list in the client structure, and also
9625 * in the hash table mapping swapped keys to waiting clients, that is,
9626 * server.io_waited_keys. */
9627 static int waitForSwappedKey(redisClient
*c
, robj
*key
) {
9628 struct dictEntry
*de
;
9632 /* If the key does not exist or is already in RAM we don't need to
9633 * block the client at all. */
9634 de
= dictFind(c
->db
->dict
,key
);
9635 if (de
== NULL
) return 0;
9636 o
= dictGetEntryKey(de
);
9637 if (o
->storage
== REDIS_VM_MEMORY
) {
9639 } else if (o
->storage
== REDIS_VM_SWAPPING
) {
9640 /* We were swapping the key, undo it! */
9641 vmCancelThreadedIOJob(o
);
9645 /* OK: the key is either swapped, or being loaded just now. */
9647 /* Add the key to the list of keys this client is waiting for.
9648 * This maps clients to keys they are waiting for. */
9649 listAddNodeTail(c
->io_keys
,key
);
9652 /* Add the client to the swapped keys => clients waiting map. */
9653 de
= dictFind(c
->db
->io_keys
,key
);
9657 /* For every key we take a list of clients blocked for it */
9659 retval
= dictAdd(c
->db
->io_keys
,key
,l
);
9661 assert(retval
== DICT_OK
);
9663 l
= dictGetEntryVal(de
);
9665 listAddNodeTail(l
,c
);
9667 /* Are we already loading the key from disk? If not create a job */
9668 if (o
->storage
== REDIS_VM_SWAPPED
) {
9671 o
->storage
= REDIS_VM_LOADING
;
9672 j
= zmalloc(sizeof(*j
));
9673 j
->type
= REDIS_IOJOB_LOAD
;
9676 j
->key
->vtype
= o
->vtype
;
9677 j
->page
= o
->vm
.page
;
9680 j
->thread
= (pthread_t
) -1;
9688 /* Preload keys for any command with first, last and step values for
9689 * the command keys prototype, as defined in the command table. */
9690 static void waitForMultipleSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
9692 if (cmd
->vm_firstkey
== 0) return;
9693 last
= cmd
->vm_lastkey
;
9694 if (last
< 0) last
= argc
+last
;
9695 for (j
= cmd
->vm_firstkey
; j
<= last
; j
+= cmd
->vm_keystep
) {
9696 redisAssert(j
< argc
);
9697 waitForSwappedKey(c
,argv
[j
]);
9701 /* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
9702 * Note that the number of keys to preload is user-defined, so we need to
9703 * apply a sanity check against argc. */
9704 static void zunionInterBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
9708 num
= atoi(argv
[2]->ptr
);
9709 if (num
> (argc
-3)) return;
9710 for (i
= 0; i
< num
; i
++) {
9711 waitForSwappedKey(c
,argv
[3+i
]);
9715 /* Preload keys needed to execute the entire MULTI/EXEC block.
9717 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
9718 * and will block the client when any command requires a swapped out value. */
9719 static void execBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
9721 struct redisCommand
*mcmd
;
9724 REDIS_NOTUSED(argc
);
9725 REDIS_NOTUSED(argv
);
9727 if (!(c
->flags
& REDIS_MULTI
)) return;
9728 for (i
= 0; i
< c
->mstate
.count
; i
++) {
9729 mcmd
= c
->mstate
.commands
[i
].cmd
;
9730 margc
= c
->mstate
.commands
[i
].argc
;
9731 margv
= c
->mstate
.commands
[i
].argv
;
9733 if (mcmd
->vm_preload_proc
!= NULL
) {
9734 mcmd
->vm_preload_proc(c
,mcmd
,margc
,margv
);
9736 waitForMultipleSwappedKeys(c
,mcmd
,margc
,margv
);
9741 /* Is this client attempting to run a command against swapped keys?
9742 * If so, block it ASAP, load the keys in background, then resume it.
9744 * The important idea about this function is that it can fail! If keys will
9745 * still be swapped when the client is resumed, this key lookups will
9746 * just block loading keys from disk. In practical terms this should only
9747 * happen with SORT BY command or if there is a bug in this function.
9749 * Return 1 if the client is marked as blocked, 0 if the client can
9750 * continue as the keys it is going to access appear to be in memory. */
9751 static int blockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
) {
9752 if (cmd
->vm_preload_proc
!= NULL
) {
9753 cmd
->vm_preload_proc(c
,cmd
,c
->argc
,c
->argv
);
9755 waitForMultipleSwappedKeys(c
,cmd
,c
->argc
,c
->argv
);
9758 /* If the client was blocked for at least one key, mark it as blocked. */
9759 if (listLength(c
->io_keys
)) {
9760 c
->flags
|= REDIS_IO_WAIT
;
9761 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
9762 server
.vm_blocked_clients
++;
9769 /* Remove the 'key' from the list of blocked keys for a given client.
9771 * The function returns 1 when there are no longer blocking keys after
9772 * the current one was removed (and the client can be unblocked). */
9773 static int dontWaitForSwappedKey(redisClient
*c
, robj
*key
) {
9777 struct dictEntry
*de
;
9779 /* Remove the key from the list of keys this client is waiting for. */
9780 listRewind(c
->io_keys
,&li
);
9781 while ((ln
= listNext(&li
)) != NULL
) {
9782 if (equalStringObjects(ln
->value
,key
)) {
9783 listDelNode(c
->io_keys
,ln
);
9789 /* Remove the client form the key => waiting clients map. */
9790 de
= dictFind(c
->db
->io_keys
,key
);
9792 l
= dictGetEntryVal(de
);
9793 ln
= listSearchKey(l
,c
);
9796 if (listLength(l
) == 0)
9797 dictDelete(c
->db
->io_keys
,key
);
9799 return listLength(c
->io_keys
) == 0;
9802 static void handleClientsBlockedOnSwappedKey(redisDb
*db
, robj
*key
) {
9803 struct dictEntry
*de
;
9808 de
= dictFind(db
->io_keys
,key
);
9811 l
= dictGetEntryVal(de
);
9812 len
= listLength(l
);
9813 /* Note: we can't use something like while(listLength(l)) as the list
9814 * can be freed by the calling function when we remove the last element. */
9817 redisClient
*c
= ln
->value
;
9819 if (dontWaitForSwappedKey(c
,key
)) {
9820 /* Put the client in the list of clients ready to go as we
9821 * loaded all the keys about it. */
9822 listAddNodeTail(server
.io_ready_clients
,c
);
9827 /* =========================== Remote Configuration ========================= */
9829 static void configSetCommand(redisClient
*c
) {
9830 robj
*o
= getDecodedObject(c
->argv
[3]);
9831 if (!strcasecmp(c
->argv
[2]->ptr
,"dbfilename")) {
9832 zfree(server
.dbfilename
);
9833 server
.dbfilename
= zstrdup(o
->ptr
);
9834 } else if (!strcasecmp(c
->argv
[2]->ptr
,"requirepass")) {
9835 zfree(server
.requirepass
);
9836 server
.requirepass
= zstrdup(o
->ptr
);
9837 } else if (!strcasecmp(c
->argv
[2]->ptr
,"masterauth")) {
9838 zfree(server
.masterauth
);
9839 server
.masterauth
= zstrdup(o
->ptr
);
9840 } else if (!strcasecmp(c
->argv
[2]->ptr
,"maxmemory")) {
9841 server
.maxmemory
= strtoll(o
->ptr
, NULL
, 10);
9842 } else if (!strcasecmp(c
->argv
[2]->ptr
,"appendfsync")) {
9843 if (!strcasecmp(o
->ptr
,"no")) {
9844 server
.appendfsync
= APPENDFSYNC_NO
;
9845 } else if (!strcasecmp(o
->ptr
,"everysec")) {
9846 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
9847 } else if (!strcasecmp(o
->ptr
,"always")) {
9848 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
9852 } else if (!strcasecmp(c
->argv
[2]->ptr
,"save")) {
9854 sds
*v
= sdssplitlen(o
->ptr
,sdslen(o
->ptr
)," ",1,&vlen
);
9856 /* Perform sanity check before setting the new config:
9857 * - Even number of args
9858 * - Seconds >= 1, changes >= 0 */
9860 sdsfreesplitres(v
,vlen
);
9863 for (j
= 0; j
< vlen
; j
++) {
9867 val
= strtoll(v
[j
], &eptr
, 10);
9868 if (eptr
[0] != '\0' ||
9869 ((j
& 1) == 0 && val
< 1) ||
9870 ((j
& 1) == 1 && val
< 0)) {
9871 sdsfreesplitres(v
,vlen
);
9875 /* Finally set the new config */
9876 resetServerSaveParams();
9877 for (j
= 0; j
< vlen
; j
+= 2) {
9881 seconds
= strtoll(v
[j
],NULL
,10);
9882 changes
= strtoll(v
[j
+1],NULL
,10);
9883 appendServerSaveParams(seconds
, changes
);
9885 sdsfreesplitres(v
,vlen
);
9887 addReplySds(c
,sdscatprintf(sdsempty(),
9888 "-ERR not supported CONFIG parameter %s\r\n",
9889 (char*)c
->argv
[2]->ptr
));
9894 addReply(c
,shared
.ok
);
9897 badfmt
: /* Bad format errors */
9898 addReplySds(c
,sdscatprintf(sdsempty(),
9899 "-ERR invalid argument '%s' for CONFIG SET '%s'\r\n",
9901 (char*)c
->argv
[2]->ptr
));
9905 static void configGetCommand(redisClient
*c
) {
9906 robj
*o
= getDecodedObject(c
->argv
[2]);
9907 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
9908 char *pattern
= o
->ptr
;
9912 decrRefCount(lenobj
);
9914 if (stringmatch(pattern
,"dbfilename",0)) {
9915 addReplyBulkCString(c
,"dbfilename");
9916 addReplyBulkCString(c
,server
.dbfilename
);
9919 if (stringmatch(pattern
,"requirepass",0)) {
9920 addReplyBulkCString(c
,"requirepass");
9921 addReplyBulkCString(c
,server
.requirepass
);
9924 if (stringmatch(pattern
,"masterauth",0)) {
9925 addReplyBulkCString(c
,"masterauth");
9926 addReplyBulkCString(c
,server
.masterauth
);
9929 if (stringmatch(pattern
,"maxmemory",0)) {
9932 snprintf(buf
,128,"%llu\n",server
.maxmemory
);
9933 addReplyBulkCString(c
,"maxmemory");
9934 addReplyBulkCString(c
,buf
);
9937 if (stringmatch(pattern
,"appendfsync",0)) {
9940 switch(server
.appendfsync
) {
9941 case APPENDFSYNC_NO
: policy
= "no"; break;
9942 case APPENDFSYNC_EVERYSEC
: policy
= "everysec"; break;
9943 case APPENDFSYNC_ALWAYS
: policy
= "always"; break;
9944 default: policy
= "unknown"; break; /* too harmless to panic */
9946 addReplyBulkCString(c
,"appendfsync");
9947 addReplyBulkCString(c
,policy
);
9950 if (stringmatch(pattern
,"save",0)) {
9951 sds buf
= sdsempty();
9954 for (j
= 0; j
< server
.saveparamslen
; j
++) {
9955 buf
= sdscatprintf(buf
,"%ld %d",
9956 server
.saveparams
[j
].seconds
,
9957 server
.saveparams
[j
].changes
);
9958 if (j
!= server
.saveparamslen
-1)
9959 buf
= sdscatlen(buf
," ",1);
9961 addReplyBulkCString(c
,"save");
9962 addReplyBulkCString(c
,buf
);
9967 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%d\r\n",matches
*2);
9970 static void configCommand(redisClient
*c
) {
9971 if (!strcasecmp(c
->argv
[1]->ptr
,"set")) {
9972 if (c
->argc
!= 4) goto badarity
;
9973 configSetCommand(c
);
9974 } else if (!strcasecmp(c
->argv
[1]->ptr
,"get")) {
9975 if (c
->argc
!= 3) goto badarity
;
9976 configGetCommand(c
);
9977 } else if (!strcasecmp(c
->argv
[1]->ptr
,"resetstat")) {
9978 if (c
->argc
!= 2) goto badarity
;
9979 server
.stat_numcommands
= 0;
9980 server
.stat_numconnections
= 0;
9981 server
.stat_expiredkeys
= 0;
9982 server
.stat_starttime
= time(NULL
);
9983 addReply(c
,shared
.ok
);
9985 addReplySds(c
,sdscatprintf(sdsempty(),
9986 "-ERR CONFIG subcommand must be one of GET, SET, RESETSTAT\r\n"));
9991 addReplySds(c
,sdscatprintf(sdsempty(),
9992 "-ERR Wrong number of arguments for CONFIG %s\r\n",
9993 (char*) c
->argv
[1]->ptr
));
9996 /* =========================== Pubsub implementation ======================== */
9998 static void freePubsubPattern(void *p
) {
9999 pubsubPattern
*pat
= p
;
10001 decrRefCount(pat
->pattern
);
10005 static int listMatchPubsubPattern(void *a
, void *b
) {
10006 pubsubPattern
*pa
= a
, *pb
= b
;
10008 return (pa
->client
== pb
->client
) &&
10009 (equalStringObjects(pa
->pattern
,pb
->pattern
));
10012 /* Subscribe a client to a channel. Returns 1 if the operation succeeded, or
10013 * 0 if the client was already subscribed to that channel. */
10014 static int pubsubSubscribeChannel(redisClient
*c
, robj
*channel
) {
10015 struct dictEntry
*de
;
10016 list
*clients
= NULL
;
10019 /* Add the channel to the client -> channels hash table */
10020 if (dictAdd(c
->pubsub_channels
,channel
,NULL
) == DICT_OK
) {
10022 incrRefCount(channel
);
10023 /* Add the client to the channel -> list of clients hash table */
10024 de
= dictFind(server
.pubsub_channels
,channel
);
10026 clients
= listCreate();
10027 dictAdd(server
.pubsub_channels
,channel
,clients
);
10028 incrRefCount(channel
);
10030 clients
= dictGetEntryVal(de
);
10032 listAddNodeTail(clients
,c
);
10034 /* Notify the client */
10035 addReply(c
,shared
.mbulk3
);
10036 addReply(c
,shared
.subscribebulk
);
10037 addReplyBulk(c
,channel
);
10038 addReplyLong(c
,dictSize(c
->pubsub_channels
)+listLength(c
->pubsub_patterns
));
10042 /* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10043 * 0 if the client was not subscribed to the specified channel. */
10044 static int pubsubUnsubscribeChannel(redisClient
*c
, robj
*channel
, int notify
) {
10045 struct dictEntry
*de
;
10050 /* Remove the channel from the client -> channels hash table */
10051 incrRefCount(channel
); /* channel may be just a pointer to the same object
10052 we have in the hash tables. Protect it... */
10053 if (dictDelete(c
->pubsub_channels
,channel
) == DICT_OK
) {
10055 /* Remove the client from the channel -> clients list hash table */
10056 de
= dictFind(server
.pubsub_channels
,channel
);
10057 assert(de
!= NULL
);
10058 clients
= dictGetEntryVal(de
);
10059 ln
= listSearchKey(clients
,c
);
10060 assert(ln
!= NULL
);
10061 listDelNode(clients
,ln
);
10062 if (listLength(clients
) == 0) {
10063 /* Free the list and associated hash entry at all if this was
10064 * the latest client, so that it will be possible to abuse
10065 * Redis PUBSUB creating millions of channels. */
10066 dictDelete(server
.pubsub_channels
,channel
);
10069 /* Notify the client */
10071 addReply(c
,shared
.mbulk3
);
10072 addReply(c
,shared
.unsubscribebulk
);
10073 addReplyBulk(c
,channel
);
10074 addReplyLong(c
,dictSize(c
->pubsub_channels
)+
10075 listLength(c
->pubsub_patterns
));
10078 decrRefCount(channel
); /* it is finally safe to release it */
10082 /* Subscribe a client to a pattern. Returns 1 if the operation succeeded, or 0 if the clinet was already subscribed to that pattern. */
10083 static int pubsubSubscribePattern(redisClient
*c
, robj
*pattern
) {
10086 if (listSearchKey(c
->pubsub_patterns
,pattern
) == NULL
) {
10088 pubsubPattern
*pat
;
10089 listAddNodeTail(c
->pubsub_patterns
,pattern
);
10090 incrRefCount(pattern
);
10091 pat
= zmalloc(sizeof(*pat
));
10092 pat
->pattern
= getDecodedObject(pattern
);
10094 listAddNodeTail(server
.pubsub_patterns
,pat
);
10096 /* Notify the client */
10097 addReply(c
,shared
.mbulk3
);
10098 addReply(c
,shared
.psubscribebulk
);
10099 addReplyBulk(c
,pattern
);
10100 addReplyLong(c
,dictSize(c
->pubsub_channels
)+listLength(c
->pubsub_patterns
));
10104 /* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10105 * 0 if the client was not subscribed to the specified channel. */
10106 static int pubsubUnsubscribePattern(redisClient
*c
, robj
*pattern
, int notify
) {
10111 incrRefCount(pattern
); /* Protect the object. May be the same we remove */
10112 if ((ln
= listSearchKey(c
->pubsub_patterns
,pattern
)) != NULL
) {
10114 listDelNode(c
->pubsub_patterns
,ln
);
10116 pat
.pattern
= pattern
;
10117 ln
= listSearchKey(server
.pubsub_patterns
,&pat
);
10118 listDelNode(server
.pubsub_patterns
,ln
);
10120 /* Notify the client */
10122 addReply(c
,shared
.mbulk3
);
10123 addReply(c
,shared
.punsubscribebulk
);
10124 addReplyBulk(c
,pattern
);
10125 addReplyLong(c
,dictSize(c
->pubsub_channels
)+
10126 listLength(c
->pubsub_patterns
));
10128 decrRefCount(pattern
);
10132 /* Unsubscribe from all the channels. Return the number of channels the
10133 * client was subscribed from. */
10134 static int pubsubUnsubscribeAllChannels(redisClient
*c
, int notify
) {
10135 dictIterator
*di
= dictGetIterator(c
->pubsub_channels
);
10139 while((de
= dictNext(di
)) != NULL
) {
10140 robj
*channel
= dictGetEntryKey(de
);
10142 count
+= pubsubUnsubscribeChannel(c
,channel
,notify
);
10144 dictReleaseIterator(di
);
10148 /* Unsubscribe from all the patterns. Return the number of patterns the
10149 * client was subscribed from. */
10150 static int pubsubUnsubscribeAllPatterns(redisClient
*c
, int notify
) {
10155 listRewind(c
->pubsub_patterns
,&li
);
10156 while ((ln
= listNext(&li
)) != NULL
) {
10157 robj
*pattern
= ln
->value
;
10159 count
+= pubsubUnsubscribePattern(c
,pattern
,notify
);
10164 /* Publish a message */
10165 static int pubsubPublishMessage(robj
*channel
, robj
*message
) {
10167 struct dictEntry
*de
;
10171 /* Send to clients listening for that channel */
10172 de
= dictFind(server
.pubsub_channels
,channel
);
10174 list
*list
= dictGetEntryVal(de
);
10178 listRewind(list
,&li
);
10179 while ((ln
= listNext(&li
)) != NULL
) {
10180 redisClient
*c
= ln
->value
;
10182 addReply(c
,shared
.mbulk3
);
10183 addReply(c
,shared
.messagebulk
);
10184 addReplyBulk(c
,channel
);
10185 addReplyBulk(c
,message
);
10189 /* Send to clients listening to matching channels */
10190 if (listLength(server
.pubsub_patterns
)) {
10191 listRewind(server
.pubsub_patterns
,&li
);
10192 channel
= getDecodedObject(channel
);
10193 while ((ln
= listNext(&li
)) != NULL
) {
10194 pubsubPattern
*pat
= ln
->value
;
10196 if (stringmatchlen((char*)pat
->pattern
->ptr
,
10197 sdslen(pat
->pattern
->ptr
),
10198 (char*)channel
->ptr
,
10199 sdslen(channel
->ptr
),0)) {
10200 addReply(pat
->client
,shared
.mbulk4
);
10201 addReply(pat
->client
,shared
.pmessagebulk
);
10202 addReplyBulk(pat
->client
,pat
->pattern
);
10203 addReplyBulk(pat
->client
,channel
);
10204 addReplyBulk(pat
->client
,message
);
10208 decrRefCount(channel
);
10213 static void subscribeCommand(redisClient
*c
) {
10216 for (j
= 1; j
< c
->argc
; j
++)
10217 pubsubSubscribeChannel(c
,c
->argv
[j
]);
10220 static void unsubscribeCommand(redisClient
*c
) {
10221 if (c
->argc
== 1) {
10222 pubsubUnsubscribeAllChannels(c
,1);
10227 for (j
= 1; j
< c
->argc
; j
++)
10228 pubsubUnsubscribeChannel(c
,c
->argv
[j
],1);
10232 static void psubscribeCommand(redisClient
*c
) {
10235 for (j
= 1; j
< c
->argc
; j
++)
10236 pubsubSubscribePattern(c
,c
->argv
[j
]);
10239 static void punsubscribeCommand(redisClient
*c
) {
10240 if (c
->argc
== 1) {
10241 pubsubUnsubscribeAllPatterns(c
,1);
10246 for (j
= 1; j
< c
->argc
; j
++)
10247 pubsubUnsubscribePattern(c
,c
->argv
[j
],1);
10251 static void publishCommand(redisClient
*c
) {
10252 int receivers
= pubsubPublishMessage(c
->argv
[1],c
->argv
[2]);
10253 addReplyLong(c
,receivers
);
10256 /* ================================= Debugging ============================== */
10258 /* Compute the sha1 of string at 's' with 'len' bytes long.
10259 * The SHA1 is then xored againt the string pointed by digest.
10260 * Since xor is commutative, this operation is used in order to
10261 * "add" digests relative to unordered elements.
10263 * So digest(a,b,c,d) will be the same of digest(b,a,c,d) */
10264 static void xorDigest(unsigned char *digest
, void *ptr
, size_t len
) {
10266 unsigned char hash
[20], *s
= ptr
;
10270 SHA1Update(&ctx
,s
,len
);
10271 SHA1Final(hash
,&ctx
);
10273 for (j
= 0; j
< 20; j
++)
10274 digest
[j
] ^= hash
[j
];
10277 static void xorObjectDigest(unsigned char *digest
, robj
*o
) {
10278 o
= getDecodedObject(o
);
10279 xorDigest(digest
,o
->ptr
,sdslen(o
->ptr
));
10283 /* This function instead of just computing the SHA1 and xoring it
10284 * against diget, also perform the digest of "digest" itself and
10285 * replace the old value with the new one.
10287 * So the final digest will be:
10289 * digest = SHA1(digest xor SHA1(data))
10291 * This function is used every time we want to preserve the order so
10292 * that digest(a,b,c,d) will be different than digest(b,c,d,a)
10294 * Also note that mixdigest("foo") followed by mixdigest("bar")
10295 * will lead to a different digest compared to "fo", "obar".
10297 static void mixDigest(unsigned char *digest
, void *ptr
, size_t len
) {
10301 xorDigest(digest
,s
,len
);
10303 SHA1Update(&ctx
,digest
,20);
10304 SHA1Final(digest
,&ctx
);
10307 static void mixObjectDigest(unsigned char *digest
, robj
*o
) {
10308 o
= getDecodedObject(o
);
10309 mixDigest(digest
,o
->ptr
,sdslen(o
->ptr
));
10313 /* Compute the dataset digest. Since keys, sets elements, hashes elements
10314 * are not ordered, we use a trick: every aggregate digest is the xor
10315 * of the digests of their elements. This way the order will not change
10316 * the result. For list instead we use a feedback entering the output digest
10317 * as input in order to ensure that a different ordered list will result in
10318 * a different digest. */
10319 static void computeDatasetDigest(unsigned char *final
) {
10320 unsigned char digest
[20];
10322 dictIterator
*di
= NULL
;
10327 memset(final
,0,20); /* Start with a clean result */
10329 for (j
= 0; j
< server
.dbnum
; j
++) {
10330 redisDb
*db
= server
.db
+j
;
10332 if (dictSize(db
->dict
) == 0) continue;
10333 di
= dictGetIterator(db
->dict
);
10335 /* hash the DB id, so the same dataset moved in a different
10336 * DB will lead to a different digest */
10338 mixDigest(final
,&aux
,sizeof(aux
));
10340 /* Iterate this DB writing every entry */
10341 while((de
= dictNext(di
)) != NULL
) {
10345 memset(digest
,0,20); /* This key-val digest */
10346 key
= dictGetEntryKey(de
);
10347 mixObjectDigest(digest
,key
);
10348 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
10349 key
->storage
== REDIS_VM_SWAPPING
) {
10350 o
= dictGetEntryVal(de
);
10353 o
= vmPreviewObject(key
);
10355 aux
= htonl(o
->type
);
10356 mixDigest(digest
,&aux
,sizeof(aux
));
10357 expiretime
= getExpire(db
,key
);
10359 /* Save the key and associated value */
10360 if (o
->type
== REDIS_STRING
) {
10361 mixObjectDigest(digest
,o
);
10362 } else if (o
->type
== REDIS_LIST
) {
10363 list
*list
= o
->ptr
;
10367 listRewind(list
,&li
);
10368 while((ln
= listNext(&li
))) {
10369 robj
*eleobj
= listNodeValue(ln
);
10371 mixObjectDigest(digest
,eleobj
);
10373 } else if (o
->type
== REDIS_SET
) {
10374 dict
*set
= o
->ptr
;
10375 dictIterator
*di
= dictGetIterator(set
);
10378 while((de
= dictNext(di
)) != NULL
) {
10379 robj
*eleobj
= dictGetEntryKey(de
);
10381 xorObjectDigest(digest
,eleobj
);
10383 dictReleaseIterator(di
);
10384 } else if (o
->type
== REDIS_ZSET
) {
10386 dictIterator
*di
= dictGetIterator(zs
->dict
);
10389 while((de
= dictNext(di
)) != NULL
) {
10390 robj
*eleobj
= dictGetEntryKey(de
);
10391 double *score
= dictGetEntryVal(de
);
10392 unsigned char eledigest
[20];
10394 snprintf(buf
,sizeof(buf
),"%.17g",*score
);
10395 memset(eledigest
,0,20);
10396 mixObjectDigest(eledigest
,eleobj
);
10397 mixDigest(eledigest
,buf
,strlen(buf
));
10398 xorDigest(digest
,eledigest
,20);
10400 dictReleaseIterator(di
);
10401 } else if (o
->type
== REDIS_HASH
) {
10405 hi
= hashInitIterator(o
);
10406 while (hashNext(hi
) != REDIS_ERR
) {
10407 unsigned char eledigest
[20];
10409 memset(eledigest
,0,20);
10410 obj
= hashCurrent(hi
,REDIS_HASH_KEY
);
10411 mixObjectDigest(eledigest
,obj
);
10413 obj
= hashCurrent(hi
,REDIS_HASH_VALUE
);
10414 mixObjectDigest(eledigest
,obj
);
10416 xorDigest(digest
,eledigest
,20);
10418 hashReleaseIterator(hi
);
10420 redisPanic("Unknown object type");
10423 /* If the key has an expire, add it to the mix */
10424 if (expiretime
!= -1) xorDigest(digest
,"!!expire!!",10);
10425 /* We can finally xor the key-val digest to the final digest */
10426 xorDigest(final
,digest
,20);
10428 dictReleaseIterator(di
);
10432 static void debugCommand(redisClient
*c
) {
10433 if (!strcasecmp(c
->argv
[1]->ptr
,"segfault")) {
10434 *((char*)-1) = 'x';
10435 } else if (!strcasecmp(c
->argv
[1]->ptr
,"reload")) {
10436 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
10437 addReply(c
,shared
.err
);
10441 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
10442 addReply(c
,shared
.err
);
10445 redisLog(REDIS_WARNING
,"DB reloaded by DEBUG RELOAD");
10446 addReply(c
,shared
.ok
);
10447 } else if (!strcasecmp(c
->argv
[1]->ptr
,"loadaof")) {
10449 if (loadAppendOnlyFile(server
.appendfilename
) != REDIS_OK
) {
10450 addReply(c
,shared
.err
);
10453 redisLog(REDIS_WARNING
,"Append Only File loaded by DEBUG LOADAOF");
10454 addReply(c
,shared
.ok
);
10455 } else if (!strcasecmp(c
->argv
[1]->ptr
,"object") && c
->argc
== 3) {
10456 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
10460 addReply(c
,shared
.nokeyerr
);
10463 key
= dictGetEntryKey(de
);
10464 val
= dictGetEntryVal(de
);
10465 if (!server
.vm_enabled
|| (key
->storage
== REDIS_VM_MEMORY
||
10466 key
->storage
== REDIS_VM_SWAPPING
)) {
10470 if (val
->encoding
< (sizeof(strencoding
)/sizeof(char*))) {
10471 strenc
= strencoding
[val
->encoding
];
10473 snprintf(buf
,64,"unknown encoding %d\n", val
->encoding
);
10476 addReplySds(c
,sdscatprintf(sdsempty(),
10477 "+Key at:%p refcount:%d, value at:%p refcount:%d "
10478 "encoding:%s serializedlength:%lld\r\n",
10479 (void*)key
, key
->refcount
, (void*)val
, val
->refcount
,
10480 strenc
, (long long) rdbSavedObjectLen(val
,NULL
)));
10482 addReplySds(c
,sdscatprintf(sdsempty(),
10483 "+Key at:%p refcount:%d, value swapped at: page %llu "
10484 "using %llu pages\r\n",
10485 (void*)key
, key
->refcount
, (unsigned long long) key
->vm
.page
,
10486 (unsigned long long) key
->vm
.usedpages
));
10488 } else if (!strcasecmp(c
->argv
[1]->ptr
,"swapin") && c
->argc
== 3) {
10489 lookupKeyRead(c
->db
,c
->argv
[2]);
10490 addReply(c
,shared
.ok
);
10491 } else if (!strcasecmp(c
->argv
[1]->ptr
,"swapout") && c
->argc
== 3) {
10492 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
10495 if (!server
.vm_enabled
) {
10496 addReplySds(c
,sdsnew("-ERR Virtual Memory is disabled\r\n"));
10500 addReply(c
,shared
.nokeyerr
);
10503 key
= dictGetEntryKey(de
);
10504 val
= dictGetEntryVal(de
);
10505 /* If the key is shared we want to create a copy */
10506 if (key
->refcount
> 1) {
10507 robj
*newkey
= dupStringObject(key
);
10509 key
= dictGetEntryKey(de
) = newkey
;
10512 if (key
->storage
!= REDIS_VM_MEMORY
) {
10513 addReplySds(c
,sdsnew("-ERR This key is not in memory\r\n"));
10514 } else if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
10515 dictGetEntryVal(de
) = NULL
;
10516 addReply(c
,shared
.ok
);
10518 addReply(c
,shared
.err
);
10520 } else if (!strcasecmp(c
->argv
[1]->ptr
,"populate") && c
->argc
== 3) {
10525 if (getLongFromObjectOrReply(c
, c
->argv
[2], &keys
, NULL
) != REDIS_OK
)
10527 for (j
= 0; j
< keys
; j
++) {
10528 snprintf(buf
,sizeof(buf
),"key:%lu",j
);
10529 key
= createStringObject(buf
,strlen(buf
));
10530 if (lookupKeyRead(c
->db
,key
) != NULL
) {
10534 snprintf(buf
,sizeof(buf
),"value:%lu",j
);
10535 val
= createStringObject(buf
,strlen(buf
));
10536 dictAdd(c
->db
->dict
,key
,val
);
10538 addReply(c
,shared
.ok
);
10539 } else if (!strcasecmp(c
->argv
[1]->ptr
,"digest") && c
->argc
== 2) {
10540 unsigned char digest
[20];
10541 sds d
= sdsnew("+");
10544 computeDatasetDigest(digest
);
10545 for (j
= 0; j
< 20; j
++)
10546 d
= sdscatprintf(d
, "%02x",digest
[j
]);
10548 d
= sdscatlen(d
,"\r\n",2);
10551 addReplySds(c
,sdsnew(
10552 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPIN <key>|SWAPOUT <key>|RELOAD]\r\n"));
10556 static void _redisAssert(char *estr
, char *file
, int line
) {
10557 redisLog(REDIS_WARNING
,"=== ASSERTION FAILED ===");
10558 redisLog(REDIS_WARNING
,"==> %s:%d '%s' is not true\n",file
,line
,estr
);
10559 #ifdef HAVE_BACKTRACE
10560 redisLog(REDIS_WARNING
,"(forcing SIGSEGV in order to print the stack trace)");
10561 *((char*)-1) = 'x';
10565 static void _redisPanic(char *msg
, char *file
, int line
) {
10566 redisLog(REDIS_WARNING
,"!!! Software Failure. Press left mouse button to continue");
10567 redisLog(REDIS_WARNING
,"Guru Meditation: %s #%s:%d",msg
,file
,line
);
10568 #ifdef HAVE_BACKTRACE
10569 redisLog(REDIS_WARNING
,"(forcing SIGSEGV in order to print the stack trace)");
10570 *((char*)-1) = 'x';
10574 /* =================================== Main! ================================ */
10577 int linuxOvercommitMemoryValue(void) {
10578 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
10581 if (!fp
) return -1;
10582 if (fgets(buf
,64,fp
) == NULL
) {
10591 void linuxOvercommitMemoryWarning(void) {
10592 if (linuxOvercommitMemoryValue() == 0) {
10593 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.");
10596 #endif /* __linux__ */
10598 static void daemonize(void) {
10602 if (fork() != 0) exit(0); /* parent exits */
10603 setsid(); /* create a new session */
10605 /* Every output goes to /dev/null. If Redis is daemonized but
10606 * the 'logfile' is set to 'stdout' in the configuration file
10607 * it will not log at all. */
10608 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
10609 dup2(fd
, STDIN_FILENO
);
10610 dup2(fd
, STDOUT_FILENO
);
10611 dup2(fd
, STDERR_FILENO
);
10612 if (fd
> STDERR_FILENO
) close(fd
);
10614 /* Try to write the pid file */
10615 fp
= fopen(server
.pidfile
,"w");
10617 fprintf(fp
,"%d\n",getpid());
10622 static void version() {
10623 printf("Redis server version %s\n", REDIS_VERSION
);
10627 static void usage() {
10628 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
10629 fprintf(stderr
," ./redis-server - (read config from stdin)\n");
10633 int main(int argc
, char **argv
) {
10636 initServerConfig();
10638 if (strcmp(argv
[1], "-v") == 0 ||
10639 strcmp(argv
[1], "--version") == 0) version();
10640 if (strcmp(argv
[1], "--help") == 0) usage();
10641 resetServerSaveParams();
10642 loadServerConfig(argv
[1]);
10643 } else if ((argc
> 2)) {
10646 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'");
10648 if (server
.daemonize
) daemonize();
10650 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
10652 linuxOvercommitMemoryWarning();
10654 start
= time(NULL
);
10655 if (server
.appendonly
) {
10656 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
10657 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %ld seconds",time(NULL
)-start
);
10659 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
10660 redisLog(REDIS_NOTICE
,"DB loaded from disk: %ld seconds",time(NULL
)-start
);
10662 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
10663 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
10665 aeDeleteEventLoop(server
.el
);
10669 /* ============================= Backtrace support ========================= */
10671 #ifdef HAVE_BACKTRACE
10672 static char *findFuncName(void *pointer
, unsigned long *offset
);
10674 static void *getMcontextEip(ucontext_t
*uc
) {
10675 #if defined(__FreeBSD__)
10676 return (void*) uc
->uc_mcontext
.mc_eip
;
10677 #elif defined(__dietlibc__)
10678 return (void*) uc
->uc_mcontext
.eip
;
10679 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
10681 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
10683 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
10685 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
10686 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
10687 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
10689 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
10691 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
10692 return (void*) uc
->uc_mcontext
.gregs
[REG_EIP
]; /* Linux 32/64 bit */
10693 #elif defined(__ia64__) /* Linux IA64 */
10694 return (void*) uc
->uc_mcontext
.sc_ip
;
10700 static void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
10702 char **messages
= NULL
;
10703 int i
, trace_size
= 0;
10704 unsigned long offset
=0;
10705 ucontext_t
*uc
= (ucontext_t
*) secret
;
10707 REDIS_NOTUSED(info
);
10709 redisLog(REDIS_WARNING
,
10710 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
10711 infostring
= genRedisInfoString();
10712 redisLog(REDIS_WARNING
, "%s",infostring
);
10713 /* It's not safe to sdsfree() the returned string under memory
10714 * corruption conditions. Let it leak as we are going to abort */
10716 trace_size
= backtrace(trace
, 100);
10717 /* overwrite sigaction with caller's address */
10718 if (getMcontextEip(uc
) != NULL
) {
10719 trace
[1] = getMcontextEip(uc
);
10721 messages
= backtrace_symbols(trace
, trace_size
);
10723 for (i
=1; i
<trace_size
; ++i
) {
10724 char *fn
= findFuncName(trace
[i
], &offset
), *p
;
10726 p
= strchr(messages
[i
],'+');
10727 if (!fn
|| (p
&& ((unsigned long)strtol(p
+1,NULL
,10)) < offset
)) {
10728 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
10730 redisLog(REDIS_WARNING
,"%d redis-server %p %s + %d", i
, trace
[i
], fn
, (unsigned int)offset
);
10733 /* free(messages); Don't call free() with possibly corrupted memory. */
10737 static void setupSigSegvAction(void) {
10738 struct sigaction act
;
10740 sigemptyset (&act
.sa_mask
);
10741 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
10742 * is used. Otherwise, sa_handler is used */
10743 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
10744 act
.sa_sigaction
= segvHandler
;
10745 sigaction (SIGSEGV
, &act
, NULL
);
10746 sigaction (SIGBUS
, &act
, NULL
);
10747 sigaction (SIGFPE
, &act
, NULL
);
10748 sigaction (SIGILL
, &act
, NULL
);
10749 sigaction (SIGBUS
, &act
, NULL
);
10753 #include "staticsymbols.h"
10754 /* This function try to convert a pointer into a function name. It's used in
10755 * oreder to provide a backtrace under segmentation fault that's able to
10756 * display functions declared as static (otherwise the backtrace is useless). */
10757 static char *findFuncName(void *pointer
, unsigned long *offset
){
10759 unsigned long off
, minoff
= 0;
10761 /* Try to match against the Symbol with the smallest offset */
10762 for (i
=0; symsTable
[i
].pointer
; i
++) {
10763 unsigned long lp
= (unsigned long) pointer
;
10765 if (lp
!= (unsigned long)-1 && lp
>= symsTable
[i
].pointer
) {
10766 off
=lp
-symsTable
[i
].pointer
;
10767 if (ret
< 0 || off
< minoff
) {
10773 if (ret
== -1) return NULL
;
10775 return symsTable
[ret
].name
;
10777 #else /* HAVE_BACKTRACE */
10778 static void setupSigSegvAction(void) {
10780 #endif /* HAVE_BACKTRACE */