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.12"
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 */
79 #include "release.h" /* Release and/or git repository information */
85 /* Static server configuration */
86 #define REDIS_SERVERPORT 6379 /* TCP port */
87 #define REDIS_MAXIDLETIME (60*5) /* default client timeout */
88 #define REDIS_IOBUF_LEN 1024
89 #define REDIS_LOADBUF_LEN 1024
90 #define REDIS_STATIC_ARGS 8
91 #define REDIS_DEFAULT_DBNUM 16
92 #define REDIS_CONFIGLINE_MAX 1024
93 #define REDIS_OBJFREELIST_MAX 1000000 /* Max number of objects to cache */
94 #define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
95 #define REDIS_EXPIRELOOKUPS_PER_CRON 10 /* lookup 10 expires per loop */
96 #define REDIS_MAX_WRITE_PER_EVENT (1024*64)
97 #define REDIS_REQUEST_MAX_SIZE (1024*1024*256) /* max bytes in inline command */
99 /* If more then REDIS_WRITEV_THRESHOLD write packets are pending use writev */
100 #define REDIS_WRITEV_THRESHOLD 3
101 /* Max number of iovecs used for each writev call */
102 #define REDIS_WRITEV_IOVEC_COUNT 256
104 /* Hash table parameters */
105 #define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
108 #define REDIS_CMD_BULK 1 /* Bulk write command */
109 #define REDIS_CMD_INLINE 2 /* Inline command */
110 /* REDIS_CMD_DENYOOM reserves a longer comment: all the commands marked with
111 this flags will return an error when the 'maxmemory' option is set in the
112 config file and the server is using more than maxmemory bytes of memory.
113 In short this commands are denied on low memory conditions. */
114 #define REDIS_CMD_DENYOOM 4
115 #define REDIS_CMD_FORCE_REPLICATION 8 /* Force replication even if dirty is 0 */
118 #define REDIS_STRING 0
124 /* Objects encoding. Some kind of objects like Strings and Hashes can be
125 * internally represented in multiple ways. The 'encoding' field of the object
126 * is set to one of this fields for this object. */
127 #define REDIS_ENCODING_RAW 0 /* Raw representation */
128 #define REDIS_ENCODING_INT 1 /* Encoded as integer */
129 #define REDIS_ENCODING_ZIPMAP 2 /* Encoded as zipmap */
130 #define REDIS_ENCODING_HT 3 /* Encoded as an hash table */
132 static char* strencoding
[] = {
133 "raw", "int", "zipmap", "hashtable"
136 /* Object types only used for dumping to disk */
137 #define REDIS_EXPIRETIME 253
138 #define REDIS_SELECTDB 254
139 #define REDIS_EOF 255
141 /* Defines related to the dump file format. To store 32 bits lengths for short
142 * keys requires a lot of space, so we check the most significant 2 bits of
143 * the first byte to interpreter the length:
145 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
146 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
147 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
148 * 11|000000 this means: specially encoded object will follow. The six bits
149 * number specify the kind of object that follows.
150 * See the REDIS_RDB_ENC_* defines.
152 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
153 * values, will fit inside. */
154 #define REDIS_RDB_6BITLEN 0
155 #define REDIS_RDB_14BITLEN 1
156 #define REDIS_RDB_32BITLEN 2
157 #define REDIS_RDB_ENCVAL 3
158 #define REDIS_RDB_LENERR UINT_MAX
160 /* When a length of a string object stored on disk has the first two bits
161 * set, the remaining two bits specify a special encoding for the object
162 * accordingly to the following defines: */
163 #define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
164 #define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
165 #define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
166 #define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
168 /* Virtual memory object->where field. */
169 #define REDIS_VM_MEMORY 0 /* The object is on memory */
170 #define REDIS_VM_SWAPPED 1 /* The object is on disk */
171 #define REDIS_VM_SWAPPING 2 /* Redis is swapping this object on disk */
172 #define REDIS_VM_LOADING 3 /* Redis is loading this object from disk */
174 /* Virtual memory static configuration stuff.
175 * Check vmFindContiguousPages() to know more about this magic numbers. */
176 #define REDIS_VM_MAX_NEAR_PAGES 65536
177 #define REDIS_VM_MAX_RANDOM_JUMP 4096
178 #define REDIS_VM_MAX_THREADS 32
179 #define REDIS_THREAD_STACK_SIZE (1024*1024*4)
180 /* The following is the *percentage* of completed I/O jobs to process when the
181 * handelr is called. While Virtual Memory I/O operations are performed by
182 * threads, this operations must be processed by the main thread when completed
183 * in order to take effect. */
184 #define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
187 #define REDIS_SLAVE 1 /* This client is a slave server */
188 #define REDIS_MASTER 2 /* This client is a master server */
189 #define REDIS_MONITOR 4 /* This client is a slave monitor, see MONITOR */
190 #define REDIS_MULTI 8 /* This client is in a MULTI context */
191 #define REDIS_BLOCKED 16 /* The client is waiting in a blocking operation */
192 #define REDIS_IO_WAIT 32 /* The client is waiting for Virtual Memory I/O */
194 /* Slave replication state - slave side */
195 #define REDIS_REPL_NONE 0 /* No active replication */
196 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
197 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
199 /* Slave replication state - from the point of view of master
200 * Note that in SEND_BULK and ONLINE state the slave receives new updates
201 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
202 * to start the next background saving in order to send updates to it. */
203 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
204 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
205 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
206 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
208 /* List related stuff */
212 /* Sort operations */
213 #define REDIS_SORT_GET 0
214 #define REDIS_SORT_ASC 1
215 #define REDIS_SORT_DESC 2
216 #define REDIS_SORTKEY_MAX 1024
219 #define REDIS_DEBUG 0
220 #define REDIS_VERBOSE 1
221 #define REDIS_NOTICE 2
222 #define REDIS_WARNING 3
224 /* Anti-warning macro... */
225 #define REDIS_NOTUSED(V) ((void) V)
227 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
228 #define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
230 /* Append only defines */
231 #define APPENDFSYNC_NO 0
232 #define APPENDFSYNC_ALWAYS 1
233 #define APPENDFSYNC_EVERYSEC 2
235 /* Hashes related defaults */
236 #define REDIS_HASH_MAX_ZIPMAP_ENTRIES 64
237 #define REDIS_HASH_MAX_ZIPMAP_VALUE 512
239 /* We can print the stacktrace, so our assert is defined this way: */
240 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),_exit(1)))
241 #define redisPanic(_e) _redisPanic(#_e,__FILE__,__LINE__),_exit(1)
242 static void _redisAssert(char *estr
, char *file
, int line
);
243 static void _redisPanic(char *msg
, char *file
, int line
);
245 /*================================= Data types ============================== */
247 /* A redis object, that is a type able to hold a string / list / set */
249 /* The VM object structure */
250 struct redisObjectVM
{
251 off_t page
; /* the page at witch the object is stored on disk */
252 off_t usedpages
; /* number of pages used on disk */
253 time_t atime
; /* Last access time */
256 /* The actual Redis Object */
257 typedef struct redisObject
{
260 unsigned char encoding
;
261 unsigned char storage
; /* If this object is a key, where is the value?
262 * REDIS_VM_MEMORY, REDIS_VM_SWAPPED, ... */
263 unsigned char vtype
; /* If this object is a key, and value is swapped out,
264 * this is the type of the swapped out object. */
266 /* VM fields, this are only allocated if VM is active, otherwise the
267 * object allocation function will just allocate
268 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
269 * Redis without VM active will not have any overhead. */
270 struct redisObjectVM vm
;
273 /* Macro used to initalize a Redis object allocated on the stack.
274 * Note that this macro is taken near the structure definition to make sure
275 * we'll update it when the structure is changed, to avoid bugs like
276 * bug #85 introduced exactly in this way. */
277 #define initStaticStringObject(_var,_ptr) do { \
279 _var.type = REDIS_STRING; \
280 _var.encoding = REDIS_ENCODING_RAW; \
282 if (server.vm_enabled) _var.storage = REDIS_VM_MEMORY; \
285 typedef struct redisDb
{
286 dict
*dict
; /* The keyspace for this DB */
287 dict
*expires
; /* Timeout of keys with a timeout set */
288 dict
*blockingkeys
; /* Keys with clients waiting for data (BLPOP) */
289 dict
*io_keys
; /* Keys with clients waiting for VM I/O */
293 /* Client MULTI/EXEC state */
294 typedef struct multiCmd
{
297 struct redisCommand
*cmd
;
300 typedef struct multiState
{
301 multiCmd
*commands
; /* Array of MULTI commands */
302 int count
; /* Total number of MULTI commands */
305 /* With multiplexing we need to take per-clinet state.
306 * Clients are taken in a liked list. */
307 typedef struct redisClient
{
312 robj
**argv
, **mbargv
;
314 int bulklen
; /* bulk read len. -1 if not in bulk read mode */
315 int multibulk
; /* multi bulk command format active */
318 time_t lastinteraction
; /* time of the last interaction, used for timeout */
319 int flags
; /* REDIS_SLAVE | REDIS_MONITOR | REDIS_MULTI ... */
320 int slaveseldb
; /* slave selected db, if this client is a slave */
321 int authenticated
; /* when requirepass is non-NULL */
322 int replstate
; /* replication state if this is a slave */
323 int repldbfd
; /* replication DB file descriptor */
324 long repldboff
; /* replication DB file offset */
325 off_t repldbsize
; /* replication DB file size */
326 multiState mstate
; /* MULTI/EXEC state */
327 robj
**blockingkeys
; /* The key we are waiting to terminate a blocking
328 * operation such as BLPOP. Otherwise NULL. */
329 int blockingkeysnum
; /* Number of blocking keys */
330 time_t blockingto
; /* Blocking operation timeout. If UNIX current time
331 * is >= blockingto then the operation timed out. */
332 list
*io_keys
; /* Keys this client is waiting to be loaded from the
333 * swap file in order to continue. */
334 dict
*pubsub_channels
; /* channels a client is interested in (SUBSCRIBE) */
335 list
*pubsub_patterns
; /* patterns a client is interested in (SUBSCRIBE) */
343 /* Global server state structure */
348 long long dirty
; /* changes to DB from the last save */
350 list
*slaves
, *monitors
;
351 char neterr
[ANET_ERR_LEN
];
353 int cronloops
; /* number of times the cron function run */
354 list
*objfreelist
; /* A list of freed objects to avoid malloc() */
355 time_t lastsave
; /* Unix time of last save succeeede */
356 /* Fields used only for stats */
357 time_t stat_starttime
; /* server start time */
358 long long stat_numcommands
; /* number of processed commands */
359 long long stat_numconnections
; /* number of connections received */
360 long long stat_expiredkeys
; /* number of expired keys */
374 pid_t bgsavechildpid
;
375 pid_t bgrewritechildpid
;
376 sds bgrewritebuf
; /* buffer taken by parent during oppend only rewrite */
377 sds aofbuf
; /* AOF buffer, written before entering the event loop */
378 struct saveparam
*saveparams
;
383 char *appendfilename
;
387 /* Replication related */
392 redisClient
*master
; /* client that is master for this slave */
394 unsigned int maxclients
;
395 unsigned long long maxmemory
;
396 unsigned int blpop_blocked_clients
;
397 unsigned int vm_blocked_clients
;
398 /* Sort parameters - qsort_r() is only available under BSD so we
399 * have to take this state global, in order to pass it to sortCompare() */
403 /* Virtual memory configuration */
408 unsigned long long vm_max_memory
;
410 size_t hash_max_zipmap_entries
;
411 size_t hash_max_zipmap_value
;
412 /* Virtual memory state */
415 off_t vm_next_page
; /* Next probably empty page */
416 off_t vm_near_pages
; /* Number of pages allocated sequentially */
417 unsigned char *vm_bitmap
; /* Bitmap of free/used pages */
418 time_t unixtime
; /* Unix time sampled every second. */
419 /* Virtual memory I/O threads stuff */
420 /* An I/O thread process an element taken from the io_jobs queue and
421 * put the result of the operation in the io_done list. While the
422 * job is being processed, it's put on io_processing queue. */
423 list
*io_newjobs
; /* List of VM I/O jobs yet to be processed */
424 list
*io_processing
; /* List of VM I/O jobs being processed */
425 list
*io_processed
; /* List of VM I/O jobs already processed */
426 list
*io_ready_clients
; /* Clients ready to be unblocked. All keys loaded */
427 pthread_mutex_t io_mutex
; /* lock to access io_jobs/io_done/io_thread_job */
428 pthread_mutex_t obj_freelist_mutex
; /* safe redis objects creation/free */
429 pthread_mutex_t io_swapfile_mutex
; /* So we can lseek + write */
430 pthread_attr_t io_threads_attr
; /* attributes for threads creation */
431 int io_active_threads
; /* Number of running I/O threads */
432 int vm_max_threads
; /* Max number of I/O threads running at the same time */
433 /* Our main thread is blocked on the event loop, locking for sockets ready
434 * to be read or written, so when a threaded I/O operation is ready to be
435 * processed by the main thread, the I/O thread will use a unix pipe to
436 * awake the main thread. The followings are the two pipe FDs. */
437 int io_ready_pipe_read
;
438 int io_ready_pipe_write
;
439 /* Virtual memory stats */
440 unsigned long long vm_stats_used_pages
;
441 unsigned long long vm_stats_swapped_objects
;
442 unsigned long long vm_stats_swapouts
;
443 unsigned long long vm_stats_swapins
;
445 dict
*pubsub_channels
; /* Map channels to list of subscribed clients */
446 list
*pubsub_patterns
; /* A list of pubsub_patterns */
451 typedef struct pubsubPattern
{
456 typedef void redisCommandProc(redisClient
*c
);
457 typedef void redisVmPreloadProc(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
);
458 struct redisCommand
{
460 redisCommandProc
*proc
;
463 /* Use a function to determine which keys need to be loaded
464 * in the background prior to executing this command. Takes precedence
465 * over vm_firstkey and others, ignored when NULL */
466 redisVmPreloadProc
*vm_preload_proc
;
467 /* What keys should be loaded in background when calling this command? */
468 int vm_firstkey
; /* The first argument that's a key (0 = no keys) */
469 int vm_lastkey
; /* THe last argument that's a key */
470 int vm_keystep
; /* The step between first and last key */
473 struct redisFunctionSym
{
475 unsigned long pointer
;
478 typedef struct _redisSortObject
{
486 typedef struct _redisSortOperation
{
489 } redisSortOperation
;
491 /* ZSETs use a specialized version of Skiplists */
493 typedef struct zskiplistNode
{
494 struct zskiplistNode
**forward
;
495 struct zskiplistNode
*backward
;
501 typedef struct zskiplist
{
502 struct zskiplistNode
*header
, *tail
;
503 unsigned long length
;
507 typedef struct zset
{
512 /* Our shared "common" objects */
514 #define REDIS_SHARED_INTEGERS 10000
515 struct sharedObjectsStruct
{
516 robj
*crlf
, *ok
, *err
, *emptybulk
, *czero
, *cone
, *pong
, *space
,
517 *colon
, *nullbulk
, *nullmultibulk
, *queued
,
518 *emptymultibulk
, *wrongtypeerr
, *nokeyerr
, *syntaxerr
, *sameobjecterr
,
519 *outofrangeerr
, *plus
,
520 *select0
, *select1
, *select2
, *select3
, *select4
,
521 *select5
, *select6
, *select7
, *select8
, *select9
,
522 *messagebulk
, *pmessagebulk
, *subscribebulk
, *unsubscribebulk
, *mbulk3
,
523 *mbulk4
, *psubscribebulk
, *punsubscribebulk
,
524 *integers
[REDIS_SHARED_INTEGERS
];
527 /* Global vars that are actally used as constants. The following double
528 * values are used for double on-disk serialization, and are initialized
529 * at runtime to avoid strange compiler optimizations. */
531 static double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
;
533 /* VM threaded I/O request message */
534 #define REDIS_IOJOB_LOAD 0 /* Load from disk to memory */
535 #define REDIS_IOJOB_PREPARE_SWAP 1 /* Compute needed pages */
536 #define REDIS_IOJOB_DO_SWAP 2 /* Swap from memory to disk */
537 typedef struct iojob
{
538 int type
; /* Request type, REDIS_IOJOB_* */
539 redisDb
*db
;/* Redis database */
540 robj
*key
; /* This I/O request is about swapping this key */
541 robj
*val
; /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
542 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
543 off_t page
; /* Swap page where to read/write the object */
544 off_t pages
; /* Swap pages needed to save object. PREPARE_SWAP return val */
545 int canceled
; /* True if this command was canceled by blocking side of VM */
546 pthread_t thread
; /* ID of the thread processing this entry */
549 /*================================ Prototypes =============================== */
551 static void freeStringObject(robj
*o
);
552 static void freeListObject(robj
*o
);
553 static void freeSetObject(robj
*o
);
554 static void decrRefCount(void *o
);
555 static robj
*createObject(int type
, void *ptr
);
556 static void freeClient(redisClient
*c
);
557 static int rdbLoad(char *filename
);
558 static void addReply(redisClient
*c
, robj
*obj
);
559 static void addReplySds(redisClient
*c
, sds s
);
560 static void incrRefCount(robj
*o
);
561 static int rdbSaveBackground(char *filename
);
562 static robj
*createStringObject(char *ptr
, size_t len
);
563 static robj
*dupStringObject(robj
*o
);
564 static void replicationFeedSlaves(list
*slaves
, int dictid
, robj
**argv
, int argc
);
565 static void replicationFeedMonitors(list
*monitors
, int dictid
, robj
**argv
, int argc
);
566 static void flushAppendOnlyFile(void);
567 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
568 static int syncWithMaster(void);
569 static robj
*tryObjectEncoding(robj
*o
);
570 static robj
*getDecodedObject(robj
*o
);
571 static int removeExpire(redisDb
*db
, robj
*key
);
572 static int expireIfNeeded(redisDb
*db
, robj
*key
);
573 static int deleteIfVolatile(redisDb
*db
, robj
*key
);
574 static int deleteIfSwapped(redisDb
*db
, robj
*key
);
575 static int deleteKey(redisDb
*db
, robj
*key
);
576 static time_t getExpire(redisDb
*db
, robj
*key
);
577 static int setExpire(redisDb
*db
, robj
*key
, time_t when
);
578 static void updateSlavesWaitingBgsave(int bgsaveerr
);
579 static void freeMemoryIfNeeded(void);
580 static int processCommand(redisClient
*c
);
581 static void setupSigSegvAction(void);
582 static void rdbRemoveTempFile(pid_t childpid
);
583 static void aofRemoveTempFile(pid_t childpid
);
584 static size_t stringObjectLen(robj
*o
);
585 static void processInputBuffer(redisClient
*c
);
586 static zskiplist
*zslCreate(void);
587 static void zslFree(zskiplist
*zsl
);
588 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
);
589 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
590 static void initClientMultiState(redisClient
*c
);
591 static void freeClientMultiState(redisClient
*c
);
592 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
);
593 static void unblockClientWaitingData(redisClient
*c
);
594 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
);
595 static void vmInit(void);
596 static void vmMarkPagesFree(off_t page
, off_t count
);
597 static robj
*vmLoadObject(robj
*key
);
598 static robj
*vmPreviewObject(robj
*key
);
599 static int vmSwapOneObjectBlocking(void);
600 static int vmSwapOneObjectThreaded(void);
601 static int vmCanSwapOut(void);
602 static int tryFreeOneObjectFromFreelist(void);
603 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
604 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
605 static void vmCancelThreadedIOJob(robj
*o
);
606 static void lockThreadedIO(void);
607 static void unlockThreadedIO(void);
608 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
);
609 static void freeIOJob(iojob
*j
);
610 static void queueIOJob(iojob
*j
);
611 static int vmWriteObjectOnSwap(robj
*o
, off_t page
);
612 static robj
*vmReadObjectFromSwap(off_t page
, int type
);
613 static void waitEmptyIOJobsQueue(void);
614 static void vmReopenSwapFile(void);
615 static int vmFreePage(off_t page
);
616 static void zunionInterBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
);
617 static void execBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
);
618 static int blockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
);
619 static int dontWaitForSwappedKey(redisClient
*c
, robj
*key
);
620 static void handleClientsBlockedOnSwappedKey(redisDb
*db
, robj
*key
);
621 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
622 static struct redisCommand
*lookupCommand(char *name
);
623 static void call(redisClient
*c
, struct redisCommand
*cmd
);
624 static void resetClient(redisClient
*c
);
625 static void convertToRealHash(robj
*o
);
626 static int pubsubUnsubscribeAllChannels(redisClient
*c
, int notify
);
627 static int pubsubUnsubscribeAllPatterns(redisClient
*c
, int notify
);
628 static void freePubsubPattern(void *p
);
629 static int listMatchPubsubPattern(void *a
, void *b
);
630 static int compareStringObjects(robj
*a
, robj
*b
);
631 static int equalStringObjects(robj
*a
, robj
*b
);
633 static int rewriteAppendOnlyFileBackground(void);
634 static int vmSwapObjectBlocking(robj
*key
, robj
*val
);
635 static int prepareForShutdown();
637 static void authCommand(redisClient
*c
);
638 static void pingCommand(redisClient
*c
);
639 static void echoCommand(redisClient
*c
);
640 static void setCommand(redisClient
*c
);
641 static void setnxCommand(redisClient
*c
);
642 static void setexCommand(redisClient
*c
);
643 static void getCommand(redisClient
*c
);
644 static void delCommand(redisClient
*c
);
645 static void existsCommand(redisClient
*c
);
646 static void incrCommand(redisClient
*c
);
647 static void decrCommand(redisClient
*c
);
648 static void incrbyCommand(redisClient
*c
);
649 static void decrbyCommand(redisClient
*c
);
650 static void selectCommand(redisClient
*c
);
651 static void randomkeyCommand(redisClient
*c
);
652 static void keysCommand(redisClient
*c
);
653 static void dbsizeCommand(redisClient
*c
);
654 static void lastsaveCommand(redisClient
*c
);
655 static void saveCommand(redisClient
*c
);
656 static void bgsaveCommand(redisClient
*c
);
657 static void bgrewriteaofCommand(redisClient
*c
);
658 static void shutdownCommand(redisClient
*c
);
659 static void moveCommand(redisClient
*c
);
660 static void renameCommand(redisClient
*c
);
661 static void renamenxCommand(redisClient
*c
);
662 static void lpushCommand(redisClient
*c
);
663 static void rpushCommand(redisClient
*c
);
664 static void lpopCommand(redisClient
*c
);
665 static void rpopCommand(redisClient
*c
);
666 static void llenCommand(redisClient
*c
);
667 static void lindexCommand(redisClient
*c
);
668 static void lrangeCommand(redisClient
*c
);
669 static void ltrimCommand(redisClient
*c
);
670 static void typeCommand(redisClient
*c
);
671 static void lsetCommand(redisClient
*c
);
672 static void saddCommand(redisClient
*c
);
673 static void sremCommand(redisClient
*c
);
674 static void smoveCommand(redisClient
*c
);
675 static void sismemberCommand(redisClient
*c
);
676 static void scardCommand(redisClient
*c
);
677 static void spopCommand(redisClient
*c
);
678 static void srandmemberCommand(redisClient
*c
);
679 static void sinterCommand(redisClient
*c
);
680 static void sinterstoreCommand(redisClient
*c
);
681 static void sunionCommand(redisClient
*c
);
682 static void sunionstoreCommand(redisClient
*c
);
683 static void sdiffCommand(redisClient
*c
);
684 static void sdiffstoreCommand(redisClient
*c
);
685 static void syncCommand(redisClient
*c
);
686 static void flushdbCommand(redisClient
*c
);
687 static void flushallCommand(redisClient
*c
);
688 static void sortCommand(redisClient
*c
);
689 static void lremCommand(redisClient
*c
);
690 static void rpoplpushcommand(redisClient
*c
);
691 static void infoCommand(redisClient
*c
);
692 static void mgetCommand(redisClient
*c
);
693 static void monitorCommand(redisClient
*c
);
694 static void expireCommand(redisClient
*c
);
695 static void expireatCommand(redisClient
*c
);
696 static void getsetCommand(redisClient
*c
);
697 static void ttlCommand(redisClient
*c
);
698 static void slaveofCommand(redisClient
*c
);
699 static void debugCommand(redisClient
*c
);
700 static void msetCommand(redisClient
*c
);
701 static void msetnxCommand(redisClient
*c
);
702 static void zaddCommand(redisClient
*c
);
703 static void zincrbyCommand(redisClient
*c
);
704 static void zrangeCommand(redisClient
*c
);
705 static void zrangebyscoreCommand(redisClient
*c
);
706 static void zcountCommand(redisClient
*c
);
707 static void zrevrangeCommand(redisClient
*c
);
708 static void zcardCommand(redisClient
*c
);
709 static void zremCommand(redisClient
*c
);
710 static void zscoreCommand(redisClient
*c
);
711 static void zremrangebyscoreCommand(redisClient
*c
);
712 static void multiCommand(redisClient
*c
);
713 static void execCommand(redisClient
*c
);
714 static void discardCommand(redisClient
*c
);
715 static void blpopCommand(redisClient
*c
);
716 static void brpopCommand(redisClient
*c
);
717 static void appendCommand(redisClient
*c
);
718 static void substrCommand(redisClient
*c
);
719 static void zrankCommand(redisClient
*c
);
720 static void zrevrankCommand(redisClient
*c
);
721 static void hsetCommand(redisClient
*c
);
722 static void hsetnxCommand(redisClient
*c
);
723 static void hgetCommand(redisClient
*c
);
724 static void hmsetCommand(redisClient
*c
);
725 static void hmgetCommand(redisClient
*c
);
726 static void hdelCommand(redisClient
*c
);
727 static void hlenCommand(redisClient
*c
);
728 static void zremrangebyrankCommand(redisClient
*c
);
729 static void zunionstoreCommand(redisClient
*c
);
730 static void zinterstoreCommand(redisClient
*c
);
731 static void hkeysCommand(redisClient
*c
);
732 static void hvalsCommand(redisClient
*c
);
733 static void hgetallCommand(redisClient
*c
);
734 static void hexistsCommand(redisClient
*c
);
735 static void configCommand(redisClient
*c
);
736 static void hincrbyCommand(redisClient
*c
);
737 static void subscribeCommand(redisClient
*c
);
738 static void unsubscribeCommand(redisClient
*c
);
739 static void psubscribeCommand(redisClient
*c
);
740 static void punsubscribeCommand(redisClient
*c
);
741 static void publishCommand(redisClient
*c
);
743 /*================================= Globals ================================= */
746 static struct redisServer server
; /* server global state */
747 static struct redisCommand cmdTable
[] = {
748 {"get",getCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
749 {"set",setCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,0,0,0},
750 {"setnx",setnxCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,0,0,0},
751 {"setex",setexCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,0,0,0},
752 {"append",appendCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
753 {"substr",substrCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
754 {"del",delCommand
,-2,REDIS_CMD_INLINE
,NULL
,0,0,0},
755 {"exists",existsCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
756 {"incr",incrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
757 {"decr",decrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
758 {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
,NULL
,1,-1,1},
759 {"rpush",rpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
760 {"lpush",lpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
761 {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
762 {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
763 {"brpop",brpopCommand
,-3,REDIS_CMD_INLINE
,NULL
,1,1,1},
764 {"blpop",blpopCommand
,-3,REDIS_CMD_INLINE
,NULL
,1,1,1},
765 {"llen",llenCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
766 {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
,NULL
,1,1,1},
767 {"lset",lsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
768 {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
769 {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
770 {"lrem",lremCommand
,4,REDIS_CMD_BULK
,NULL
,1,1,1},
771 {"rpoplpush",rpoplpushcommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,2,1},
772 {"sadd",saddCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
773 {"srem",sremCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
774 {"smove",smoveCommand
,4,REDIS_CMD_BULK
,NULL
,1,2,1},
775 {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
776 {"scard",scardCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
777 {"spop",spopCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
778 {"srandmember",srandmemberCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
779 {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
780 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
781 {"sunion",sunionCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
782 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
783 {"sdiff",sdiffCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
784 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
785 {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
786 {"zadd",zaddCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
787 {"zincrby",zincrbyCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
788 {"zrem",zremCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
789 {"zremrangebyscore",zremrangebyscoreCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
790 {"zremrangebyrank",zremrangebyrankCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
791 {"zunionstore",zunionstoreCommand
,-4,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,zunionInterBlockClientOnSwappedKeys
,0,0,0},
792 {"zinterstore",zinterstoreCommand
,-4,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,zunionInterBlockClientOnSwappedKeys
,0,0,0},
793 {"zrange",zrangeCommand
,-4,REDIS_CMD_INLINE
,NULL
,1,1,1},
794 {"zrangebyscore",zrangebyscoreCommand
,-4,REDIS_CMD_INLINE
,NULL
,1,1,1},
795 {"zcount",zcountCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
796 {"zrevrange",zrevrangeCommand
,-4,REDIS_CMD_INLINE
,NULL
,1,1,1},
797 {"zcard",zcardCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
798 {"zscore",zscoreCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
799 {"zrank",zrankCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
800 {"zrevrank",zrevrankCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
801 {"hset",hsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
802 {"hsetnx",hsetnxCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
803 {"hget",hgetCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
804 {"hmset",hmsetCommand
,-4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
805 {"hmget",hmgetCommand
,-3,REDIS_CMD_BULK
,NULL
,1,1,1},
806 {"hincrby",hincrbyCommand
,4,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
807 {"hdel",hdelCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
808 {"hlen",hlenCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
809 {"hkeys",hkeysCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
810 {"hvals",hvalsCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
811 {"hgetall",hgetallCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
812 {"hexists",hexistsCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
813 {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
814 {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
815 {"getset",getsetCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
816 {"mset",msetCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,-1,2},
817 {"msetnx",msetnxCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,-1,2},
818 {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
819 {"select",selectCommand
,2,REDIS_CMD_INLINE
,NULL
,0,0,0},
820 {"move",moveCommand
,3,REDIS_CMD_INLINE
,NULL
,1,1,1},
821 {"rename",renameCommand
,3,REDIS_CMD_INLINE
,NULL
,1,1,1},
822 {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
,NULL
,1,1,1},
823 {"expire",expireCommand
,3,REDIS_CMD_INLINE
,NULL
,0,0,0},
824 {"expireat",expireatCommand
,3,REDIS_CMD_INLINE
,NULL
,0,0,0},
825 {"keys",keysCommand
,2,REDIS_CMD_INLINE
,NULL
,0,0,0},
826 {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
827 {"auth",authCommand
,2,REDIS_CMD_INLINE
,NULL
,0,0,0},
828 {"ping",pingCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
829 {"echo",echoCommand
,2,REDIS_CMD_BULK
,NULL
,0,0,0},
830 {"save",saveCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
831 {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
832 {"bgrewriteaof",bgrewriteaofCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
833 {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
834 {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
835 {"type",typeCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
836 {"multi",multiCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
837 {"exec",execCommand
,1,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,execBlockClientOnSwappedKeys
,0,0,0},
838 {"discard",discardCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
839 {"sync",syncCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
840 {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
841 {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
842 {"sort",sortCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
843 {"info",infoCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
844 {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
845 {"ttl",ttlCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
846 {"slaveof",slaveofCommand
,3,REDIS_CMD_INLINE
,NULL
,0,0,0},
847 {"debug",debugCommand
,-2,REDIS_CMD_INLINE
,NULL
,0,0,0},
848 {"config",configCommand
,-2,REDIS_CMD_BULK
,NULL
,0,0,0},
849 {"subscribe",subscribeCommand
,-2,REDIS_CMD_INLINE
,NULL
,0,0,0},
850 {"unsubscribe",unsubscribeCommand
,-1,REDIS_CMD_INLINE
,NULL
,0,0,0},
851 {"psubscribe",psubscribeCommand
,-2,REDIS_CMD_INLINE
,NULL
,0,0,0},
852 {"punsubscribe",punsubscribeCommand
,-1,REDIS_CMD_INLINE
,NULL
,0,0,0},
853 {"publish",publishCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_FORCE_REPLICATION
,NULL
,0,0,0},
854 {NULL
,NULL
,0,0,NULL
,0,0,0}
857 /*============================ Utility functions ============================ */
859 /* Glob-style pattern matching. */
860 static int stringmatchlen(const char *pattern
, int patternLen
,
861 const char *string
, int stringLen
, int nocase
)
866 while (pattern
[1] == '*') {
871 return 1; /* match */
873 if (stringmatchlen(pattern
+1, patternLen
-1,
874 string
, stringLen
, nocase
))
875 return 1; /* match */
879 return 0; /* no match */
883 return 0; /* no match */
893 not = pattern
[0] == '^';
900 if (pattern
[0] == '\\') {
903 if (pattern
[0] == string
[0])
905 } else if (pattern
[0] == ']') {
907 } else if (patternLen
== 0) {
911 } else if (pattern
[1] == '-' && patternLen
>= 3) {
912 int start
= pattern
[0];
913 int end
= pattern
[2];
921 start
= tolower(start
);
927 if (c
>= start
&& c
<= end
)
931 if (pattern
[0] == string
[0])
934 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
944 return 0; /* no match */
950 if (patternLen
>= 2) {
957 if (pattern
[0] != string
[0])
958 return 0; /* no match */
960 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
961 return 0; /* no match */
969 if (stringLen
== 0) {
970 while(*pattern
== '*') {
977 if (patternLen
== 0 && stringLen
== 0)
982 static int stringmatch(const char *pattern
, const char *string
, int nocase
) {
983 return stringmatchlen(pattern
,strlen(pattern
),string
,strlen(string
),nocase
);
986 /* Convert a string representing an amount of memory into the number of
987 * bytes, so for instance memtoll("1Gi") will return 1073741824 that is
990 * On parsing error, if *err is not NULL, it's set to 1, otherwise it's
992 static long long memtoll(const char *p
, int *err
) {
995 long mul
; /* unit multiplier */
1000 /* Search the first non digit character. */
1003 while(*u
&& isdigit(*u
)) u
++;
1004 if (*u
== '\0' || !strcasecmp(u
,"b")) {
1006 } else if (!strcasecmp(u
,"k")) {
1008 } else if (!strcasecmp(u
,"kb")) {
1010 } else if (!strcasecmp(u
,"m")) {
1012 } else if (!strcasecmp(u
,"mb")) {
1014 } else if (!strcasecmp(u
,"g")) {
1015 mul
= 1000L*1000*1000;
1016 } else if (!strcasecmp(u
,"gb")) {
1017 mul
= 1024L*1024*1024;
1023 if (digits
>= sizeof(buf
)) {
1027 memcpy(buf
,p
,digits
);
1029 val
= strtoll(buf
,NULL
,10);
1033 /* Convert a long long into a string. Returns the number of
1034 * characters needed to represent the number, that can be shorter if passed
1035 * buffer length is not enough to store the whole number. */
1036 static int ll2string(char *s
, size_t len
, long long value
) {
1038 unsigned long long v
;
1041 if (len
== 0) return 0;
1042 v
= (value
< 0) ? -value
: value
;
1043 p
= buf
+31; /* point to the last character */
1048 if (value
< 0) *p
-- = '-';
1051 if (l
+1 > len
) l
= len
-1; /* Make sure it fits, including the nul term */
1057 static void redisLog(int level
, const char *fmt
, ...) {
1061 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
1065 if (level
>= server
.verbosity
) {
1071 strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
));
1072 fprintf(fp
,"[%d] %s %c ",(int)getpid(),buf
,c
[level
]);
1073 vfprintf(fp
, fmt
, ap
);
1079 if (server
.logfile
) fclose(fp
);
1082 /*====================== Hash table type implementation ==================== */
1084 /* This is an hash table type that uses the SDS dynamic strings libary as
1085 * keys and radis objects as values (objects can hold SDS strings,
1088 static void dictVanillaFree(void *privdata
, void *val
)
1090 DICT_NOTUSED(privdata
);
1094 static void dictListDestructor(void *privdata
, void *val
)
1096 DICT_NOTUSED(privdata
);
1097 listRelease((list
*)val
);
1100 static int sdsDictKeyCompare(void *privdata
, const void *key1
,
1104 DICT_NOTUSED(privdata
);
1106 l1
= sdslen((sds
)key1
);
1107 l2
= sdslen((sds
)key2
);
1108 if (l1
!= l2
) return 0;
1109 return memcmp(key1
, key2
, l1
) == 0;
1112 static void dictRedisObjectDestructor(void *privdata
, void *val
)
1114 DICT_NOTUSED(privdata
);
1116 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
1120 static int dictObjKeyCompare(void *privdata
, const void *key1
,
1123 const robj
*o1
= key1
, *o2
= key2
;
1124 return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
1127 static unsigned int dictObjHash(const void *key
) {
1128 const robj
*o
= key
;
1129 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
1132 static int dictEncObjKeyCompare(void *privdata
, const void *key1
,
1135 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
1138 if (o1
->encoding
== REDIS_ENCODING_INT
&&
1139 o2
->encoding
== REDIS_ENCODING_INT
)
1140 return o1
->ptr
== o2
->ptr
;
1142 o1
= getDecodedObject(o1
);
1143 o2
= getDecodedObject(o2
);
1144 cmp
= sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
1150 static unsigned int dictEncObjHash(const void *key
) {
1151 robj
*o
= (robj
*) key
;
1153 if (o
->encoding
== REDIS_ENCODING_RAW
) {
1154 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
1156 if (o
->encoding
== REDIS_ENCODING_INT
) {
1160 len
= ll2string(buf
,32,(long)o
->ptr
);
1161 return dictGenHashFunction((unsigned char*)buf
, len
);
1165 o
= getDecodedObject(o
);
1166 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
1173 /* Sets type and expires */
1174 static dictType setDictType
= {
1175 dictEncObjHash
, /* hash function */
1178 dictEncObjKeyCompare
, /* key compare */
1179 dictRedisObjectDestructor
, /* key destructor */
1180 NULL
/* val destructor */
1183 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
1184 static dictType zsetDictType
= {
1185 dictEncObjHash
, /* hash function */
1188 dictEncObjKeyCompare
, /* key compare */
1189 dictRedisObjectDestructor
, /* key destructor */
1190 dictVanillaFree
/* val destructor of malloc(sizeof(double)) */
1194 static dictType dbDictType
= {
1195 dictObjHash
, /* hash function */
1198 dictObjKeyCompare
, /* key compare */
1199 dictRedisObjectDestructor
, /* key destructor */
1200 dictRedisObjectDestructor
/* val destructor */
1204 static dictType keyptrDictType
= {
1205 dictObjHash
, /* hash function */
1208 dictObjKeyCompare
, /* key compare */
1209 dictRedisObjectDestructor
, /* key destructor */
1210 NULL
/* val destructor */
1213 /* Hash type hash table (note that small hashes are represented with zimpaps) */
1214 static dictType hashDictType
= {
1215 dictEncObjHash
, /* hash function */
1218 dictEncObjKeyCompare
, /* key compare */
1219 dictRedisObjectDestructor
, /* key destructor */
1220 dictRedisObjectDestructor
/* val destructor */
1223 /* Keylist hash table type has unencoded redis objects as keys and
1224 * lists as values. It's used for blocking operations (BLPOP) and to
1225 * map swapped keys to a list of clients waiting for this keys to be loaded. */
1226 static dictType keylistDictType
= {
1227 dictObjHash
, /* hash function */
1230 dictObjKeyCompare
, /* key compare */
1231 dictRedisObjectDestructor
, /* key destructor */
1232 dictListDestructor
/* val destructor */
1235 static void version();
1237 /* ========================= Random utility functions ======================= */
1239 /* Redis generally does not try to recover from out of memory conditions
1240 * when allocating objects or strings, it is not clear if it will be possible
1241 * to report this condition to the client since the networking layer itself
1242 * is based on heap allocation for send buffers, so we simply abort.
1243 * At least the code will be simpler to read... */
1244 static void oom(const char *msg
) {
1245 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
1250 /* ====================== Redis server networking stuff ===================== */
1251 static void closeTimedoutClients(void) {
1254 time_t now
= time(NULL
);
1257 listRewind(server
.clients
,&li
);
1258 while ((ln
= listNext(&li
)) != NULL
) {
1259 c
= listNodeValue(ln
);
1260 if (server
.maxidletime
&&
1261 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
1262 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
1263 dictSize(c
->pubsub_channels
) == 0 && /* no timeout for pubsub */
1264 listLength(c
->pubsub_patterns
) == 0 &&
1265 (now
- c
->lastinteraction
> server
.maxidletime
))
1267 redisLog(REDIS_VERBOSE
,"Closing idle client");
1269 } else if (c
->flags
& REDIS_BLOCKED
) {
1270 if (c
->blockingto
!= 0 && c
->blockingto
< now
) {
1271 addReply(c
,shared
.nullmultibulk
);
1272 unblockClientWaitingData(c
);
1278 static int htNeedsResize(dict
*dict
) {
1279 long long size
, used
;
1281 size
= dictSlots(dict
);
1282 used
= dictSize(dict
);
1283 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
1284 (used
*100/size
< REDIS_HT_MINFILL
));
1287 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
1288 * we resize the hash table to save memory */
1289 static void tryResizeHashTables(void) {
1292 for (j
= 0; j
< server
.dbnum
; j
++) {
1293 if (htNeedsResize(server
.db
[j
].dict
))
1294 dictResize(server
.db
[j
].dict
);
1295 if (htNeedsResize(server
.db
[j
].expires
))
1296 dictResize(server
.db
[j
].expires
);
1300 /* Our hash table implementation performs rehashing incrementally while
1301 * we write/read from the hash table. Still if the server is idle, the hash
1302 * table will use two tables for a long time. So we try to use 1 millisecond
1303 * of CPU time at every serverCron() loop in order to rehash some key. */
1304 static void incrementallyRehash(void) {
1307 for (j
= 0; j
< server
.dbnum
; j
++) {
1308 if (dictIsRehashing(server
.db
[j
].dict
)) {
1309 dictRehashMilliseconds(server
.db
[j
].dict
,1);
1310 break; /* already used our millisecond for this loop... */
1315 /* A background saving child (BGSAVE) terminated its work. Handle this. */
1316 void backgroundSaveDoneHandler(int statloc
) {
1317 int exitcode
= WEXITSTATUS(statloc
);
1318 int bysignal
= WIFSIGNALED(statloc
);
1320 if (!bysignal
&& exitcode
== 0) {
1321 redisLog(REDIS_NOTICE
,
1322 "Background saving terminated with success");
1324 server
.lastsave
= time(NULL
);
1325 } else if (!bysignal
&& exitcode
!= 0) {
1326 redisLog(REDIS_WARNING
, "Background saving error");
1328 redisLog(REDIS_WARNING
,
1329 "Background saving terminated by signal %d", WTERMSIG(statloc
));
1330 rdbRemoveTempFile(server
.bgsavechildpid
);
1332 server
.bgsavechildpid
= -1;
1333 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1334 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1335 updateSlavesWaitingBgsave(exitcode
== 0 ? REDIS_OK
: REDIS_ERR
);
1338 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1340 void backgroundRewriteDoneHandler(int statloc
) {
1341 int exitcode
= WEXITSTATUS(statloc
);
1342 int bysignal
= WIFSIGNALED(statloc
);
1344 if (!bysignal
&& exitcode
== 0) {
1348 redisLog(REDIS_NOTICE
,
1349 "Background append only file rewriting terminated with success");
1350 /* Now it's time to flush the differences accumulated by the parent */
1351 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) server
.bgrewritechildpid
);
1352 fd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
1354 redisLog(REDIS_WARNING
, "Not able to open the temp append only file produced by the child: %s", strerror(errno
));
1357 /* Flush our data... */
1358 if (write(fd
,server
.bgrewritebuf
,sdslen(server
.bgrewritebuf
)) !=
1359 (signed) sdslen(server
.bgrewritebuf
)) {
1360 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
));
1364 redisLog(REDIS_NOTICE
,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server
.bgrewritebuf
));
1365 /* Now our work is to rename the temp file into the stable file. And
1366 * switch the file descriptor used by the server for append only. */
1367 if (rename(tmpfile
,server
.appendfilename
) == -1) {
1368 redisLog(REDIS_WARNING
,"Can't rename the temp append only file into the stable one: %s", strerror(errno
));
1372 /* Mission completed... almost */
1373 redisLog(REDIS_NOTICE
,"Append only file successfully rewritten.");
1374 if (server
.appendfd
!= -1) {
1375 /* If append only is actually enabled... */
1376 close(server
.appendfd
);
1377 server
.appendfd
= fd
;
1379 server
.appendseldb
= -1; /* Make sure it will issue SELECT */
1380 redisLog(REDIS_NOTICE
,"The new append only file was selected for future appends.");
1382 /* If append only is disabled we just generate a dump in this
1383 * format. Why not? */
1386 } else if (!bysignal
&& exitcode
!= 0) {
1387 redisLog(REDIS_WARNING
, "Background append only file rewriting error");
1389 redisLog(REDIS_WARNING
,
1390 "Background append only file rewriting terminated by signal %d",
1394 sdsfree(server
.bgrewritebuf
);
1395 server
.bgrewritebuf
= sdsempty();
1396 aofRemoveTempFile(server
.bgrewritechildpid
);
1397 server
.bgrewritechildpid
= -1;
1400 /* This function is called once a background process of some kind terminates,
1401 * as we want to avoid resizing the hash tables when there is a child in order
1402 * to play well with copy-on-write (otherwise when a resize happens lots of
1403 * memory pages are copied). The goal of this function is to update the ability
1404 * for dict.c to resize the hash tables accordingly to the fact we have o not
1405 * running childs. */
1406 static void updateDictResizePolicy(void) {
1407 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1)
1410 dictDisableResize();
1413 static int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
1414 int j
, loops
= server
.cronloops
++;
1415 REDIS_NOTUSED(eventLoop
);
1417 REDIS_NOTUSED(clientData
);
1419 /* We take a cached value of the unix time in the global state because
1420 * with virtual memory and aging there is to store the current time
1421 * in objects at every object access, and accuracy is not needed.
1422 * To access a global var is faster than calling time(NULL) */
1423 server
.unixtime
= time(NULL
);
1425 /* We received a SIGTERM, shutting down here in a safe way, as it is
1426 * not ok doing so inside the signal handler. */
1427 if (server
.shutdown_asap
) {
1428 if (prepareForShutdown() == REDIS_OK
) exit(0);
1429 redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
1432 /* Show some info about non-empty databases */
1433 for (j
= 0; j
< server
.dbnum
; j
++) {
1434 long long size
, used
, vkeys
;
1436 size
= dictSlots(server
.db
[j
].dict
);
1437 used
= dictSize(server
.db
[j
].dict
);
1438 vkeys
= dictSize(server
.db
[j
].expires
);
1439 if (!(loops
% 50) && (used
|| vkeys
)) {
1440 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
1441 /* dictPrintStats(server.dict); */
1445 /* We don't want to resize the hash tables while a bacground saving
1446 * is in progress: the saving child is created using fork() that is
1447 * implemented with a copy-on-write semantic in most modern systems, so
1448 * if we resize the HT while there is the saving child at work actually
1449 * a lot of memory movements in the parent will cause a lot of pages
1451 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1) {
1452 if (!(loops
% 10)) tryResizeHashTables();
1453 if (server
.activerehashing
) incrementallyRehash();
1456 /* Show information about connected clients */
1457 if (!(loops
% 50)) {
1458 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use",
1459 listLength(server
.clients
)-listLength(server
.slaves
),
1460 listLength(server
.slaves
),
1461 zmalloc_used_memory());
1464 /* Close connections of timedout clients */
1465 if ((server
.maxidletime
&& !(loops
% 100)) || server
.blpop_blocked_clients
)
1466 closeTimedoutClients();
1468 /* Check if a background saving or AOF rewrite in progress terminated */
1469 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
1473 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
1474 if (pid
== server
.bgsavechildpid
) {
1475 backgroundSaveDoneHandler(statloc
);
1477 backgroundRewriteDoneHandler(statloc
);
1479 updateDictResizePolicy();
1482 /* If there is not a background saving in progress check if
1483 * we have to save now */
1484 time_t now
= time(NULL
);
1485 for (j
= 0; j
< server
.saveparamslen
; j
++) {
1486 struct saveparam
*sp
= server
.saveparams
+j
;
1488 if (server
.dirty
>= sp
->changes
&&
1489 now
-server
.lastsave
> sp
->seconds
) {
1490 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
1491 sp
->changes
, sp
->seconds
);
1492 rdbSaveBackground(server
.dbfilename
);
1498 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1499 * will use few CPU cycles if there are few expiring keys, otherwise
1500 * it will get more aggressive to avoid that too much memory is used by
1501 * keys that can be removed from the keyspace. */
1502 for (j
= 0; j
< server
.dbnum
; j
++) {
1504 redisDb
*db
= server
.db
+j
;
1506 /* Continue to expire if at the end of the cycle more than 25%
1507 * of the keys were expired. */
1509 long num
= dictSize(db
->expires
);
1510 time_t now
= time(NULL
);
1513 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
1514 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
1519 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
1520 t
= (time_t) dictGetEntryVal(de
);
1522 deleteKey(db
,dictGetEntryKey(de
));
1524 server
.stat_expiredkeys
++;
1527 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
1530 /* Swap a few keys on disk if we are over the memory limit and VM
1531 * is enbled. Try to free objects from the free list first. */
1532 if (vmCanSwapOut()) {
1533 while (server
.vm_enabled
&& zmalloc_used_memory() >
1534 server
.vm_max_memory
)
1538 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
1539 retval
= (server
.vm_max_threads
== 0) ?
1540 vmSwapOneObjectBlocking() :
1541 vmSwapOneObjectThreaded();
1542 if (retval
== REDIS_ERR
&& !(loops
% 300) &&
1543 zmalloc_used_memory() >
1544 (server
.vm_max_memory
+server
.vm_max_memory
/10))
1546 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
1548 /* Note that when using threade I/O we free just one object,
1549 * because anyway when the I/O thread in charge to swap this
1550 * object out will finish, the handler of completed jobs
1551 * will try to swap more objects if we are still out of memory. */
1552 if (retval
== REDIS_ERR
|| server
.vm_max_threads
> 0) break;
1556 /* Check if we should connect to a MASTER */
1557 if (server
.replstate
== REDIS_REPL_CONNECT
&& !(loops
% 10)) {
1558 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
1559 if (syncWithMaster() == REDIS_OK
) {
1560 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
1561 if (server
.appendonly
) rewriteAppendOnlyFileBackground();
1567 /* This function gets called every time Redis is entering the
1568 * main loop of the event driven library, that is, before to sleep
1569 * for ready file descriptors. */
1570 static void beforeSleep(struct aeEventLoop
*eventLoop
) {
1571 REDIS_NOTUSED(eventLoop
);
1573 /* Awake clients that got all the swapped keys they requested */
1574 if (server
.vm_enabled
&& listLength(server
.io_ready_clients
)) {
1578 listRewind(server
.io_ready_clients
,&li
);
1579 while((ln
= listNext(&li
))) {
1580 redisClient
*c
= ln
->value
;
1581 struct redisCommand
*cmd
;
1583 /* Resume the client. */
1584 listDelNode(server
.io_ready_clients
,ln
);
1585 c
->flags
&= (~REDIS_IO_WAIT
);
1586 server
.vm_blocked_clients
--;
1587 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
1588 readQueryFromClient
, c
);
1589 cmd
= lookupCommand(c
->argv
[0]->ptr
);
1590 assert(cmd
!= NULL
);
1593 /* There may be more data to process in the input buffer. */
1594 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
1595 processInputBuffer(c
);
1598 /* Write the AOF buffer on disk */
1599 flushAppendOnlyFile();
1602 static void createSharedObjects(void) {
1605 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
1606 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
1607 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
1608 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
1609 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
1610 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
1611 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
1612 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
1613 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
1614 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
1615 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
1616 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
1617 "-ERR Operation against a key holding the wrong kind of value\r\n"));
1618 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
1619 "-ERR no such key\r\n"));
1620 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
1621 "-ERR syntax error\r\n"));
1622 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
1623 "-ERR source and destination objects are the same\r\n"));
1624 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
1625 "-ERR index out of range\r\n"));
1626 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
1627 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
1628 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
1629 shared
.select0
= createStringObject("select 0\r\n",10);
1630 shared
.select1
= createStringObject("select 1\r\n",10);
1631 shared
.select2
= createStringObject("select 2\r\n",10);
1632 shared
.select3
= createStringObject("select 3\r\n",10);
1633 shared
.select4
= createStringObject("select 4\r\n",10);
1634 shared
.select5
= createStringObject("select 5\r\n",10);
1635 shared
.select6
= createStringObject("select 6\r\n",10);
1636 shared
.select7
= createStringObject("select 7\r\n",10);
1637 shared
.select8
= createStringObject("select 8\r\n",10);
1638 shared
.select9
= createStringObject("select 9\r\n",10);
1639 shared
.messagebulk
= createStringObject("$7\r\nmessage\r\n",13);
1640 shared
.pmessagebulk
= createStringObject("$8\r\npmessage\r\n",14);
1641 shared
.subscribebulk
= createStringObject("$9\r\nsubscribe\r\n",15);
1642 shared
.unsubscribebulk
= createStringObject("$11\r\nunsubscribe\r\n",18);
1643 shared
.psubscribebulk
= createStringObject("$10\r\npsubscribe\r\n",17);
1644 shared
.punsubscribebulk
= createStringObject("$12\r\npunsubscribe\r\n",19);
1645 shared
.mbulk3
= createStringObject("*3\r\n",4);
1646 shared
.mbulk4
= createStringObject("*4\r\n",4);
1647 for (j
= 0; j
< REDIS_SHARED_INTEGERS
; j
++) {
1648 shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
);
1649 shared
.integers
[j
]->encoding
= REDIS_ENCODING_INT
;
1653 static void appendServerSaveParams(time_t seconds
, int changes
) {
1654 server
.saveparams
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1));
1655 server
.saveparams
[server
.saveparamslen
].seconds
= seconds
;
1656 server
.saveparams
[server
.saveparamslen
].changes
= changes
;
1657 server
.saveparamslen
++;
1660 static void resetServerSaveParams() {
1661 zfree(server
.saveparams
);
1662 server
.saveparams
= NULL
;
1663 server
.saveparamslen
= 0;
1666 static void initServerConfig() {
1667 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
1668 server
.port
= REDIS_SERVERPORT
;
1669 server
.verbosity
= REDIS_VERBOSE
;
1670 server
.maxidletime
= REDIS_MAXIDLETIME
;
1671 server
.saveparams
= NULL
;
1672 server
.logfile
= NULL
; /* NULL = log on standard output */
1673 server
.bindaddr
= NULL
;
1674 server
.glueoutputbuf
= 1;
1675 server
.daemonize
= 0;
1676 server
.appendonly
= 0;
1677 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
1678 server
.lastfsync
= time(NULL
);
1679 server
.appendfd
= -1;
1680 server
.appendseldb
= -1; /* Make sure the first time will not match */
1681 server
.pidfile
= zstrdup("/var/run/redis.pid");
1682 server
.dbfilename
= zstrdup("dump.rdb");
1683 server
.appendfilename
= zstrdup("appendonly.aof");
1684 server
.requirepass
= NULL
;
1685 server
.rdbcompression
= 1;
1686 server
.activerehashing
= 1;
1687 server
.maxclients
= 0;
1688 server
.blpop_blocked_clients
= 0;
1689 server
.maxmemory
= 0;
1690 server
.vm_enabled
= 0;
1691 server
.vm_swap_file
= zstrdup("/tmp/redis-%p.vm");
1692 server
.vm_page_size
= 256; /* 256 bytes per page */
1693 server
.vm_pages
= 1024*1024*100; /* 104 millions of pages */
1694 server
.vm_max_memory
= 1024LL*1024*1024*1; /* 1 GB of RAM */
1695 server
.vm_max_threads
= 4;
1696 server
.vm_blocked_clients
= 0;
1697 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
1698 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
1699 server
.shutdown_asap
= 0;
1701 resetServerSaveParams();
1703 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1704 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1705 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1706 /* Replication related */
1708 server
.masterauth
= NULL
;
1709 server
.masterhost
= NULL
;
1710 server
.masterport
= 6379;
1711 server
.master
= NULL
;
1712 server
.replstate
= REDIS_REPL_NONE
;
1714 /* Double constants initialization */
1716 R_PosInf
= 1.0/R_Zero
;
1717 R_NegInf
= -1.0/R_Zero
;
1718 R_Nan
= R_Zero
/R_Zero
;
1721 static void initServer() {
1724 signal(SIGHUP
, SIG_IGN
);
1725 signal(SIGPIPE
, SIG_IGN
);
1726 setupSigSegvAction();
1728 server
.devnull
= fopen("/dev/null","w");
1729 if (server
.devnull
== NULL
) {
1730 redisLog(REDIS_WARNING
, "Can't open /dev/null: %s", server
.neterr
);
1733 server
.clients
= listCreate();
1734 server
.slaves
= listCreate();
1735 server
.monitors
= listCreate();
1736 server
.objfreelist
= listCreate();
1737 createSharedObjects();
1738 server
.el
= aeCreateEventLoop();
1739 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
1740 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
1741 if (server
.fd
== -1) {
1742 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
1745 for (j
= 0; j
< server
.dbnum
; j
++) {
1746 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
1747 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
1748 server
.db
[j
].blockingkeys
= dictCreate(&keylistDictType
,NULL
);
1749 if (server
.vm_enabled
)
1750 server
.db
[j
].io_keys
= dictCreate(&keylistDictType
,NULL
);
1751 server
.db
[j
].id
= j
;
1753 server
.pubsub_channels
= dictCreate(&keylistDictType
,NULL
);
1754 server
.pubsub_patterns
= listCreate();
1755 listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
);
1756 listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
);
1757 server
.cronloops
= 0;
1758 server
.bgsavechildpid
= -1;
1759 server
.bgrewritechildpid
= -1;
1760 server
.bgrewritebuf
= sdsempty();
1761 server
.aofbuf
= sdsempty();
1762 server
.lastsave
= time(NULL
);
1764 server
.stat_numcommands
= 0;
1765 server
.stat_numconnections
= 0;
1766 server
.stat_expiredkeys
= 0;
1767 server
.stat_starttime
= time(NULL
);
1768 server
.unixtime
= time(NULL
);
1769 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
1770 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
1771 acceptHandler
, NULL
) == AE_ERR
) oom("creating file event");
1773 if (server
.appendonly
) {
1774 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
1775 if (server
.appendfd
== -1) {
1776 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
1782 if (server
.vm_enabled
) vmInit();
1785 /* Empty the whole database */
1786 static long long emptyDb() {
1788 long long removed
= 0;
1790 for (j
= 0; j
< server
.dbnum
; j
++) {
1791 removed
+= dictSize(server
.db
[j
].dict
);
1792 dictEmpty(server
.db
[j
].dict
);
1793 dictEmpty(server
.db
[j
].expires
);
1798 static int yesnotoi(char *s
) {
1799 if (!strcasecmp(s
,"yes")) return 1;
1800 else if (!strcasecmp(s
,"no")) return 0;
1804 /* I agree, this is a very rudimental way to load a configuration...
1805 will improve later if the config gets more complex */
1806 static void loadServerConfig(char *filename
) {
1808 char buf
[REDIS_CONFIGLINE_MAX
+1], *err
= NULL
;
1812 if (filename
[0] == '-' && filename
[1] == '\0')
1815 if ((fp
= fopen(filename
,"r")) == NULL
) {
1816 redisLog(REDIS_WARNING
, "Fatal error, can't open config file '%s'", filename
);
1821 while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) {
1827 line
= sdstrim(line
," \t\r\n");
1829 /* Skip comments and blank lines*/
1830 if (line
[0] == '#' || line
[0] == '\0') {
1835 /* Split into arguments */
1836 argv
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
);
1837 sdstolower(argv
[0]);
1839 /* Execute config directives */
1840 if (!strcasecmp(argv
[0],"timeout") && argc
== 2) {
1841 server
.maxidletime
= atoi(argv
[1]);
1842 if (server
.maxidletime
< 0) {
1843 err
= "Invalid timeout value"; goto loaderr
;
1845 } else if (!strcasecmp(argv
[0],"port") && argc
== 2) {
1846 server
.port
= atoi(argv
[1]);
1847 if (server
.port
< 1 || server
.port
> 65535) {
1848 err
= "Invalid port"; goto loaderr
;
1850 } else if (!strcasecmp(argv
[0],"bind") && argc
== 2) {
1851 server
.bindaddr
= zstrdup(argv
[1]);
1852 } else if (!strcasecmp(argv
[0],"save") && argc
== 3) {
1853 int seconds
= atoi(argv
[1]);
1854 int changes
= atoi(argv
[2]);
1855 if (seconds
< 1 || changes
< 0) {
1856 err
= "Invalid save parameters"; goto loaderr
;
1858 appendServerSaveParams(seconds
,changes
);
1859 } else if (!strcasecmp(argv
[0],"dir") && argc
== 2) {
1860 if (chdir(argv
[1]) == -1) {
1861 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s",
1862 argv
[1], strerror(errno
));
1865 } else if (!strcasecmp(argv
[0],"loglevel") && argc
== 2) {
1866 if (!strcasecmp(argv
[1],"debug")) server
.verbosity
= REDIS_DEBUG
;
1867 else if (!strcasecmp(argv
[1],"verbose")) server
.verbosity
= REDIS_VERBOSE
;
1868 else if (!strcasecmp(argv
[1],"notice")) server
.verbosity
= REDIS_NOTICE
;
1869 else if (!strcasecmp(argv
[1],"warning")) server
.verbosity
= REDIS_WARNING
;
1871 err
= "Invalid log level. Must be one of debug, notice, warning";
1874 } else if (!strcasecmp(argv
[0],"logfile") && argc
== 2) {
1877 server
.logfile
= zstrdup(argv
[1]);
1878 if (!strcasecmp(server
.logfile
,"stdout")) {
1879 zfree(server
.logfile
);
1880 server
.logfile
= NULL
;
1882 if (server
.logfile
) {
1883 /* Test if we are able to open the file. The server will not
1884 * be able to abort just for this problem later... */
1885 logfp
= fopen(server
.logfile
,"a");
1886 if (logfp
== NULL
) {
1887 err
= sdscatprintf(sdsempty(),
1888 "Can't open the log file: %s", strerror(errno
));
1893 } else if (!strcasecmp(argv
[0],"databases") && argc
== 2) {
1894 server
.dbnum
= atoi(argv
[1]);
1895 if (server
.dbnum
< 1) {
1896 err
= "Invalid number of databases"; goto loaderr
;
1898 } else if (!strcasecmp(argv
[0],"include") && argc
== 2) {
1899 loadServerConfig(argv
[1]);
1900 } else if (!strcasecmp(argv
[0],"maxclients") && argc
== 2) {
1901 server
.maxclients
= atoi(argv
[1]);
1902 } else if (!strcasecmp(argv
[0],"maxmemory") && argc
== 2) {
1903 server
.maxmemory
= memtoll(argv
[1],NULL
);
1904 } else if (!strcasecmp(argv
[0],"slaveof") && argc
== 3) {
1905 server
.masterhost
= sdsnew(argv
[1]);
1906 server
.masterport
= atoi(argv
[2]);
1907 server
.replstate
= REDIS_REPL_CONNECT
;
1908 } else if (!strcasecmp(argv
[0],"masterauth") && argc
== 2) {
1909 server
.masterauth
= zstrdup(argv
[1]);
1910 } else if (!strcasecmp(argv
[0],"glueoutputbuf") && argc
== 2) {
1911 if ((server
.glueoutputbuf
= yesnotoi(argv
[1])) == -1) {
1912 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1914 } else if (!strcasecmp(argv
[0],"rdbcompression") && argc
== 2) {
1915 if ((server
.rdbcompression
= yesnotoi(argv
[1])) == -1) {
1916 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1918 } else if (!strcasecmp(argv
[0],"activerehashing") && argc
== 2) {
1919 if ((server
.activerehashing
= yesnotoi(argv
[1])) == -1) {
1920 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1922 } else if (!strcasecmp(argv
[0],"daemonize") && argc
== 2) {
1923 if ((server
.daemonize
= yesnotoi(argv
[1])) == -1) {
1924 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1926 } else if (!strcasecmp(argv
[0],"appendonly") && argc
== 2) {
1927 if ((server
.appendonly
= yesnotoi(argv
[1])) == -1) {
1928 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1930 } else if (!strcasecmp(argv
[0],"appendfilename") && argc
== 2) {
1931 zfree(server
.appendfilename
);
1932 server
.appendfilename
= zstrdup(argv
[1]);
1933 } else if (!strcasecmp(argv
[0],"appendfsync") && argc
== 2) {
1934 if (!strcasecmp(argv
[1],"no")) {
1935 server
.appendfsync
= APPENDFSYNC_NO
;
1936 } else if (!strcasecmp(argv
[1],"always")) {
1937 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1938 } else if (!strcasecmp(argv
[1],"everysec")) {
1939 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
1941 err
= "argument must be 'no', 'always' or 'everysec'";
1944 } else if (!strcasecmp(argv
[0],"requirepass") && argc
== 2) {
1945 server
.requirepass
= zstrdup(argv
[1]);
1946 } else if (!strcasecmp(argv
[0],"pidfile") && argc
== 2) {
1947 zfree(server
.pidfile
);
1948 server
.pidfile
= zstrdup(argv
[1]);
1949 } else if (!strcasecmp(argv
[0],"dbfilename") && argc
== 2) {
1950 zfree(server
.dbfilename
);
1951 server
.dbfilename
= zstrdup(argv
[1]);
1952 } else if (!strcasecmp(argv
[0],"vm-enabled") && argc
== 2) {
1953 if ((server
.vm_enabled
= yesnotoi(argv
[1])) == -1) {
1954 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1956 } else if (!strcasecmp(argv
[0],"vm-swap-file") && argc
== 2) {
1957 zfree(server
.vm_swap_file
);
1958 server
.vm_swap_file
= zstrdup(argv
[1]);
1959 } else if (!strcasecmp(argv
[0],"vm-max-memory") && argc
== 2) {
1960 server
.vm_max_memory
= memtoll(argv
[1],NULL
);
1961 } else if (!strcasecmp(argv
[0],"vm-page-size") && argc
== 2) {
1962 server
.vm_page_size
= memtoll(argv
[1], NULL
);
1963 } else if (!strcasecmp(argv
[0],"vm-pages") && argc
== 2) {
1964 server
.vm_pages
= memtoll(argv
[1], NULL
);
1965 } else if (!strcasecmp(argv
[0],"vm-max-threads") && argc
== 2) {
1966 server
.vm_max_threads
= strtoll(argv
[1], NULL
, 10);
1967 } else if (!strcasecmp(argv
[0],"hash-max-zipmap-entries") && argc
== 2){
1968 server
.hash_max_zipmap_entries
= memtoll(argv
[1], NULL
);
1969 } else if (!strcasecmp(argv
[0],"hash-max-zipmap-value") && argc
== 2){
1970 server
.hash_max_zipmap_value
= memtoll(argv
[1], NULL
);
1972 err
= "Bad directive or wrong number of arguments"; goto loaderr
;
1974 for (j
= 0; j
< argc
; j
++)
1979 if (fp
!= stdin
) fclose(fp
);
1983 fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n");
1984 fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
);
1985 fprintf(stderr
, ">>> '%s'\n", line
);
1986 fprintf(stderr
, "%s\n", err
);
1990 static void freeClientArgv(redisClient
*c
) {
1993 for (j
= 0; j
< c
->argc
; j
++)
1994 decrRefCount(c
->argv
[j
]);
1995 for (j
= 0; j
< c
->mbargc
; j
++)
1996 decrRefCount(c
->mbargv
[j
]);
2001 static void freeClient(redisClient
*c
) {
2004 /* Note that if the client we are freeing is blocked into a blocking
2005 * call, we have to set querybuf to NULL *before* to call
2006 * unblockClientWaitingData() to avoid processInputBuffer() will get
2007 * called. Also it is important to remove the file events after
2008 * this, because this call adds the READABLE event. */
2009 sdsfree(c
->querybuf
);
2011 if (c
->flags
& REDIS_BLOCKED
)
2012 unblockClientWaitingData(c
);
2014 /* Unsubscribe from all the pubsub channels */
2015 pubsubUnsubscribeAllChannels(c
,0);
2016 pubsubUnsubscribeAllPatterns(c
,0);
2017 dictRelease(c
->pubsub_channels
);
2018 listRelease(c
->pubsub_patterns
);
2019 /* Obvious cleanup */
2020 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
2021 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
2022 listRelease(c
->reply
);
2025 /* Remove from the list of clients */
2026 ln
= listSearchKey(server
.clients
,c
);
2027 redisAssert(ln
!= NULL
);
2028 listDelNode(server
.clients
,ln
);
2029 /* Remove from the list of clients waiting for swapped keys */
2030 if (c
->flags
& REDIS_IO_WAIT
&& listLength(c
->io_keys
) == 0) {
2031 ln
= listSearchKey(server
.io_ready_clients
,c
);
2033 listDelNode(server
.io_ready_clients
,ln
);
2034 server
.vm_blocked_clients
--;
2037 while (server
.vm_enabled
&& listLength(c
->io_keys
)) {
2038 ln
= listFirst(c
->io_keys
);
2039 dontWaitForSwappedKey(c
,ln
->value
);
2041 listRelease(c
->io_keys
);
2042 /* Master/slave cleanup */
2043 if (c
->flags
& REDIS_SLAVE
) {
2044 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
2046 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
2047 ln
= listSearchKey(l
,c
);
2048 redisAssert(ln
!= NULL
);
2051 if (c
->flags
& REDIS_MASTER
) {
2052 server
.master
= NULL
;
2053 server
.replstate
= REDIS_REPL_CONNECT
;
2055 /* Release memory */
2058 freeClientMultiState(c
);
2062 #define GLUEREPLY_UP_TO (1024)
2063 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
2065 char buf
[GLUEREPLY_UP_TO
];
2070 listRewind(c
->reply
,&li
);
2071 while((ln
= listNext(&li
))) {
2075 objlen
= sdslen(o
->ptr
);
2076 if (copylen
+ objlen
<= GLUEREPLY_UP_TO
) {
2077 memcpy(buf
+copylen
,o
->ptr
,objlen
);
2079 listDelNode(c
->reply
,ln
);
2081 if (copylen
== 0) return;
2085 /* Now the output buffer is empty, add the new single element */
2086 o
= createObject(REDIS_STRING
,sdsnewlen(buf
,copylen
));
2087 listAddNodeHead(c
->reply
,o
);
2090 static void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2091 redisClient
*c
= privdata
;
2092 int nwritten
= 0, totwritten
= 0, objlen
;
2095 REDIS_NOTUSED(mask
);
2097 /* Use writev() if we have enough buffers to send */
2098 if (!server
.glueoutputbuf
&&
2099 listLength(c
->reply
) > REDIS_WRITEV_THRESHOLD
&&
2100 !(c
->flags
& REDIS_MASTER
))
2102 sendReplyToClientWritev(el
, fd
, privdata
, mask
);
2106 while(listLength(c
->reply
)) {
2107 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
2108 glueReplyBuffersIfNeeded(c
);
2110 o
= listNodeValue(listFirst(c
->reply
));
2111 objlen
= sdslen(o
->ptr
);
2114 listDelNode(c
->reply
,listFirst(c
->reply
));
2118 if (c
->flags
& REDIS_MASTER
) {
2119 /* Don't reply to a master */
2120 nwritten
= objlen
- c
->sentlen
;
2122 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen
- c
->sentlen
);
2123 if (nwritten
<= 0) break;
2125 c
->sentlen
+= nwritten
;
2126 totwritten
+= nwritten
;
2127 /* If we fully sent the object on head go to the next one */
2128 if (c
->sentlen
== objlen
) {
2129 listDelNode(c
->reply
,listFirst(c
->reply
));
2132 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
2133 * bytes, in a single threaded server it's a good idea to serve
2134 * other clients as well, even if a very large request comes from
2135 * super fast link that is always able to accept data (in real world
2136 * scenario think about 'KEYS *' against the loopback interfae) */
2137 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
) break;
2139 if (nwritten
== -1) {
2140 if (errno
== EAGAIN
) {
2143 redisLog(REDIS_VERBOSE
,
2144 "Error writing to client: %s", strerror(errno
));
2149 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
2150 if (listLength(c
->reply
) == 0) {
2152 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
2156 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
)
2158 redisClient
*c
= privdata
;
2159 int nwritten
= 0, totwritten
= 0, objlen
, willwrite
;
2161 struct iovec iov
[REDIS_WRITEV_IOVEC_COUNT
];
2162 int offset
, ion
= 0;
2164 REDIS_NOTUSED(mask
);
2167 while (listLength(c
->reply
)) {
2168 offset
= c
->sentlen
;
2172 /* fill-in the iov[] array */
2173 for(node
= listFirst(c
->reply
); node
; node
= listNextNode(node
)) {
2174 o
= listNodeValue(node
);
2175 objlen
= sdslen(o
->ptr
);
2177 if (totwritten
+ objlen
- offset
> REDIS_MAX_WRITE_PER_EVENT
)
2180 if(ion
== REDIS_WRITEV_IOVEC_COUNT
)
2181 break; /* no more iovecs */
2183 iov
[ion
].iov_base
= ((char*)o
->ptr
) + offset
;
2184 iov
[ion
].iov_len
= objlen
- offset
;
2185 willwrite
+= objlen
- offset
;
2186 offset
= 0; /* just for the first item */
2193 /* write all collected blocks at once */
2194 if((nwritten
= writev(fd
, iov
, ion
)) < 0) {
2195 if (errno
!= EAGAIN
) {
2196 redisLog(REDIS_VERBOSE
,
2197 "Error writing to client: %s", strerror(errno
));
2204 totwritten
+= nwritten
;
2205 offset
= c
->sentlen
;
2207 /* remove written robjs from c->reply */
2208 while (nwritten
&& listLength(c
->reply
)) {
2209 o
= listNodeValue(listFirst(c
->reply
));
2210 objlen
= sdslen(o
->ptr
);
2212 if(nwritten
>= objlen
- offset
) {
2213 listDelNode(c
->reply
, listFirst(c
->reply
));
2214 nwritten
-= objlen
- offset
;
2218 c
->sentlen
+= nwritten
;
2226 c
->lastinteraction
= time(NULL
);
2228 if (listLength(c
->reply
) == 0) {
2230 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
2234 static struct redisCommand
*lookupCommand(char *name
) {
2236 while(cmdTable
[j
].name
!= NULL
) {
2237 if (!strcasecmp(name
,cmdTable
[j
].name
)) return &cmdTable
[j
];
2243 /* resetClient prepare the client to process the next command */
2244 static void resetClient(redisClient
*c
) {
2250 /* Call() is the core of Redis execution of a command */
2251 static void call(redisClient
*c
, struct redisCommand
*cmd
) {
2254 dirty
= server
.dirty
;
2256 dirty
= server
.dirty
-dirty
;
2258 if (server
.appendonly
&& dirty
)
2259 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
2260 if ((dirty
|| cmd
->flags
& REDIS_CMD_FORCE_REPLICATION
) &&
2261 listLength(server
.slaves
))
2262 replicationFeedSlaves(server
.slaves
,c
->db
->id
,c
->argv
,c
->argc
);
2263 if (listLength(server
.monitors
))
2264 replicationFeedMonitors(server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
);
2265 server
.stat_numcommands
++;
2268 /* If this function gets called we already read a whole
2269 * command, argments are in the client argv/argc fields.
2270 * processCommand() execute the command or prepare the
2271 * server for a bulk read from the client.
2273 * If 1 is returned the client is still alive and valid and
2274 * and other operations can be performed by the caller. Otherwise
2275 * if 0 is returned the client was destroied (i.e. after QUIT). */
2276 static int processCommand(redisClient
*c
) {
2277 struct redisCommand
*cmd
;
2279 /* Free some memory if needed (maxmemory setting) */
2280 if (server
.maxmemory
) freeMemoryIfNeeded();
2282 /* Handle the multi bulk command type. This is an alternative protocol
2283 * supported by Redis in order to receive commands that are composed of
2284 * multiple binary-safe "bulk" arguments. The latency of processing is
2285 * a bit higher but this allows things like multi-sets, so if this
2286 * protocol is used only for MSET and similar commands this is a big win. */
2287 if (c
->multibulk
== 0 && c
->argc
== 1 && ((char*)(c
->argv
[0]->ptr
))[0] == '*') {
2288 c
->multibulk
= atoi(((char*)c
->argv
[0]->ptr
)+1);
2289 if (c
->multibulk
<= 0) {
2293 decrRefCount(c
->argv
[c
->argc
-1]);
2297 } else if (c
->multibulk
) {
2298 if (c
->bulklen
== -1) {
2299 if (((char*)c
->argv
[0]->ptr
)[0] != '$') {
2300 addReplySds(c
,sdsnew("-ERR multi bulk protocol error\r\n"));
2304 int bulklen
= atoi(((char*)c
->argv
[0]->ptr
)+1);
2305 decrRefCount(c
->argv
[0]);
2306 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
2308 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
2313 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
2317 c
->mbargv
= zrealloc(c
->mbargv
,(sizeof(robj
*))*(c
->mbargc
+1));
2318 c
->mbargv
[c
->mbargc
] = c
->argv
[0];
2322 if (c
->multibulk
== 0) {
2326 /* Here we need to swap the multi-bulk argc/argv with the
2327 * normal argc/argv of the client structure. */
2329 c
->argv
= c
->mbargv
;
2330 c
->mbargv
= auxargv
;
2333 c
->argc
= c
->mbargc
;
2334 c
->mbargc
= auxargc
;
2336 /* We need to set bulklen to something different than -1
2337 * in order for the code below to process the command without
2338 * to try to read the last argument of a bulk command as
2339 * a special argument. */
2341 /* continue below and process the command */
2348 /* -- end of multi bulk commands processing -- */
2350 /* The QUIT command is handled as a special case. Normal command
2351 * procs are unable to close the client connection safely */
2352 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
2357 /* Now lookup the command and check ASAP about trivial error conditions
2358 * such wrong arity, bad command name and so forth. */
2359 cmd
= lookupCommand(c
->argv
[0]->ptr
);
2362 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
2363 (char*)c
->argv
[0]->ptr
));
2366 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
2367 (c
->argc
< -cmd
->arity
)) {
2369 sdscatprintf(sdsempty(),
2370 "-ERR wrong number of arguments for '%s' command\r\n",
2374 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
2375 /* This is a bulk command, we have to read the last argument yet. */
2376 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
2378 decrRefCount(c
->argv
[c
->argc
-1]);
2379 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
2381 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
2386 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
2387 /* It is possible that the bulk read is already in the
2388 * buffer. Check this condition and handle it accordingly.
2389 * This is just a fast path, alternative to call processInputBuffer().
2390 * It's a good idea since the code is small and this condition
2391 * happens most of the times. */
2392 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
2393 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2395 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2397 /* Otherwise return... there is to read the last argument
2398 * from the socket. */
2402 /* Let's try to encode the bulk object to save space. */
2403 if (cmd
->flags
& REDIS_CMD_BULK
)
2404 c
->argv
[c
->argc
-1] = tryObjectEncoding(c
->argv
[c
->argc
-1]);
2406 /* Check if the user is authenticated */
2407 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
2408 addReplySds(c
,sdsnew("-ERR operation not permitted\r\n"));
2413 /* Handle the maxmemory directive */
2414 if (server
.maxmemory
&& (cmd
->flags
& REDIS_CMD_DENYOOM
) &&
2415 zmalloc_used_memory() > server
.maxmemory
)
2417 addReplySds(c
,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
2422 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
2423 if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0)
2425 cmd
->proc
!= subscribeCommand
&& cmd
->proc
!= unsubscribeCommand
&&
2426 cmd
->proc
!= psubscribeCommand
&& cmd
->proc
!= punsubscribeCommand
) {
2427 addReplySds(c
,sdsnew("-ERR only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context\r\n"));
2432 /* Exec the command */
2433 if (c
->flags
& REDIS_MULTI
&& cmd
->proc
!= execCommand
&& cmd
->proc
!= discardCommand
) {
2434 queueMultiCommand(c
,cmd
);
2435 addReply(c
,shared
.queued
);
2437 if (server
.vm_enabled
&& server
.vm_max_threads
> 0 &&
2438 blockClientOnSwappedKeys(c
,cmd
)) return 1;
2442 /* Prepare the client for the next command */
2447 static void replicationFeedSlaves(list
*slaves
, int dictid
, robj
**argv
, int argc
) {
2452 /* We need 1+(ARGS*3) objects since commands are using the new protocol
2453 * and we one 1 object for the first "*<count>\r\n" multibulk count, then
2454 * for every additional object we have "$<count>\r\n" + object + "\r\n". */
2455 robj
*static_outv
[REDIS_STATIC_ARGS
*3+1];
2458 if (argc
<= REDIS_STATIC_ARGS
) {
2461 outv
= zmalloc(sizeof(robj
*)*(argc
*3+1));
2464 lenobj
= createObject(REDIS_STRING
,
2465 sdscatprintf(sdsempty(), "*%d\r\n", argc
));
2466 lenobj
->refcount
= 0;
2467 outv
[outc
++] = lenobj
;
2468 for (j
= 0; j
< argc
; j
++) {
2469 lenobj
= createObject(REDIS_STRING
,
2470 sdscatprintf(sdsempty(),"$%lu\r\n",
2471 (unsigned long) stringObjectLen(argv
[j
])));
2472 lenobj
->refcount
= 0;
2473 outv
[outc
++] = lenobj
;
2474 outv
[outc
++] = argv
[j
];
2475 outv
[outc
++] = shared
.crlf
;
2478 /* Increment all the refcounts at start and decrement at end in order to
2479 * be sure to free objects if there is no slave in a replication state
2480 * able to be feed with commands */
2481 for (j
= 0; j
< outc
; j
++) incrRefCount(outv
[j
]);
2482 listRewind(slaves
,&li
);
2483 while((ln
= listNext(&li
))) {
2484 redisClient
*slave
= ln
->value
;
2486 /* Don't feed slaves that are still waiting for BGSAVE to start */
2487 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) continue;
2489 /* Feed all the other slaves, MONITORs and so on */
2490 if (slave
->slaveseldb
!= dictid
) {
2494 case 0: selectcmd
= shared
.select0
; break;
2495 case 1: selectcmd
= shared
.select1
; break;
2496 case 2: selectcmd
= shared
.select2
; break;
2497 case 3: selectcmd
= shared
.select3
; break;
2498 case 4: selectcmd
= shared
.select4
; break;
2499 case 5: selectcmd
= shared
.select5
; break;
2500 case 6: selectcmd
= shared
.select6
; break;
2501 case 7: selectcmd
= shared
.select7
; break;
2502 case 8: selectcmd
= shared
.select8
; break;
2503 case 9: selectcmd
= shared
.select9
; break;
2505 selectcmd
= createObject(REDIS_STRING
,
2506 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
2507 selectcmd
->refcount
= 0;
2510 addReply(slave
,selectcmd
);
2511 slave
->slaveseldb
= dictid
;
2513 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
2515 for (j
= 0; j
< outc
; j
++) decrRefCount(outv
[j
]);
2516 if (outv
!= static_outv
) zfree(outv
);
2519 static sds
sdscatrepr(sds s
, char *p
, size_t len
) {
2520 s
= sdscatlen(s
,"\"",1);
2525 s
= sdscatprintf(s
,"\\%c",*p
);
2527 case '\n': s
= sdscatlen(s
,"\\n",1); break;
2528 case '\r': s
= sdscatlen(s
,"\\r",1); break;
2529 case '\t': s
= sdscatlen(s
,"\\t",1); break;
2530 case '\a': s
= sdscatlen(s
,"\\a",1); break;
2531 case '\b': s
= sdscatlen(s
,"\\b",1); break;
2534 s
= sdscatprintf(s
,"%c",*p
);
2536 s
= sdscatprintf(s
,"\\x%02x",(unsigned char)*p
);
2541 return sdscatlen(s
,"\"",1);
2544 static void replicationFeedMonitors(list
*monitors
, int dictid
, robj
**argv
, int argc
) {
2548 sds cmdrepr
= sdsnew("+");
2552 gettimeofday(&tv
,NULL
);
2553 cmdrepr
= sdscatprintf(cmdrepr
,"%ld.%ld ",(long)tv
.tv_sec
,(long)tv
.tv_usec
);
2554 if (dictid
!= 0) cmdrepr
= sdscatprintf(cmdrepr
,"(db %d) ", dictid
);
2556 for (j
= 0; j
< argc
; j
++) {
2557 if (argv
[j
]->encoding
== REDIS_ENCODING_INT
) {
2558 cmdrepr
= sdscatprintf(cmdrepr
, "%ld", (long)argv
[j
]->ptr
);
2560 cmdrepr
= sdscatrepr(cmdrepr
,(char*)argv
[j
]->ptr
,
2561 sdslen(argv
[j
]->ptr
));
2564 cmdrepr
= sdscatlen(cmdrepr
," ",1);
2566 cmdrepr
= sdscatlen(cmdrepr
,"\r\n",2);
2567 cmdobj
= createObject(REDIS_STRING
,cmdrepr
);
2569 listRewind(monitors
,&li
);
2570 while((ln
= listNext(&li
))) {
2571 redisClient
*monitor
= ln
->value
;
2572 addReply(monitor
,cmdobj
);
2574 decrRefCount(cmdobj
);
2577 static void processInputBuffer(redisClient
*c
) {
2579 /* Before to process the input buffer, make sure the client is not
2580 * waitig for a blocking operation such as BLPOP. Note that the first
2581 * iteration the client is never blocked, otherwise the processInputBuffer
2582 * would not be called at all, but after the execution of the first commands
2583 * in the input buffer the client may be blocked, and the "goto again"
2584 * will try to reiterate. The following line will make it return asap. */
2585 if (c
->flags
& REDIS_BLOCKED
|| c
->flags
& REDIS_IO_WAIT
) return;
2586 if (c
->bulklen
== -1) {
2587 /* Read the first line of the query */
2588 char *p
= strchr(c
->querybuf
,'\n');
2595 query
= c
->querybuf
;
2596 c
->querybuf
= sdsempty();
2597 querylen
= 1+(p
-(query
));
2598 if (sdslen(query
) > querylen
) {
2599 /* leave data after the first line of the query in the buffer */
2600 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
2602 *p
= '\0'; /* remove "\n" */
2603 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
2604 sdsupdatelen(query
);
2606 /* Now we can split the query in arguments */
2607 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
2610 if (c
->argv
) zfree(c
->argv
);
2611 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
2613 for (j
= 0; j
< argc
; j
++) {
2614 if (sdslen(argv
[j
])) {
2615 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
2623 /* Execute the command. If the client is still valid
2624 * after processCommand() return and there is something
2625 * on the query buffer try to process the next command. */
2626 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2628 /* Nothing to process, argc == 0. Just process the query
2629 * buffer if it's not empty or return to the caller */
2630 if (sdslen(c
->querybuf
)) goto again
;
2633 } else if (sdslen(c
->querybuf
) >= REDIS_REQUEST_MAX_SIZE
) {
2634 redisLog(REDIS_VERBOSE
, "Client protocol error");
2639 /* Bulk read handling. Note that if we are at this point
2640 the client already sent a command terminated with a newline,
2641 we are reading the bulk data that is actually the last
2642 argument of the command. */
2643 int qbl
= sdslen(c
->querybuf
);
2645 if (c
->bulklen
<= qbl
) {
2646 /* Copy everything but the final CRLF as final argument */
2647 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2649 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2650 /* Process the command. If the client is still valid after
2651 * the processing and there is more data in the buffer
2652 * try to parse it. */
2653 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2659 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2660 redisClient
*c
= (redisClient
*) privdata
;
2661 char buf
[REDIS_IOBUF_LEN
];
2664 REDIS_NOTUSED(mask
);
2666 nread
= read(fd
, buf
, REDIS_IOBUF_LEN
);
2668 if (errno
== EAGAIN
) {
2671 redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
));
2675 } else if (nread
== 0) {
2676 redisLog(REDIS_VERBOSE
, "Client closed connection");
2681 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
2682 c
->lastinteraction
= time(NULL
);
2686 processInputBuffer(c
);
2689 static int selectDb(redisClient
*c
, int id
) {
2690 if (id
< 0 || id
>= server
.dbnum
)
2692 c
->db
= &server
.db
[id
];
2696 static void *dupClientReplyValue(void *o
) {
2697 incrRefCount((robj
*)o
);
2701 static int listMatchObjects(void *a
, void *b
) {
2702 return equalStringObjects(a
,b
);
2705 static redisClient
*createClient(int fd
) {
2706 redisClient
*c
= zmalloc(sizeof(*c
));
2708 anetNonBlock(NULL
,fd
);
2709 anetTcpNoDelay(NULL
,fd
);
2710 if (!c
) return NULL
;
2713 c
->querybuf
= sdsempty();
2722 c
->lastinteraction
= time(NULL
);
2723 c
->authenticated
= 0;
2724 c
->replstate
= REDIS_REPL_NONE
;
2725 c
->reply
= listCreate();
2726 listSetFreeMethod(c
->reply
,decrRefCount
);
2727 listSetDupMethod(c
->reply
,dupClientReplyValue
);
2728 c
->blockingkeys
= NULL
;
2729 c
->blockingkeysnum
= 0;
2730 c
->io_keys
= listCreate();
2731 listSetFreeMethod(c
->io_keys
,decrRefCount
);
2732 c
->pubsub_channels
= dictCreate(&setDictType
,NULL
);
2733 c
->pubsub_patterns
= listCreate();
2734 listSetFreeMethod(c
->pubsub_patterns
,decrRefCount
);
2735 listSetMatchMethod(c
->pubsub_patterns
,listMatchObjects
);
2736 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
2737 readQueryFromClient
, c
) == AE_ERR
) {
2741 listAddNodeTail(server
.clients
,c
);
2742 initClientMultiState(c
);
2746 static void addReply(redisClient
*c
, robj
*obj
) {
2747 if (listLength(c
->reply
) == 0 &&
2748 (c
->replstate
== REDIS_REPL_NONE
||
2749 c
->replstate
== REDIS_REPL_ONLINE
) &&
2750 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
2751 sendReplyToClient
, c
) == AE_ERR
) return;
2753 if (server
.vm_enabled
&& obj
->storage
!= REDIS_VM_MEMORY
) {
2754 obj
= dupStringObject(obj
);
2755 obj
->refcount
= 0; /* getDecodedObject() will increment the refcount */
2757 listAddNodeTail(c
->reply
,getDecodedObject(obj
));
2760 static void addReplySds(redisClient
*c
, sds s
) {
2761 robj
*o
= createObject(REDIS_STRING
,s
);
2766 static void addReplyDouble(redisClient
*c
, double d
) {
2769 snprintf(buf
,sizeof(buf
),"%.17g",d
);
2770 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
2771 (unsigned long) strlen(buf
),buf
));
2774 static void addReplyLongLong(redisClient
*c
, long long ll
) {
2779 addReply(c
,shared
.czero
);
2781 } else if (ll
== 1) {
2782 addReply(c
,shared
.cone
);
2786 len
= ll2string(buf
+1,sizeof(buf
)-1,ll
);
2789 addReplySds(c
,sdsnewlen(buf
,len
+3));
2792 static void addReplyUlong(redisClient
*c
, unsigned long ul
) {
2797 addReply(c
,shared
.czero
);
2799 } else if (ul
== 1) {
2800 addReply(c
,shared
.cone
);
2803 len
= snprintf(buf
,sizeof(buf
),":%lu\r\n",ul
);
2804 addReplySds(c
,sdsnewlen(buf
,len
));
2807 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) {
2827 intlen
= ll2string(buf
+1,sizeof(buf
)-1,(long long)len
);
2828 buf
[intlen
+1] = '\r';
2829 buf
[intlen
+2] = '\n';
2830 addReplySds(c
,sdsnewlen(buf
,intlen
+3));
2833 static void addReplyBulk(redisClient
*c
, robj
*obj
) {
2834 addReplyBulkLen(c
,obj
);
2836 addReply(c
,shared
.crlf
);
2839 /* In the CONFIG command we need to add vanilla C string as bulk replies */
2840 static void addReplyBulkCString(redisClient
*c
, char *s
) {
2842 addReply(c
,shared
.nullbulk
);
2844 robj
*o
= createStringObject(s
,strlen(s
));
2850 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2855 REDIS_NOTUSED(mask
);
2856 REDIS_NOTUSED(privdata
);
2858 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
2859 if (cfd
== AE_ERR
) {
2860 redisLog(REDIS_VERBOSE
,"Accepting client connection: %s", server
.neterr
);
2863 redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
);
2864 if ((c
= createClient(cfd
)) == NULL
) {
2865 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
2866 close(cfd
); /* May be already closed, just ingore errors */
2869 /* If maxclient directive is set and this is one client more... close the
2870 * connection. Note that we create the client instead to check before
2871 * for this condition, since now the socket is already set in nonblocking
2872 * mode and we can send an error for free using the Kernel I/O */
2873 if (server
.maxclients
&& listLength(server
.clients
) > server
.maxclients
) {
2874 char *err
= "-ERR max number of clients reached\r\n";
2876 /* That's a best effort error message, don't check write errors */
2877 if (write(c
->fd
,err
,strlen(err
)) == -1) {
2878 /* Nothing to do, Just to avoid the warning... */
2883 server
.stat_numconnections
++;
2886 /* ======================= Redis objects implementation ===================== */
2888 static robj
*createObject(int type
, void *ptr
) {
2891 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
2892 if (listLength(server
.objfreelist
)) {
2893 listNode
*head
= listFirst(server
.objfreelist
);
2894 o
= listNodeValue(head
);
2895 listDelNode(server
.objfreelist
,head
);
2896 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2898 if (server
.vm_enabled
) {
2899 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2900 o
= zmalloc(sizeof(*o
));
2902 o
= zmalloc(sizeof(*o
)-sizeof(struct redisObjectVM
));
2906 o
->encoding
= REDIS_ENCODING_RAW
;
2909 if (server
.vm_enabled
) {
2910 /* Note that this code may run in the context of an I/O thread
2911 * and accessing to server.unixtime in theory is an error
2912 * (no locks). But in practice this is safe, and even if we read
2913 * garbage Redis will not fail, as it's just a statistical info */
2914 o
->vm
.atime
= server
.unixtime
;
2915 o
->storage
= REDIS_VM_MEMORY
;
2920 static robj
*createStringObject(char *ptr
, size_t len
) {
2921 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
2924 static robj
*createStringObjectFromLongLong(long long value
) {
2926 if (value
>= 0 && value
< REDIS_SHARED_INTEGERS
) {
2927 incrRefCount(shared
.integers
[value
]);
2928 o
= shared
.integers
[value
];
2930 o
= createObject(REDIS_STRING
, NULL
);
2931 if (value
>= LONG_MIN
&& value
<= LONG_MAX
) {
2932 o
->encoding
= REDIS_ENCODING_INT
;
2933 o
->ptr
= (void*)((long)value
);
2935 o
= createObject(REDIS_STRING
,sdsfromlonglong(value
));
2941 static robj
*dupStringObject(robj
*o
) {
2942 assert(o
->encoding
== REDIS_ENCODING_RAW
);
2943 return createStringObject(o
->ptr
,sdslen(o
->ptr
));
2946 static robj
*createListObject(void) {
2947 list
*l
= listCreate();
2949 listSetFreeMethod(l
,decrRefCount
);
2950 return createObject(REDIS_LIST
,l
);
2953 static robj
*createSetObject(void) {
2954 dict
*d
= dictCreate(&setDictType
,NULL
);
2955 return createObject(REDIS_SET
,d
);
2958 static robj
*createHashObject(void) {
2959 /* All the Hashes start as zipmaps. Will be automatically converted
2960 * into hash tables if there are enough elements or big elements
2962 unsigned char *zm
= zipmapNew();
2963 robj
*o
= createObject(REDIS_HASH
,zm
);
2964 o
->encoding
= REDIS_ENCODING_ZIPMAP
;
2968 static robj
*createZsetObject(void) {
2969 zset
*zs
= zmalloc(sizeof(*zs
));
2971 zs
->dict
= dictCreate(&zsetDictType
,NULL
);
2972 zs
->zsl
= zslCreate();
2973 return createObject(REDIS_ZSET
,zs
);
2976 static void freeStringObject(robj
*o
) {
2977 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2982 static void freeListObject(robj
*o
) {
2983 listRelease((list
*) o
->ptr
);
2986 static void freeSetObject(robj
*o
) {
2987 dictRelease((dict
*) o
->ptr
);
2990 static void freeZsetObject(robj
*o
) {
2993 dictRelease(zs
->dict
);
2998 static void freeHashObject(robj
*o
) {
2999 switch (o
->encoding
) {
3000 case REDIS_ENCODING_HT
:
3001 dictRelease((dict
*) o
->ptr
);
3003 case REDIS_ENCODING_ZIPMAP
:
3007 redisPanic("Unknown hash encoding type");
3012 static void incrRefCount(robj
*o
) {
3016 static void decrRefCount(void *obj
) {
3019 if (o
->refcount
<= 0) redisPanic("decrRefCount against refcount <= 0");
3020 /* Object is a key of a swapped out value, or in the process of being
3022 if (server
.vm_enabled
&&
3023 (o
->storage
== REDIS_VM_SWAPPED
|| o
->storage
== REDIS_VM_LOADING
))
3025 if (o
->storage
== REDIS_VM_LOADING
) vmCancelThreadedIOJob(obj
);
3026 redisAssert(o
->type
== REDIS_STRING
);
3027 freeStringObject(o
);
3028 vmMarkPagesFree(o
->vm
.page
,o
->vm
.usedpages
);
3029 pthread_mutex_lock(&server
.obj_freelist_mutex
);
3030 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
3031 !listAddNodeHead(server
.objfreelist
,o
))
3033 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
3034 server
.vm_stats_swapped_objects
--;
3037 /* Object is in memory, or in the process of being swapped out. */
3038 if (--(o
->refcount
) == 0) {
3039 if (server
.vm_enabled
&& o
->storage
== REDIS_VM_SWAPPING
)
3040 vmCancelThreadedIOJob(obj
);
3042 case REDIS_STRING
: freeStringObject(o
); break;
3043 case REDIS_LIST
: freeListObject(o
); break;
3044 case REDIS_SET
: freeSetObject(o
); break;
3045 case REDIS_ZSET
: freeZsetObject(o
); break;
3046 case REDIS_HASH
: freeHashObject(o
); break;
3047 default: redisPanic("Unknown object type"); break;
3049 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
3050 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
3051 !listAddNodeHead(server
.objfreelist
,o
))
3053 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
3057 static robj
*lookupKey(redisDb
*db
, robj
*key
) {
3058 dictEntry
*de
= dictFind(db
->dict
,key
);
3060 robj
*key
= dictGetEntryKey(de
);
3061 robj
*val
= dictGetEntryVal(de
);
3063 if (server
.vm_enabled
) {
3064 if (key
->storage
== REDIS_VM_MEMORY
||
3065 key
->storage
== REDIS_VM_SWAPPING
)
3067 /* If we were swapping the object out, stop it, this key
3069 if (key
->storage
== REDIS_VM_SWAPPING
)
3070 vmCancelThreadedIOJob(key
);
3071 /* Update the access time of the key for the aging algorithm. */
3072 key
->vm
.atime
= server
.unixtime
;
3074 int notify
= (key
->storage
== REDIS_VM_LOADING
);
3076 /* Our value was swapped on disk. Bring it at home. */
3077 redisAssert(val
== NULL
);
3078 val
= vmLoadObject(key
);
3079 dictGetEntryVal(de
) = val
;
3081 /* Clients blocked by the VM subsystem may be waiting for
3083 if (notify
) handleClientsBlockedOnSwappedKey(db
,key
);
3092 static robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
3093 expireIfNeeded(db
,key
);
3094 return lookupKey(db
,key
);
3097 static robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
3098 deleteIfVolatile(db
,key
);
3099 return lookupKey(db
,key
);
3102 static robj
*lookupKeyReadOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
3103 robj
*o
= lookupKeyRead(c
->db
, key
);
3104 if (!o
) addReply(c
,reply
);
3108 static robj
*lookupKeyWriteOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
3109 robj
*o
= lookupKeyWrite(c
->db
, key
);
3110 if (!o
) addReply(c
,reply
);
3114 static int checkType(redisClient
*c
, robj
*o
, int type
) {
3115 if (o
->type
!= type
) {
3116 addReply(c
,shared
.wrongtypeerr
);
3122 static int deleteKey(redisDb
*db
, robj
*key
) {
3125 /* We need to protect key from destruction: after the first dictDelete()
3126 * it may happen that 'key' is no longer valid if we don't increment
3127 * it's count. This may happen when we get the object reference directly
3128 * from the hash table with dictRandomKey() or dict iterators */
3130 if (dictSize(db
->expires
)) dictDelete(db
->expires
,key
);
3131 retval
= dictDelete(db
->dict
,key
);
3134 return retval
== DICT_OK
;
3137 /* Check if the nul-terminated string 's' can be represented by a long
3138 * (that is, is a number that fits into long without any other space or
3139 * character before or after the digits).
3141 * If so, the function returns REDIS_OK and *longval is set to the value
3142 * of the number. Otherwise REDIS_ERR is returned */
3143 static int isStringRepresentableAsLong(sds s
, long *longval
) {
3144 char buf
[32], *endptr
;
3148 value
= strtol(s
, &endptr
, 10);
3149 if (endptr
[0] != '\0') return REDIS_ERR
;
3150 slen
= ll2string(buf
,32,value
);
3152 /* If the number converted back into a string is not identical
3153 * then it's not possible to encode the string as integer */
3154 if (sdslen(s
) != (unsigned)slen
|| memcmp(buf
,s
,slen
)) return REDIS_ERR
;
3155 if (longval
) *longval
= value
;
3159 /* Try to encode a string object in order to save space */
3160 static robj
*tryObjectEncoding(robj
*o
) {
3164 if (o
->encoding
!= REDIS_ENCODING_RAW
)
3165 return o
; /* Already encoded */
3167 /* It's not safe to encode shared objects: shared objects can be shared
3168 * everywhere in the "object space" of Redis. Encoded objects can only
3169 * appear as "values" (and not, for instance, as keys) */
3170 if (o
->refcount
> 1) return o
;
3172 /* Currently we try to encode only strings */
3173 redisAssert(o
->type
== REDIS_STRING
);
3175 /* Check if we can represent this string as a long integer */
3176 if (isStringRepresentableAsLong(s
,&value
) == REDIS_ERR
) return o
;
3178 /* Ok, this object can be encoded */
3179 if (value
>= 0 && value
< REDIS_SHARED_INTEGERS
) {
3181 incrRefCount(shared
.integers
[value
]);
3182 return shared
.integers
[value
];
3184 o
->encoding
= REDIS_ENCODING_INT
;
3186 o
->ptr
= (void*) value
;
3191 /* Get a decoded version of an encoded object (returned as a new object).
3192 * If the object is already raw-encoded just increment the ref count. */
3193 static robj
*getDecodedObject(robj
*o
) {
3196 if (o
->encoding
== REDIS_ENCODING_RAW
) {
3200 if (o
->type
== REDIS_STRING
&& o
->encoding
== REDIS_ENCODING_INT
) {
3203 ll2string(buf
,32,(long)o
->ptr
);
3204 dec
= createStringObject(buf
,strlen(buf
));
3207 redisPanic("Unknown encoding type");
3211 /* Compare two string objects via strcmp() or alike.
3212 * Note that the objects may be integer-encoded. In such a case we
3213 * use ll2string() to get a string representation of the numbers on the stack
3214 * and compare the strings, it's much faster than calling getDecodedObject().
3216 * Important note: if objects are not integer encoded, but binary-safe strings,
3217 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
3219 static int compareStringObjects(robj
*a
, robj
*b
) {
3220 redisAssert(a
->type
== REDIS_STRING
&& b
->type
== REDIS_STRING
);
3221 char bufa
[128], bufb
[128], *astr
, *bstr
;
3224 if (a
== b
) return 0;
3225 if (a
->encoding
!= REDIS_ENCODING_RAW
) {
3226 ll2string(bufa
,sizeof(bufa
),(long) a
->ptr
);
3232 if (b
->encoding
!= REDIS_ENCODING_RAW
) {
3233 ll2string(bufb
,sizeof(bufb
),(long) b
->ptr
);
3239 return bothsds
? sdscmp(astr
,bstr
) : strcmp(astr
,bstr
);
3242 /* Equal string objects return 1 if the two objects are the same from the
3243 * point of view of a string comparison, otherwise 0 is returned. Note that
3244 * this function is faster then checking for (compareStringObject(a,b) == 0)
3245 * because it can perform some more optimization. */
3246 static int equalStringObjects(robj
*a
, robj
*b
) {
3247 if (a
->encoding
!= REDIS_ENCODING_RAW
&& b
->encoding
!= REDIS_ENCODING_RAW
){
3248 return a
->ptr
== b
->ptr
;
3250 return compareStringObjects(a
,b
) == 0;
3254 static size_t stringObjectLen(robj
*o
) {
3255 redisAssert(o
->type
== REDIS_STRING
);
3256 if (o
->encoding
== REDIS_ENCODING_RAW
) {
3257 return sdslen(o
->ptr
);
3261 return ll2string(buf
,32,(long)o
->ptr
);
3265 static int getDoubleFromObject(robj
*o
, double *target
) {
3272 redisAssert(o
->type
== REDIS_STRING
);
3273 if (o
->encoding
== REDIS_ENCODING_RAW
) {
3274 value
= strtod(o
->ptr
, &eptr
);
3275 if (eptr
[0] != '\0') return REDIS_ERR
;
3276 } else if (o
->encoding
== REDIS_ENCODING_INT
) {
3277 value
= (long)o
->ptr
;
3279 redisPanic("Unknown string encoding");
3287 static int getDoubleFromObjectOrReply(redisClient
*c
, robj
*o
, double *target
, const char *msg
) {
3289 if (getDoubleFromObject(o
, &value
) != REDIS_OK
) {
3291 addReplySds(c
, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg
));
3293 addReplySds(c
, sdsnew("-ERR value is not a double\r\n"));
3302 static int getLongLongFromObject(robj
*o
, long long *target
) {
3309 redisAssert(o
->type
== REDIS_STRING
);
3310 if (o
->encoding
== REDIS_ENCODING_RAW
) {
3311 value
= strtoll(o
->ptr
, &eptr
, 10);
3312 if (eptr
[0] != '\0') return REDIS_ERR
;
3313 } else if (o
->encoding
== REDIS_ENCODING_INT
) {
3314 value
= (long)o
->ptr
;
3316 redisPanic("Unknown string encoding");
3324 static int getLongLongFromObjectOrReply(redisClient
*c
, robj
*o
, long long *target
, const char *msg
) {
3326 if (getLongLongFromObject(o
, &value
) != REDIS_OK
) {
3328 addReplySds(c
, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg
));
3330 addReplySds(c
, sdsnew("-ERR value is not an integer\r\n"));
3339 static int getLongFromObjectOrReply(redisClient
*c
, robj
*o
, long *target
, const char *msg
) {
3342 if (getLongLongFromObjectOrReply(c
, o
, &value
, msg
) != REDIS_OK
) return REDIS_ERR
;
3343 if (value
< LONG_MIN
|| value
> LONG_MAX
) {
3345 addReplySds(c
, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg
));
3347 addReplySds(c
, sdsnew("-ERR value is out of range\r\n"));
3356 /*============================ RDB saving/loading =========================== */
3358 static int rdbSaveType(FILE *fp
, unsigned char type
) {
3359 if (fwrite(&type
,1,1,fp
) == 0) return -1;
3363 static int rdbSaveTime(FILE *fp
, time_t t
) {
3364 int32_t t32
= (int32_t) t
;
3365 if (fwrite(&t32
,4,1,fp
) == 0) return -1;
3369 /* check rdbLoadLen() comments for more info */
3370 static int rdbSaveLen(FILE *fp
, uint32_t len
) {
3371 unsigned char buf
[2];
3374 /* Save a 6 bit len */
3375 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
3376 if (fwrite(buf
,1,1,fp
) == 0) return -1;
3377 } else if (len
< (1<<14)) {
3378 /* Save a 14 bit len */
3379 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
3381 if (fwrite(buf
,2,1,fp
) == 0) return -1;
3383 /* Save a 32 bit len */
3384 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
3385 if (fwrite(buf
,1,1,fp
) == 0) return -1;
3387 if (fwrite(&len
,4,1,fp
) == 0) return -1;
3392 /* Encode 'value' as an integer if possible (if integer will fit the
3393 * supported range). If the function sucessful encoded the integer
3394 * then the (up to 5 bytes) encoded representation is written in the
3395 * string pointed by 'enc' and the length is returned. Otherwise
3397 static int rdbEncodeInteger(long long value
, unsigned char *enc
) {
3398 /* Finally check if it fits in our ranges */
3399 if (value
>= -(1<<7) && value
<= (1<<7)-1) {
3400 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT8
;
3401 enc
[1] = value
&0xFF;
3403 } else if (value
>= -(1<<15) && value
<= (1<<15)-1) {
3404 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
;
3405 enc
[1] = value
&0xFF;
3406 enc
[2] = (value
>>8)&0xFF;
3408 } else if (value
>= -((long long)1<<31) && value
<= ((long long)1<<31)-1) {
3409 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT32
;
3410 enc
[1] = value
&0xFF;
3411 enc
[2] = (value
>>8)&0xFF;
3412 enc
[3] = (value
>>16)&0xFF;
3413 enc
[4] = (value
>>24)&0xFF;
3420 /* String objects in the form "2391" "-100" without any space and with a
3421 * range of values that can fit in an 8, 16 or 32 bit signed value can be
3422 * encoded as integers to save space */
3423 static int rdbTryIntegerEncoding(char *s
, size_t len
, unsigned char *enc
) {
3425 char *endptr
, buf
[32];
3427 /* Check if it's possible to encode this value as a number */
3428 value
= strtoll(s
, &endptr
, 10);
3429 if (endptr
[0] != '\0') return 0;
3430 ll2string(buf
,32,value
);
3432 /* If the number converted back into a string is not identical
3433 * then it's not possible to encode the string as integer */
3434 if (strlen(buf
) != len
|| memcmp(buf
,s
,len
)) return 0;
3436 return rdbEncodeInteger(value
,enc
);
3439 static int rdbSaveLzfStringObject(FILE *fp
, unsigned char *s
, size_t len
) {
3440 size_t comprlen
, outlen
;
3444 /* We require at least four bytes compression for this to be worth it */
3445 if (len
<= 4) return 0;
3447 if ((out
= zmalloc(outlen
+1)) == NULL
) return 0;
3448 comprlen
= lzf_compress(s
, len
, out
, outlen
);
3449 if (comprlen
== 0) {
3453 /* Data compressed! Let's save it on disk */
3454 byte
= (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_LZF
;
3455 if (fwrite(&byte
,1,1,fp
) == 0) goto writeerr
;
3456 if (rdbSaveLen(fp
,comprlen
) == -1) goto writeerr
;
3457 if (rdbSaveLen(fp
,len
) == -1) goto writeerr
;
3458 if (fwrite(out
,comprlen
,1,fp
) == 0) goto writeerr
;
3467 /* Save a string objet as [len][data] on disk. If the object is a string
3468 * representation of an integer value we try to safe it in a special form */
3469 static int rdbSaveRawString(FILE *fp
, unsigned char *s
, size_t len
) {
3472 /* Try integer encoding */
3474 unsigned char buf
[5];
3475 if ((enclen
= rdbTryIntegerEncoding((char*)s
,len
,buf
)) > 0) {
3476 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
3481 /* Try LZF compression - under 20 bytes it's unable to compress even
3482 * aaaaaaaaaaaaaaaaaa so skip it */
3483 if (server
.rdbcompression
&& len
> 20) {
3486 retval
= rdbSaveLzfStringObject(fp
,s
,len
);
3487 if (retval
== -1) return -1;
3488 if (retval
> 0) return 0;
3489 /* retval == 0 means data can't be compressed, save the old way */
3492 /* Store verbatim */
3493 if (rdbSaveLen(fp
,len
) == -1) return -1;
3494 if (len
&& fwrite(s
,len
,1,fp
) == 0) return -1;
3498 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
3499 static int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
3502 /* Avoid to decode the object, then encode it again, if the
3503 * object is alrady integer encoded. */
3504 if (obj
->encoding
== REDIS_ENCODING_INT
) {
3505 long val
= (long) obj
->ptr
;
3506 unsigned char buf
[5];
3509 if ((enclen
= rdbEncodeInteger(val
,buf
)) > 0) {
3510 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
3513 /* otherwise... fall throught and continue with the usual
3517 /* Avoid incr/decr ref count business when possible.
3518 * This plays well with copy-on-write given that we are probably
3519 * in a child process (BGSAVE). Also this makes sure key objects
3520 * of swapped objects are not incRefCount-ed (an assert does not allow
3521 * this in order to avoid bugs) */
3522 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
3523 obj
= getDecodedObject(obj
);
3524 retval
= rdbSaveRawString(fp
,obj
->ptr
,sdslen(obj
->ptr
));
3527 retval
= rdbSaveRawString(fp
,obj
->ptr
,sdslen(obj
->ptr
));
3532 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
3533 * 8 bit integer specifing the length of the representation.
3534 * This 8 bit integer has special values in order to specify the following
3540 static int rdbSaveDoubleValue(FILE *fp
, double val
) {
3541 unsigned char buf
[128];
3547 } else if (!isfinite(val
)) {
3549 buf
[0] = (val
< 0) ? 255 : 254;
3551 #if (DBL_MANT_DIG >= 52) && (LLONG_MAX == 0x7fffffffffffffffLL)
3552 /* Check if the float is in a safe range to be casted into a
3553 * long long. We are assuming that long long is 64 bit here.
3554 * Also we are assuming that there are no implementations around where
3555 * double has precision < 52 bit.
3557 * Under this assumptions we test if a double is inside an interval
3558 * where casting to long long is safe. Then using two castings we
3559 * make sure the decimal part is zero. If all this is true we use
3560 * integer printing function that is much faster. */
3561 double min
= -4503599627370495; /* (2^52)-1 */
3562 double max
= 4503599627370496; /* -(2^52) */
3563 if (val
> min
&& val
< max
&& val
== ((double)((long long)val
)))
3564 ll2string((char*)buf
+1,sizeof(buf
),(long long)val
);
3567 snprintf((char*)buf
+1,sizeof(buf
)-1,"%.17g",val
);
3568 buf
[0] = strlen((char*)buf
+1);
3571 if (fwrite(buf
,len
,1,fp
) == 0) return -1;
3575 /* Save a Redis object. */
3576 static int rdbSaveObject(FILE *fp
, robj
*o
) {
3577 if (o
->type
== REDIS_STRING
) {
3578 /* Save a string value */
3579 if (rdbSaveStringObject(fp
,o
) == -1) return -1;
3580 } else if (o
->type
== REDIS_LIST
) {
3581 /* Save a list value */
3582 list
*list
= o
->ptr
;
3586 if (rdbSaveLen(fp
,listLength(list
)) == -1) return -1;
3587 listRewind(list
,&li
);
3588 while((ln
= listNext(&li
))) {
3589 robj
*eleobj
= listNodeValue(ln
);
3591 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
3593 } else if (o
->type
== REDIS_SET
) {
3594 /* Save a set value */
3596 dictIterator
*di
= dictGetIterator(set
);
3599 if (rdbSaveLen(fp
,dictSize(set
)) == -1) return -1;
3600 while((de
= dictNext(di
)) != NULL
) {
3601 robj
*eleobj
= dictGetEntryKey(de
);
3603 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
3605 dictReleaseIterator(di
);
3606 } else if (o
->type
== REDIS_ZSET
) {
3607 /* Save a set value */
3609 dictIterator
*di
= dictGetIterator(zs
->dict
);
3612 if (rdbSaveLen(fp
,dictSize(zs
->dict
)) == -1) return -1;
3613 while((de
= dictNext(di
)) != NULL
) {
3614 robj
*eleobj
= dictGetEntryKey(de
);
3615 double *score
= dictGetEntryVal(de
);
3617 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
3618 if (rdbSaveDoubleValue(fp
,*score
) == -1) return -1;
3620 dictReleaseIterator(di
);
3621 } else if (o
->type
== REDIS_HASH
) {
3622 /* Save a hash value */
3623 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
3624 unsigned char *p
= zipmapRewind(o
->ptr
);
3625 unsigned int count
= zipmapLen(o
->ptr
);
3626 unsigned char *key
, *val
;
3627 unsigned int klen
, vlen
;
3629 if (rdbSaveLen(fp
,count
) == -1) return -1;
3630 while((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) != NULL
) {
3631 if (rdbSaveRawString(fp
,key
,klen
) == -1) return -1;
3632 if (rdbSaveRawString(fp
,val
,vlen
) == -1) return -1;
3635 dictIterator
*di
= dictGetIterator(o
->ptr
);
3638 if (rdbSaveLen(fp
,dictSize((dict
*)o
->ptr
)) == -1) return -1;
3639 while((de
= dictNext(di
)) != NULL
) {
3640 robj
*key
= dictGetEntryKey(de
);
3641 robj
*val
= dictGetEntryVal(de
);
3643 if (rdbSaveStringObject(fp
,key
) == -1) return -1;
3644 if (rdbSaveStringObject(fp
,val
) == -1) return -1;
3646 dictReleaseIterator(di
);
3649 redisPanic("Unknown object type");
3654 /* Return the length the object will have on disk if saved with
3655 * the rdbSaveObject() function. Currently we use a trick to get
3656 * this length with very little changes to the code. In the future
3657 * we could switch to a faster solution. */
3658 static off_t
rdbSavedObjectLen(robj
*o
, FILE *fp
) {
3659 if (fp
== NULL
) fp
= server
.devnull
;
3661 assert(rdbSaveObject(fp
,o
) != 1);
3665 /* Return the number of pages required to save this object in the swap file */
3666 static off_t
rdbSavedObjectPages(robj
*o
, FILE *fp
) {
3667 off_t bytes
= rdbSavedObjectLen(o
,fp
);
3669 return (bytes
+(server
.vm_page_size
-1))/server
.vm_page_size
;
3672 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
3673 static int rdbSave(char *filename
) {
3674 dictIterator
*di
= NULL
;
3679 time_t now
= time(NULL
);
3681 /* Wait for I/O therads to terminate, just in case this is a
3682 * foreground-saving, to avoid seeking the swap file descriptor at the
3684 if (server
.vm_enabled
)
3685 waitEmptyIOJobsQueue();
3687 snprintf(tmpfile
,256,"temp-%d.rdb", (int) getpid());
3688 fp
= fopen(tmpfile
,"w");
3690 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
3693 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
3694 for (j
= 0; j
< server
.dbnum
; j
++) {
3695 redisDb
*db
= server
.db
+j
;
3697 if (dictSize(d
) == 0) continue;
3698 di
= dictGetIterator(d
);
3704 /* Write the SELECT DB opcode */
3705 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
3706 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
3708 /* Iterate this DB writing every entry */
3709 while((de
= dictNext(di
)) != NULL
) {
3710 robj
*key
= dictGetEntryKey(de
);
3711 robj
*o
= dictGetEntryVal(de
);
3712 time_t expiretime
= getExpire(db
,key
);
3714 /* Save the expire time */
3715 if (expiretime
!= -1) {
3716 /* If this key is already expired skip it */
3717 if (expiretime
< now
) continue;
3718 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
;
3719 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
;
3721 /* Save the key and associated value. This requires special
3722 * handling if the value is swapped out. */
3723 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
3724 key
->storage
== REDIS_VM_SWAPPING
) {
3725 /* Save type, key, value */
3726 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
3727 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3728 if (rdbSaveObject(fp
,o
) == -1) goto werr
;
3730 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
3732 /* Get a preview of the object in memory */
3733 po
= vmPreviewObject(key
);
3734 /* Save type, key, value */
3735 if (rdbSaveType(fp
,key
->vtype
) == -1) goto werr
;
3736 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3737 if (rdbSaveObject(fp
,po
) == -1) goto werr
;
3738 /* Remove the loaded object from memory */
3742 dictReleaseIterator(di
);
3745 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
3747 /* Make sure data will not remain on the OS's output buffers */
3752 /* Use RENAME to make sure the DB file is changed atomically only
3753 * if the generate DB file is ok. */
3754 if (rename(tmpfile
,filename
) == -1) {
3755 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destination: %s", strerror(errno
));
3759 redisLog(REDIS_NOTICE
,"DB saved on disk");
3761 server
.lastsave
= time(NULL
);
3767 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
3768 if (di
) dictReleaseIterator(di
);
3772 static int rdbSaveBackground(char *filename
) {
3775 if (server
.bgsavechildpid
!= -1) return REDIS_ERR
;
3776 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
3777 if ((childpid
= fork()) == 0) {
3779 if (server
.vm_enabled
) vmReopenSwapFile();
3781 if (rdbSave(filename
) == REDIS_OK
) {
3788 if (childpid
== -1) {
3789 redisLog(REDIS_WARNING
,"Can't save in background: fork: %s",
3793 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
3794 server
.bgsavechildpid
= childpid
;
3795 updateDictResizePolicy();
3798 return REDIS_OK
; /* unreached */
3801 static void rdbRemoveTempFile(pid_t childpid
) {
3804 snprintf(tmpfile
,256,"temp-%d.rdb", (int) childpid
);
3808 static int rdbLoadType(FILE *fp
) {
3810 if (fread(&type
,1,1,fp
) == 0) return -1;
3814 static time_t rdbLoadTime(FILE *fp
) {
3816 if (fread(&t32
,4,1,fp
) == 0) return -1;
3817 return (time_t) t32
;
3820 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
3821 * of this file for a description of how this are stored on disk.
3823 * isencoded is set to 1 if the readed length is not actually a length but
3824 * an "encoding type", check the above comments for more info */
3825 static uint32_t rdbLoadLen(FILE *fp
, int *isencoded
) {
3826 unsigned char buf
[2];
3830 if (isencoded
) *isencoded
= 0;
3831 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3832 type
= (buf
[0]&0xC0)>>6;
3833 if (type
== REDIS_RDB_6BITLEN
) {
3834 /* Read a 6 bit len */
3836 } else if (type
== REDIS_RDB_ENCVAL
) {
3837 /* Read a 6 bit len encoding type */
3838 if (isencoded
) *isencoded
= 1;
3840 } else if (type
== REDIS_RDB_14BITLEN
) {
3841 /* Read a 14 bit len */
3842 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3843 return ((buf
[0]&0x3F)<<8)|buf
[1];
3845 /* Read a 32 bit len */
3846 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
3851 /* Load an integer-encoded object from file 'fp', with the specified
3852 * encoding type 'enctype'. If encode is true the function may return
3853 * an integer-encoded object as reply, otherwise the returned object
3854 * will always be encoded as a raw string. */
3855 static robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
, int encode
) {
3856 unsigned char enc
[4];
3859 if (enctype
== REDIS_RDB_ENC_INT8
) {
3860 if (fread(enc
,1,1,fp
) == 0) return NULL
;
3861 val
= (signed char)enc
[0];
3862 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
3864 if (fread(enc
,2,1,fp
) == 0) return NULL
;
3865 v
= enc
[0]|(enc
[1]<<8);
3867 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
3869 if (fread(enc
,4,1,fp
) == 0) return NULL
;
3870 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
3873 val
= 0; /* anti-warning */
3874 redisPanic("Unknown RDB integer encoding type");
3877 return createStringObjectFromLongLong(val
);
3879 return createObject(REDIS_STRING
,sdsfromlonglong(val
));
3882 static robj
*rdbLoadLzfStringObject(FILE*fp
) {
3883 unsigned int len
, clen
;
3884 unsigned char *c
= NULL
;
3887 if ((clen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3888 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3889 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
3890 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
3891 if (fread(c
,clen
,1,fp
) == 0) goto err
;
3892 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
3894 return createObject(REDIS_STRING
,val
);
3901 static robj
*rdbGenericLoadStringObject(FILE*fp
, int encode
) {
3906 len
= rdbLoadLen(fp
,&isencoded
);
3909 case REDIS_RDB_ENC_INT8
:
3910 case REDIS_RDB_ENC_INT16
:
3911 case REDIS_RDB_ENC_INT32
:
3912 return rdbLoadIntegerObject(fp
,len
,encode
);
3913 case REDIS_RDB_ENC_LZF
:
3914 return rdbLoadLzfStringObject(fp
);
3916 redisPanic("Unknown RDB encoding type");
3920 if (len
== REDIS_RDB_LENERR
) return NULL
;
3921 val
= sdsnewlen(NULL
,len
);
3922 if (len
&& fread(val
,len
,1,fp
) == 0) {
3926 return createObject(REDIS_STRING
,val
);
3929 static robj
*rdbLoadStringObject(FILE *fp
) {
3930 return rdbGenericLoadStringObject(fp
,0);
3933 static robj
*rdbLoadEncodedStringObject(FILE *fp
) {
3934 return rdbGenericLoadStringObject(fp
,1);
3937 /* For information about double serialization check rdbSaveDoubleValue() */
3938 static int rdbLoadDoubleValue(FILE *fp
, double *val
) {
3942 if (fread(&len
,1,1,fp
) == 0) return -1;
3944 case 255: *val
= R_NegInf
; return 0;
3945 case 254: *val
= R_PosInf
; return 0;
3946 case 253: *val
= R_Nan
; return 0;
3948 if (fread(buf
,len
,1,fp
) == 0) return -1;
3950 sscanf(buf
, "%lg", val
);
3955 /* Load a Redis object of the specified type from the specified file.
3956 * On success a newly allocated object is returned, otherwise NULL. */
3957 static robj
*rdbLoadObject(int type
, FILE *fp
) {
3960 redisLog(REDIS_DEBUG
,"LOADING OBJECT %d (at %d)\n",type
,ftell(fp
));
3961 if (type
== REDIS_STRING
) {
3962 /* Read string value */
3963 if ((o
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
3964 o
= tryObjectEncoding(o
);
3965 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
3966 /* Read list/set value */
3969 if ((listlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3970 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
3971 /* It's faster to expand the dict to the right size asap in order
3972 * to avoid rehashing */
3973 if (type
== REDIS_SET
&& listlen
> DICT_HT_INITIAL_SIZE
)
3974 dictExpand(o
->ptr
,listlen
);
3975 /* Load every single element of the list/set */
3979 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
3980 ele
= tryObjectEncoding(ele
);
3981 if (type
== REDIS_LIST
) {
3982 listAddNodeTail((list
*)o
->ptr
,ele
);
3984 dictAdd((dict
*)o
->ptr
,ele
,NULL
);
3987 } else if (type
== REDIS_ZSET
) {
3988 /* Read list/set value */
3992 if ((zsetlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3993 o
= createZsetObject();
3995 /* Load every single element of the list/set */
3998 double *score
= zmalloc(sizeof(double));
4000 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
4001 ele
= tryObjectEncoding(ele
);
4002 if (rdbLoadDoubleValue(fp
,score
) == -1) return NULL
;
4003 dictAdd(zs
->dict
,ele
,score
);
4004 zslInsert(zs
->zsl
,*score
,ele
);
4005 incrRefCount(ele
); /* added to skiplist */
4007 } else if (type
== REDIS_HASH
) {
4010 if ((hashlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
4011 o
= createHashObject();
4012 /* Too many entries? Use an hash table. */
4013 if (hashlen
> server
.hash_max_zipmap_entries
)
4014 convertToRealHash(o
);
4015 /* Load every key/value, then set it into the zipmap or hash
4016 * table, as needed. */
4020 if ((key
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
4021 if ((val
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
4022 /* If we are using a zipmap and there are too big values
4023 * the object is converted to real hash table encoding. */
4024 if (o
->encoding
!= REDIS_ENCODING_HT
&&
4025 (sdslen(key
->ptr
) > server
.hash_max_zipmap_value
||
4026 sdslen(val
->ptr
) > server
.hash_max_zipmap_value
))
4028 convertToRealHash(o
);
4031 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
4032 unsigned char *zm
= o
->ptr
;
4034 zm
= zipmapSet(zm
,key
->ptr
,sdslen(key
->ptr
),
4035 val
->ptr
,sdslen(val
->ptr
),NULL
);
4040 key
= tryObjectEncoding(key
);
4041 val
= tryObjectEncoding(val
);
4042 dictAdd((dict
*)o
->ptr
,key
,val
);
4046 redisPanic("Unknown object type");
4051 static int rdbLoad(char *filename
) {
4054 int type
, retval
, rdbver
;
4055 int swap_all_values
= 0;
4056 dict
*d
= server
.db
[0].dict
;
4057 redisDb
*db
= server
.db
+0;
4059 time_t expiretime
, now
= time(NULL
);
4060 long long loadedkeys
= 0;
4062 fp
= fopen(filename
,"r");
4063 if (!fp
) return REDIS_ERR
;
4064 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
4066 if (memcmp(buf
,"REDIS",5) != 0) {
4068 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
4071 rdbver
= atoi(buf
+5);
4074 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
4082 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
4083 if (type
== REDIS_EXPIRETIME
) {
4084 if ((expiretime
= rdbLoadTime(fp
)) == -1) goto eoferr
;
4085 /* We read the time so we need to read the object type again */
4086 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
4088 if (type
== REDIS_EOF
) break;
4089 /* Handle SELECT DB opcode as a special case */
4090 if (type
== REDIS_SELECTDB
) {
4091 if ((dbid
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
)
4093 if (dbid
>= (unsigned)server
.dbnum
) {
4094 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
4097 db
= server
.db
+dbid
;
4102 if ((key
= rdbLoadStringObject(fp
)) == NULL
) goto eoferr
;
4104 if ((val
= rdbLoadObject(type
,fp
)) == NULL
) goto eoferr
;
4105 /* Check if the key already expired */
4106 if (expiretime
!= -1 && expiretime
< now
) {
4111 /* Add the new object in the hash table */
4112 retval
= dictAdd(d
,key
,val
);
4113 if (retval
== DICT_ERR
) {
4114 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key
->ptr
);
4118 /* Set the expire time if needed */
4119 if (expiretime
!= -1) setExpire(db
,key
,expiretime
);
4121 /* Handle swapping while loading big datasets when VM is on */
4123 /* If we detecter we are hopeless about fitting something in memory
4124 * we just swap every new key on disk. Directly...
4125 * Note that's important to check for this condition before resorting
4126 * to random sampling, otherwise we may try to swap already
4128 if (swap_all_values
) {
4129 dictEntry
*de
= dictFind(d
,key
);
4131 /* de may be NULL since the key already expired */
4133 key
= dictGetEntryKey(de
);
4134 val
= dictGetEntryVal(de
);
4136 if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
4137 dictGetEntryVal(de
) = NULL
;
4143 /* If we have still some hope of having some value fitting memory
4144 * then we try random sampling. */
4145 if (!swap_all_values
&& server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
4146 while (zmalloc_used_memory() > server
.vm_max_memory
) {
4147 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
4149 if (zmalloc_used_memory() > server
.vm_max_memory
)
4150 swap_all_values
= 1; /* We are already using too much mem */
4156 eoferr
: /* unexpected end of file is handled here with a fatal exit */
4157 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
4159 return REDIS_ERR
; /* Just to avoid warning */
4162 /*================================== Shutdown =============================== */
4163 static int prepareForShutdown() {
4164 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
4165 /* Kill the saving child if there is a background saving in progress.
4166 We want to avoid race conditions, for instance our saving child may
4167 overwrite the synchronous saving did by SHUTDOWN. */
4168 if (server
.bgsavechildpid
!= -1) {
4169 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
4170 kill(server
.bgsavechildpid
,SIGKILL
);
4171 rdbRemoveTempFile(server
.bgsavechildpid
);
4173 if (server
.appendonly
) {
4174 /* Append only file: fsync() the AOF and exit */
4175 fsync(server
.appendfd
);
4176 if (server
.vm_enabled
) unlink(server
.vm_swap_file
);
4178 /* Snapshotting. Perform a SYNC SAVE and exit */
4179 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
4180 if (server
.daemonize
)
4181 unlink(server
.pidfile
);
4182 redisLog(REDIS_WARNING
,"%zu bytes used at exit",zmalloc_used_memory());
4184 /* Ooops.. error saving! The best we can do is to continue
4185 * operating. Note that if there was a background saving process,
4186 * in the next cron() Redis will be notified that the background
4187 * saving aborted, handling special stuff like slaves pending for
4188 * synchronization... */
4189 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
4193 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
4197 /*================================== Commands =============================== */
4199 static void authCommand(redisClient
*c
) {
4200 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
4201 c
->authenticated
= 1;
4202 addReply(c
,shared
.ok
);
4204 c
->authenticated
= 0;
4205 addReplySds(c
,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
4209 static void pingCommand(redisClient
*c
) {
4210 addReply(c
,shared
.pong
);
4213 static void echoCommand(redisClient
*c
) {
4214 addReplyBulk(c
,c
->argv
[1]);
4217 /*=================================== Strings =============================== */
4219 static void setGenericCommand(redisClient
*c
, int nx
, robj
*key
, robj
*val
, robj
*expire
) {
4221 long seconds
= 0; /* initialized to avoid an harmness warning */
4224 if (getLongFromObjectOrReply(c
, expire
, &seconds
, NULL
) != REDIS_OK
)
4227 addReplySds(c
,sdsnew("-ERR invalid expire time in SETEX\r\n"));
4232 if (nx
) deleteIfVolatile(c
->db
,key
);
4233 retval
= dictAdd(c
->db
->dict
,key
,val
);
4234 if (retval
== DICT_ERR
) {
4236 /* If the key is about a swapped value, we want a new key object
4237 * to overwrite the old. So we delete the old key in the database.
4238 * This will also make sure that swap pages about the old object
4239 * will be marked as free. */
4240 if (server
.vm_enabled
&& deleteIfSwapped(c
->db
,key
))
4242 dictReplace(c
->db
->dict
,key
,val
);
4245 addReply(c
,shared
.czero
);
4253 removeExpire(c
->db
,key
);
4254 if (expire
) setExpire(c
->db
,key
,time(NULL
)+seconds
);
4255 addReply(c
, nx
? shared
.cone
: shared
.ok
);
4258 static void setCommand(redisClient
*c
) {
4259 setGenericCommand(c
,0,c
->argv
[1],c
->argv
[2],NULL
);
4262 static void setnxCommand(redisClient
*c
) {
4263 setGenericCommand(c
,1,c
->argv
[1],c
->argv
[2],NULL
);
4266 static void setexCommand(redisClient
*c
) {
4267 setGenericCommand(c
,0,c
->argv
[1],c
->argv
[3],c
->argv
[2]);
4270 static int getGenericCommand(redisClient
*c
) {
4273 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
)
4276 if (o
->type
!= REDIS_STRING
) {
4277 addReply(c
,shared
.wrongtypeerr
);
4285 static void getCommand(redisClient
*c
) {
4286 getGenericCommand(c
);
4289 static void getsetCommand(redisClient
*c
) {
4290 if (getGenericCommand(c
) == REDIS_ERR
) return;
4291 if (dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]) == DICT_ERR
) {
4292 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
4294 incrRefCount(c
->argv
[1]);
4296 incrRefCount(c
->argv
[2]);
4298 removeExpire(c
->db
,c
->argv
[1]);
4301 static void mgetCommand(redisClient
*c
) {
4304 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
4305 for (j
= 1; j
< c
->argc
; j
++) {
4306 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[j
]);
4308 addReply(c
,shared
.nullbulk
);
4310 if (o
->type
!= REDIS_STRING
) {
4311 addReply(c
,shared
.nullbulk
);
4319 static void msetGenericCommand(redisClient
*c
, int nx
) {
4320 int j
, busykeys
= 0;
4322 if ((c
->argc
% 2) == 0) {
4323 addReplySds(c
,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
4326 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
4327 * set nothing at all if at least one already key exists. */
4329 for (j
= 1; j
< c
->argc
; j
+= 2) {
4330 if (lookupKeyWrite(c
->db
,c
->argv
[j
]) != NULL
) {
4336 addReply(c
, shared
.czero
);
4340 for (j
= 1; j
< c
->argc
; j
+= 2) {
4343 c
->argv
[j
+1] = tryObjectEncoding(c
->argv
[j
+1]);
4344 retval
= dictAdd(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
4345 if (retval
== DICT_ERR
) {
4346 dictReplace(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
4347 incrRefCount(c
->argv
[j
+1]);
4349 incrRefCount(c
->argv
[j
]);
4350 incrRefCount(c
->argv
[j
+1]);
4352 removeExpire(c
->db
,c
->argv
[j
]);
4354 server
.dirty
+= (c
->argc
-1)/2;
4355 addReply(c
, nx
? shared
.cone
: shared
.ok
);
4358 static void msetCommand(redisClient
*c
) {
4359 msetGenericCommand(c
,0);
4362 static void msetnxCommand(redisClient
*c
) {
4363 msetGenericCommand(c
,1);
4366 static void incrDecrCommand(redisClient
*c
, long long incr
) {
4371 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4372 if (o
!= NULL
&& checkType(c
,o
,REDIS_STRING
)) return;
4373 if (getLongLongFromObjectOrReply(c
,o
,&value
,NULL
) != REDIS_OK
) return;
4376 o
= createStringObjectFromLongLong(value
);
4377 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],o
);
4378 if (retval
== DICT_ERR
) {
4379 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
4380 removeExpire(c
->db
,c
->argv
[1]);
4382 incrRefCount(c
->argv
[1]);
4385 addReply(c
,shared
.colon
);
4387 addReply(c
,shared
.crlf
);
4390 static void incrCommand(redisClient
*c
) {
4391 incrDecrCommand(c
,1);
4394 static void decrCommand(redisClient
*c
) {
4395 incrDecrCommand(c
,-1);
4398 static void incrbyCommand(redisClient
*c
) {
4401 if (getLongLongFromObjectOrReply(c
, c
->argv
[2], &incr
, NULL
) != REDIS_OK
) return;
4402 incrDecrCommand(c
,incr
);
4405 static void decrbyCommand(redisClient
*c
) {
4408 if (getLongLongFromObjectOrReply(c
, c
->argv
[2], &incr
, NULL
) != REDIS_OK
) return;
4409 incrDecrCommand(c
,-incr
);
4412 static void appendCommand(redisClient
*c
) {
4417 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4419 /* Create the key */
4420 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
4421 incrRefCount(c
->argv
[1]);
4422 incrRefCount(c
->argv
[2]);
4423 totlen
= stringObjectLen(c
->argv
[2]);
4427 de
= dictFind(c
->db
->dict
,c
->argv
[1]);
4430 o
= dictGetEntryVal(de
);
4431 if (o
->type
!= REDIS_STRING
) {
4432 addReply(c
,shared
.wrongtypeerr
);
4435 /* If the object is specially encoded or shared we have to make
4437 if (o
->refcount
!= 1 || o
->encoding
!= REDIS_ENCODING_RAW
) {
4438 robj
*decoded
= getDecodedObject(o
);
4440 o
= createStringObject(decoded
->ptr
, sdslen(decoded
->ptr
));
4441 decrRefCount(decoded
);
4442 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
4445 if (c
->argv
[2]->encoding
== REDIS_ENCODING_RAW
) {
4446 o
->ptr
= sdscatlen(o
->ptr
,
4447 c
->argv
[2]->ptr
, sdslen(c
->argv
[2]->ptr
));
4449 o
->ptr
= sdscatprintf(o
->ptr
, "%ld",
4450 (unsigned long) c
->argv
[2]->ptr
);
4452 totlen
= sdslen(o
->ptr
);
4455 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",(unsigned long)totlen
));
4458 static void substrCommand(redisClient
*c
) {
4460 long start
= atoi(c
->argv
[2]->ptr
);
4461 long end
= atoi(c
->argv
[3]->ptr
);
4462 size_t rangelen
, strlen
;
4465 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
4466 checkType(c
,o
,REDIS_STRING
)) return;
4468 o
= getDecodedObject(o
);
4469 strlen
= sdslen(o
->ptr
);
4471 /* convert negative indexes */
4472 if (start
< 0) start
= strlen
+start
;
4473 if (end
< 0) end
= strlen
+end
;
4474 if (start
< 0) start
= 0;
4475 if (end
< 0) end
= 0;
4477 /* indexes sanity checks */
4478 if (start
> end
|| (size_t)start
>= strlen
) {
4479 /* Out of range start or start > end result in null reply */
4480 addReply(c
,shared
.nullbulk
);
4484 if ((size_t)end
>= strlen
) end
= strlen
-1;
4485 rangelen
= (end
-start
)+1;
4487 /* Return the result */
4488 addReplySds(c
,sdscatprintf(sdsempty(),"$%zu\r\n",rangelen
));
4489 range
= sdsnewlen((char*)o
->ptr
+start
,rangelen
);
4490 addReplySds(c
,range
);
4491 addReply(c
,shared
.crlf
);
4495 /* ========================= Type agnostic commands ========================= */
4497 static void delCommand(redisClient
*c
) {
4500 for (j
= 1; j
< c
->argc
; j
++) {
4501 if (deleteKey(c
->db
,c
->argv
[j
])) {
4506 addReplyLongLong(c
,deleted
);
4509 static void existsCommand(redisClient
*c
) {
4510 expireIfNeeded(c
->db
,c
->argv
[1]);
4511 if (dictFind(c
->db
->dict
,c
->argv
[1])) {
4512 addReply(c
, shared
.cone
);
4514 addReply(c
, shared
.czero
);
4518 static void selectCommand(redisClient
*c
) {
4519 int id
= atoi(c
->argv
[1]->ptr
);
4521 if (selectDb(c
,id
) == REDIS_ERR
) {
4522 addReplySds(c
,sdsnew("-ERR invalid DB index\r\n"));
4524 addReply(c
,shared
.ok
);
4528 static void randomkeyCommand(redisClient
*c
) {
4533 de
= dictGetRandomKey(c
->db
->dict
);
4534 if (!de
|| expireIfNeeded(c
->db
,dictGetEntryKey(de
)) == 0) break;
4538 addReply(c
,shared
.nullbulk
);
4542 key
= dictGetEntryKey(de
);
4543 if (server
.vm_enabled
) {
4544 key
= dupStringObject(key
);
4545 addReplyBulk(c
,key
);
4548 addReplyBulk(c
,key
);
4552 static void keysCommand(redisClient
*c
) {
4555 sds pattern
= c
->argv
[1]->ptr
;
4556 int plen
= sdslen(pattern
);
4557 unsigned long numkeys
= 0;
4558 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
4560 di
= dictGetIterator(c
->db
->dict
);
4562 decrRefCount(lenobj
);
4563 while((de
= dictNext(di
)) != NULL
) {
4564 robj
*keyobj
= dictGetEntryKey(de
);
4566 sds key
= keyobj
->ptr
;
4567 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
4568 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
4569 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
4570 addReplyBulk(c
,keyobj
);
4575 dictReleaseIterator(di
);
4576 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",numkeys
);
4579 static void dbsizeCommand(redisClient
*c
) {
4581 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c
->db
->dict
)));
4584 static void lastsaveCommand(redisClient
*c
) {
4586 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
4589 static void typeCommand(redisClient
*c
) {
4593 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4598 case REDIS_STRING
: type
= "+string"; break;
4599 case REDIS_LIST
: type
= "+list"; break;
4600 case REDIS_SET
: type
= "+set"; break;
4601 case REDIS_ZSET
: type
= "+zset"; break;
4602 case REDIS_HASH
: type
= "+hash"; break;
4603 default: type
= "+unknown"; break;
4606 addReplySds(c
,sdsnew(type
));
4607 addReply(c
,shared
.crlf
);
4610 static void saveCommand(redisClient
*c
) {
4611 if (server
.bgsavechildpid
!= -1) {
4612 addReplySds(c
,sdsnew("-ERR background save in progress\r\n"));
4615 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
4616 addReply(c
,shared
.ok
);
4618 addReply(c
,shared
.err
);
4622 static void bgsaveCommand(redisClient
*c
) {
4623 if (server
.bgsavechildpid
!= -1) {
4624 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
4627 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
4628 char *status
= "+Background saving started\r\n";
4629 addReplySds(c
,sdsnew(status
));
4631 addReply(c
,shared
.err
);
4635 static void shutdownCommand(redisClient
*c
) {
4636 if (prepareForShutdown() == REDIS_OK
)
4638 addReplySds(c
, sdsnew("-ERR Errors trying to SHUTDOWN. Check logs.\r\n"));
4641 static void renameGenericCommand(redisClient
*c
, int nx
) {
4644 /* To use the same key as src and dst is probably an error */
4645 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
4646 addReply(c
,shared
.sameobjecterr
);
4650 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
)
4654 deleteIfVolatile(c
->db
,c
->argv
[2]);
4655 if (dictAdd(c
->db
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
4658 addReply(c
,shared
.czero
);
4661 dictReplace(c
->db
->dict
,c
->argv
[2],o
);
4663 incrRefCount(c
->argv
[2]);
4665 deleteKey(c
->db
,c
->argv
[1]);
4667 addReply(c
,nx
? shared
.cone
: shared
.ok
);
4670 static void renameCommand(redisClient
*c
) {
4671 renameGenericCommand(c
,0);
4674 static void renamenxCommand(redisClient
*c
) {
4675 renameGenericCommand(c
,1);
4678 static void moveCommand(redisClient
*c
) {
4683 /* Obtain source and target DB pointers */
4686 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
4687 addReply(c
,shared
.outofrangeerr
);
4691 selectDb(c
,srcid
); /* Back to the source DB */
4693 /* If the user is moving using as target the same
4694 * DB as the source DB it is probably an error. */
4696 addReply(c
,shared
.sameobjecterr
);
4700 /* Check if the element exists and get a reference */
4701 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4703 addReply(c
,shared
.czero
);
4707 /* Try to add the element to the target DB */
4708 deleteIfVolatile(dst
,c
->argv
[1]);
4709 if (dictAdd(dst
->dict
,c
->argv
[1],o
) == DICT_ERR
) {
4710 addReply(c
,shared
.czero
);
4713 incrRefCount(c
->argv
[1]);
4716 /* OK! key moved, free the entry in the source DB */
4717 deleteKey(src
,c
->argv
[1]);
4719 addReply(c
,shared
.cone
);
4722 /* =================================== Lists ================================ */
4723 static void pushGenericCommand(redisClient
*c
, int where
) {
4727 lobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4729 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
4730 addReply(c
,shared
.cone
);
4733 lobj
= createListObject();
4735 if (where
== REDIS_HEAD
) {
4736 listAddNodeHead(list
,c
->argv
[2]);
4738 listAddNodeTail(list
,c
->argv
[2]);
4740 dictAdd(c
->db
->dict
,c
->argv
[1],lobj
);
4741 incrRefCount(c
->argv
[1]);
4742 incrRefCount(c
->argv
[2]);
4744 if (lobj
->type
!= REDIS_LIST
) {
4745 addReply(c
,shared
.wrongtypeerr
);
4748 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
4749 addReply(c
,shared
.cone
);
4753 if (where
== REDIS_HEAD
) {
4754 listAddNodeHead(list
,c
->argv
[2]);
4756 listAddNodeTail(list
,c
->argv
[2]);
4758 incrRefCount(c
->argv
[2]);
4761 addReplyLongLong(c
,listLength(list
));
4764 static void lpushCommand(redisClient
*c
) {
4765 pushGenericCommand(c
,REDIS_HEAD
);
4768 static void rpushCommand(redisClient
*c
) {
4769 pushGenericCommand(c
,REDIS_TAIL
);
4772 static void llenCommand(redisClient
*c
) {
4776 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
4777 checkType(c
,o
,REDIS_LIST
)) return;
4780 addReplyUlong(c
,listLength(l
));
4783 static void lindexCommand(redisClient
*c
) {
4785 int index
= atoi(c
->argv
[2]->ptr
);
4789 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
4790 checkType(c
,o
,REDIS_LIST
)) return;
4793 ln
= listIndex(list
, index
);
4795 addReply(c
,shared
.nullbulk
);
4797 robj
*ele
= listNodeValue(ln
);
4798 addReplyBulk(c
,ele
);
4802 static void lsetCommand(redisClient
*c
) {
4804 int index
= atoi(c
->argv
[2]->ptr
);
4808 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
||
4809 checkType(c
,o
,REDIS_LIST
)) return;
4812 ln
= listIndex(list
, index
);
4814 addReply(c
,shared
.outofrangeerr
);
4816 robj
*ele
= listNodeValue(ln
);
4819 listNodeValue(ln
) = c
->argv
[3];
4820 incrRefCount(c
->argv
[3]);
4821 addReply(c
,shared
.ok
);
4826 static void popGenericCommand(redisClient
*c
, int where
) {
4831 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
4832 checkType(c
,o
,REDIS_LIST
)) return;
4835 if (where
== REDIS_HEAD
)
4836 ln
= listFirst(list
);
4838 ln
= listLast(list
);
4841 addReply(c
,shared
.nullbulk
);
4843 robj
*ele
= listNodeValue(ln
);
4844 addReplyBulk(c
,ele
);
4845 listDelNode(list
,ln
);
4846 if (listLength(list
) == 0) deleteKey(c
->db
,c
->argv
[1]);
4851 static void lpopCommand(redisClient
*c
) {
4852 popGenericCommand(c
,REDIS_HEAD
);
4855 static void rpopCommand(redisClient
*c
) {
4856 popGenericCommand(c
,REDIS_TAIL
);
4859 static void lrangeCommand(redisClient
*c
) {
4861 int start
= atoi(c
->argv
[2]->ptr
);
4862 int end
= atoi(c
->argv
[3]->ptr
);
4869 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.emptymultibulk
)) == NULL
4870 || checkType(c
,o
,REDIS_LIST
)) return;
4872 llen
= listLength(list
);
4874 /* convert negative indexes */
4875 if (start
< 0) start
= llen
+start
;
4876 if (end
< 0) end
= llen
+end
;
4877 if (start
< 0) start
= 0;
4878 if (end
< 0) end
= 0;
4880 /* indexes sanity checks */
4881 if (start
> end
|| start
>= llen
) {
4882 /* Out of range start or start > end result in empty list */
4883 addReply(c
,shared
.emptymultibulk
);
4886 if (end
>= llen
) end
= llen
-1;
4887 rangelen
= (end
-start
)+1;
4889 /* Return the result in form of a multi-bulk reply */
4890 ln
= listIndex(list
, start
);
4891 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
4892 for (j
= 0; j
< rangelen
; j
++) {
4893 ele
= listNodeValue(ln
);
4894 addReplyBulk(c
,ele
);
4899 static void ltrimCommand(redisClient
*c
) {
4901 int start
= atoi(c
->argv
[2]->ptr
);
4902 int end
= atoi(c
->argv
[3]->ptr
);
4904 int j
, ltrim
, rtrim
;
4908 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.ok
)) == NULL
||
4909 checkType(c
,o
,REDIS_LIST
)) return;
4911 llen
= listLength(list
);
4913 /* convert negative indexes */
4914 if (start
< 0) start
= llen
+start
;
4915 if (end
< 0) end
= llen
+end
;
4916 if (start
< 0) start
= 0;
4917 if (end
< 0) end
= 0;
4919 /* indexes sanity checks */
4920 if (start
> end
|| start
>= llen
) {
4921 /* Out of range start or start > end result in empty list */
4925 if (end
>= llen
) end
= llen
-1;
4930 /* Remove list elements to perform the trim */
4931 for (j
= 0; j
< ltrim
; j
++) {
4932 ln
= listFirst(list
);
4933 listDelNode(list
,ln
);
4935 for (j
= 0; j
< rtrim
; j
++) {
4936 ln
= listLast(list
);
4937 listDelNode(list
,ln
);
4939 if (listLength(list
) == 0) deleteKey(c
->db
,c
->argv
[1]);
4941 addReply(c
,shared
.ok
);
4944 static void lremCommand(redisClient
*c
) {
4947 listNode
*ln
, *next
;
4948 int toremove
= atoi(c
->argv
[2]->ptr
);
4952 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
4953 checkType(c
,o
,REDIS_LIST
)) return;
4957 toremove
= -toremove
;
4960 ln
= fromtail
? list
->tail
: list
->head
;
4962 robj
*ele
= listNodeValue(ln
);
4964 next
= fromtail
? ln
->prev
: ln
->next
;
4965 if (equalStringObjects(ele
,c
->argv
[3])) {
4966 listDelNode(list
,ln
);
4969 if (toremove
&& removed
== toremove
) break;
4973 if (listLength(list
) == 0) deleteKey(c
->db
,c
->argv
[1]);
4974 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
4977 /* This is the semantic of this command:
4978 * RPOPLPUSH srclist dstlist:
4979 * IF LLEN(srclist) > 0
4980 * element = RPOP srclist
4981 * LPUSH dstlist element
4988 * The idea is to be able to get an element from a list in a reliable way
4989 * since the element is not just returned but pushed against another list
4990 * as well. This command was originally proposed by Ezra Zygmuntowicz.
4992 static void rpoplpushcommand(redisClient
*c
) {
4997 if ((sobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
4998 checkType(c
,sobj
,REDIS_LIST
)) return;
4999 srclist
= sobj
->ptr
;
5000 ln
= listLast(srclist
);
5003 addReply(c
,shared
.nullbulk
);
5005 robj
*dobj
= lookupKeyWrite(c
->db
,c
->argv
[2]);
5006 robj
*ele
= listNodeValue(ln
);
5009 if (dobj
&& dobj
->type
!= REDIS_LIST
) {
5010 addReply(c
,shared
.wrongtypeerr
);
5014 /* Add the element to the target list (unless it's directly
5015 * passed to some BLPOP-ing client */
5016 if (!handleClientsWaitingListPush(c
,c
->argv
[2],ele
)) {
5018 /* Create the list if the key does not exist */
5019 dobj
= createListObject();
5020 dictAdd(c
->db
->dict
,c
->argv
[2],dobj
);
5021 incrRefCount(c
->argv
[2]);
5023 dstlist
= dobj
->ptr
;
5024 listAddNodeHead(dstlist
,ele
);
5028 /* Send the element to the client as reply as well */
5029 addReplyBulk(c
,ele
);
5031 /* Finally remove the element from the source list */
5032 listDelNode(srclist
,ln
);
5033 if (listLength(srclist
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5038 /* ==================================== Sets ================================ */
5040 static void saddCommand(redisClient
*c
) {
5043 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
5045 set
= createSetObject();
5046 dictAdd(c
->db
->dict
,c
->argv
[1],set
);
5047 incrRefCount(c
->argv
[1]);
5049 if (set
->type
!= REDIS_SET
) {
5050 addReply(c
,shared
.wrongtypeerr
);
5054 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
5055 incrRefCount(c
->argv
[2]);
5057 addReply(c
,shared
.cone
);
5059 addReply(c
,shared
.czero
);
5063 static void sremCommand(redisClient
*c
) {
5066 if ((set
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5067 checkType(c
,set
,REDIS_SET
)) return;
5069 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
5071 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
5072 if (dictSize((dict
*)set
->ptr
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5073 addReply(c
,shared
.cone
);
5075 addReply(c
,shared
.czero
);
5079 static void smoveCommand(redisClient
*c
) {
5080 robj
*srcset
, *dstset
;
5082 srcset
= lookupKeyWrite(c
->db
,c
->argv
[1]);
5083 dstset
= lookupKeyWrite(c
->db
,c
->argv
[2]);
5085 /* If the source key does not exist return 0, if it's of the wrong type
5087 if (srcset
== NULL
|| srcset
->type
!= REDIS_SET
) {
5088 addReply(c
, srcset
? shared
.wrongtypeerr
: shared
.czero
);
5091 /* Error if the destination key is not a set as well */
5092 if (dstset
&& dstset
->type
!= REDIS_SET
) {
5093 addReply(c
,shared
.wrongtypeerr
);
5096 /* Remove the element from the source set */
5097 if (dictDelete(srcset
->ptr
,c
->argv
[3]) == DICT_ERR
) {
5098 /* Key not found in the src set! return zero */
5099 addReply(c
,shared
.czero
);
5102 if (dictSize((dict
*)srcset
->ptr
) == 0 && srcset
!= dstset
)
5103 deleteKey(c
->db
,c
->argv
[1]);
5105 /* Add the element to the destination set */
5107 dstset
= createSetObject();
5108 dictAdd(c
->db
->dict
,c
->argv
[2],dstset
);
5109 incrRefCount(c
->argv
[2]);
5111 if (dictAdd(dstset
->ptr
,c
->argv
[3],NULL
) == DICT_OK
)
5112 incrRefCount(c
->argv
[3]);
5113 addReply(c
,shared
.cone
);
5116 static void sismemberCommand(redisClient
*c
) {
5119 if ((set
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5120 checkType(c
,set
,REDIS_SET
)) return;
5122 if (dictFind(set
->ptr
,c
->argv
[2]))
5123 addReply(c
,shared
.cone
);
5125 addReply(c
,shared
.czero
);
5128 static void scardCommand(redisClient
*c
) {
5132 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5133 checkType(c
,o
,REDIS_SET
)) return;
5136 addReplyUlong(c
,dictSize(s
));
5139 static void spopCommand(redisClient
*c
) {
5143 if ((set
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
5144 checkType(c
,set
,REDIS_SET
)) return;
5146 de
= dictGetRandomKey(set
->ptr
);
5148 addReply(c
,shared
.nullbulk
);
5150 robj
*ele
= dictGetEntryKey(de
);
5152 addReplyBulk(c
,ele
);
5153 dictDelete(set
->ptr
,ele
);
5154 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
5155 if (dictSize((dict
*)set
->ptr
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5160 static void srandmemberCommand(redisClient
*c
) {
5164 if ((set
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
5165 checkType(c
,set
,REDIS_SET
)) return;
5167 de
= dictGetRandomKey(set
->ptr
);
5169 addReply(c
,shared
.nullbulk
);
5171 robj
*ele
= dictGetEntryKey(de
);
5173 addReplyBulk(c
,ele
);
5177 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
5178 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
5180 return dictSize(*d1
)-dictSize(*d2
);
5183 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, unsigned long setsnum
, robj
*dstkey
) {
5184 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
5187 robj
*lenobj
= NULL
, *dstset
= NULL
;
5188 unsigned long j
, cardinality
= 0;
5190 for (j
= 0; j
< setsnum
; j
++) {
5194 lookupKeyWrite(c
->db
,setskeys
[j
]) :
5195 lookupKeyRead(c
->db
,setskeys
[j
]);
5199 if (deleteKey(c
->db
,dstkey
))
5201 addReply(c
,shared
.czero
);
5203 addReply(c
,shared
.emptymultibulk
);
5207 if (setobj
->type
!= REDIS_SET
) {
5209 addReply(c
,shared
.wrongtypeerr
);
5212 dv
[j
] = setobj
->ptr
;
5214 /* Sort sets from the smallest to largest, this will improve our
5215 * algorithm's performace */
5216 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
5218 /* The first thing we should output is the total number of elements...
5219 * since this is a multi-bulk write, but at this stage we don't know
5220 * the intersection set size, so we use a trick, append an empty object
5221 * to the output list and save the pointer to later modify it with the
5224 lenobj
= createObject(REDIS_STRING
,NULL
);
5226 decrRefCount(lenobj
);
5228 /* If we have a target key where to store the resulting set
5229 * create this key with an empty set inside */
5230 dstset
= createSetObject();
5233 /* Iterate all the elements of the first (smallest) set, and test
5234 * the element against all the other sets, if at least one set does
5235 * not include the element it is discarded */
5236 di
= dictGetIterator(dv
[0]);
5238 while((de
= dictNext(di
)) != NULL
) {
5241 for (j
= 1; j
< setsnum
; j
++)
5242 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
5244 continue; /* at least one set does not contain the member */
5245 ele
= dictGetEntryKey(de
);
5247 addReplyBulk(c
,ele
);
5250 dictAdd(dstset
->ptr
,ele
,NULL
);
5254 dictReleaseIterator(di
);
5257 /* Store the resulting set into the target, if the intersection
5258 * is not an empty set. */
5259 deleteKey(c
->db
,dstkey
);
5260 if (dictSize((dict
*)dstset
->ptr
) > 0) {
5261 dictAdd(c
->db
->dict
,dstkey
,dstset
);
5262 incrRefCount(dstkey
);
5263 addReplyLongLong(c
,dictSize((dict
*)dstset
->ptr
));
5265 decrRefCount(dstset
);
5266 addReply(c
,shared
.czero
);
5270 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",cardinality
);
5275 static void sinterCommand(redisClient
*c
) {
5276 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
5279 static void sinterstoreCommand(redisClient
*c
) {
5280 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
5283 #define REDIS_OP_UNION 0
5284 #define REDIS_OP_DIFF 1
5285 #define REDIS_OP_INTER 2
5287 static void sunionDiffGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
, int op
) {
5288 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
5291 robj
*dstset
= NULL
;
5292 int j
, cardinality
= 0;
5294 for (j
= 0; j
< setsnum
; j
++) {
5298 lookupKeyWrite(c
->db
,setskeys
[j
]) :
5299 lookupKeyRead(c
->db
,setskeys
[j
]);
5304 if (setobj
->type
!= REDIS_SET
) {
5306 addReply(c
,shared
.wrongtypeerr
);
5309 dv
[j
] = setobj
->ptr
;
5312 /* We need a temp set object to store our union. If the dstkey
5313 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
5314 * this set object will be the resulting object to set into the target key*/
5315 dstset
= createSetObject();
5317 /* Iterate all the elements of all the sets, add every element a single
5318 * time to the result set */
5319 for (j
= 0; j
< setsnum
; j
++) {
5320 if (op
== REDIS_OP_DIFF
&& j
== 0 && !dv
[j
]) break; /* result set is empty */
5321 if (!dv
[j
]) continue; /* non existing keys are like empty sets */
5323 di
= dictGetIterator(dv
[j
]);
5325 while((de
= dictNext(di
)) != NULL
) {
5328 /* dictAdd will not add the same element multiple times */
5329 ele
= dictGetEntryKey(de
);
5330 if (op
== REDIS_OP_UNION
|| j
== 0) {
5331 if (dictAdd(dstset
->ptr
,ele
,NULL
) == DICT_OK
) {
5335 } else if (op
== REDIS_OP_DIFF
) {
5336 if (dictDelete(dstset
->ptr
,ele
) == DICT_OK
) {
5341 dictReleaseIterator(di
);
5343 /* result set is empty? Exit asap. */
5344 if (op
== REDIS_OP_DIFF
&& cardinality
== 0) break;
5347 /* Output the content of the resulting set, if not in STORE mode */
5349 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",cardinality
));
5350 di
= dictGetIterator(dstset
->ptr
);
5351 while((de
= dictNext(di
)) != NULL
) {
5354 ele
= dictGetEntryKey(de
);
5355 addReplyBulk(c
,ele
);
5357 dictReleaseIterator(di
);
5358 decrRefCount(dstset
);
5360 /* If we have a target key where to store the resulting set
5361 * create this key with the result set inside */
5362 deleteKey(c
->db
,dstkey
);
5363 if (dictSize((dict
*)dstset
->ptr
) > 0) {
5364 dictAdd(c
->db
->dict
,dstkey
,dstset
);
5365 incrRefCount(dstkey
);
5366 addReplyLongLong(c
,dictSize((dict
*)dstset
->ptr
));
5368 decrRefCount(dstset
);
5369 addReply(c
,shared
.czero
);
5376 static void sunionCommand(redisClient
*c
) {
5377 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_UNION
);
5380 static void sunionstoreCommand(redisClient
*c
) {
5381 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_UNION
);
5384 static void sdiffCommand(redisClient
*c
) {
5385 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_DIFF
);
5388 static void sdiffstoreCommand(redisClient
*c
) {
5389 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_DIFF
);
5392 /* ==================================== ZSets =============================== */
5394 /* ZSETs are ordered sets using two data structures to hold the same elements
5395 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
5398 * The elements are added to an hash table mapping Redis objects to scores.
5399 * At the same time the elements are added to a skip list mapping scores
5400 * to Redis objects (so objects are sorted by scores in this "view"). */
5402 /* This skiplist implementation is almost a C translation of the original
5403 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
5404 * Alternative to Balanced Trees", modified in three ways:
5405 * a) this implementation allows for repeated values.
5406 * b) the comparison is not just by key (our 'score') but by satellite data.
5407 * c) there is a back pointer, so it's a doubly linked list with the back
5408 * pointers being only at "level 1". This allows to traverse the list
5409 * from tail to head, useful for ZREVRANGE. */
5411 static zskiplistNode
*zslCreateNode(int level
, double score
, robj
*obj
) {
5412 zskiplistNode
*zn
= zmalloc(sizeof(*zn
));
5414 zn
->forward
= zmalloc(sizeof(zskiplistNode
*) * level
);
5416 zn
->span
= zmalloc(sizeof(unsigned int) * (level
- 1));
5422 static zskiplist
*zslCreate(void) {
5426 zsl
= zmalloc(sizeof(*zsl
));
5429 zsl
->header
= zslCreateNode(ZSKIPLIST_MAXLEVEL
,0,NULL
);
5430 for (j
= 0; j
< ZSKIPLIST_MAXLEVEL
; j
++) {
5431 zsl
->header
->forward
[j
] = NULL
;
5433 /* span has space for ZSKIPLIST_MAXLEVEL-1 elements */
5434 if (j
< ZSKIPLIST_MAXLEVEL
-1)
5435 zsl
->header
->span
[j
] = 0;
5437 zsl
->header
->backward
= NULL
;
5442 static void zslFreeNode(zskiplistNode
*node
) {
5443 decrRefCount(node
->obj
);
5444 zfree(node
->forward
);
5449 static void zslFree(zskiplist
*zsl
) {
5450 zskiplistNode
*node
= zsl
->header
->forward
[0], *next
;
5452 zfree(zsl
->header
->forward
);
5453 zfree(zsl
->header
->span
);
5456 next
= node
->forward
[0];
5463 static int zslRandomLevel(void) {
5465 while ((random()&0xFFFF) < (ZSKIPLIST_P
* 0xFFFF))
5467 return (level
<ZSKIPLIST_MAXLEVEL
) ? level
: ZSKIPLIST_MAXLEVEL
;
5470 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
) {
5471 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5472 unsigned int rank
[ZSKIPLIST_MAXLEVEL
];
5476 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5477 /* store rank that is crossed to reach the insert position */
5478 rank
[i
] = i
== (zsl
->level
-1) ? 0 : rank
[i
+1];
5480 while (x
->forward
[i
] &&
5481 (x
->forward
[i
]->score
< score
||
5482 (x
->forward
[i
]->score
== score
&&
5483 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0))) {
5484 rank
[i
] += i
> 0 ? x
->span
[i
-1] : 1;
5489 /* we assume the key is not already inside, since we allow duplicated
5490 * scores, and the re-insertion of score and redis object should never
5491 * happpen since the caller of zslInsert() should test in the hash table
5492 * if the element is already inside or not. */
5493 level
= zslRandomLevel();
5494 if (level
> zsl
->level
) {
5495 for (i
= zsl
->level
; i
< level
; i
++) {
5497 update
[i
] = zsl
->header
;
5498 update
[i
]->span
[i
-1] = zsl
->length
;
5502 x
= zslCreateNode(level
,score
,obj
);
5503 for (i
= 0; i
< level
; i
++) {
5504 x
->forward
[i
] = update
[i
]->forward
[i
];
5505 update
[i
]->forward
[i
] = x
;
5507 /* update span covered by update[i] as x is inserted here */
5509 x
->span
[i
-1] = update
[i
]->span
[i
-1] - (rank
[0] - rank
[i
]);
5510 update
[i
]->span
[i
-1] = (rank
[0] - rank
[i
]) + 1;
5514 /* increment span for untouched levels */
5515 for (i
= level
; i
< zsl
->level
; i
++) {
5516 update
[i
]->span
[i
-1]++;
5519 x
->backward
= (update
[0] == zsl
->header
) ? NULL
: update
[0];
5521 x
->forward
[0]->backward
= x
;
5527 /* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
5528 void zslDeleteNode(zskiplist
*zsl
, zskiplistNode
*x
, zskiplistNode
**update
) {
5530 for (i
= 0; i
< zsl
->level
; i
++) {
5531 if (update
[i
]->forward
[i
] == x
) {
5533 update
[i
]->span
[i
-1] += x
->span
[i
-1] - 1;
5535 update
[i
]->forward
[i
] = x
->forward
[i
];
5537 /* invariant: i > 0, because update[0]->forward[0]
5538 * is always equal to x */
5539 update
[i
]->span
[i
-1] -= 1;
5542 if (x
->forward
[0]) {
5543 x
->forward
[0]->backward
= x
->backward
;
5545 zsl
->tail
= x
->backward
;
5547 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
5552 /* Delete an element with matching score/object from the skiplist. */
5553 static int zslDelete(zskiplist
*zsl
, double score
, robj
*obj
) {
5554 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5558 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5559 while (x
->forward
[i
] &&
5560 (x
->forward
[i
]->score
< score
||
5561 (x
->forward
[i
]->score
== score
&&
5562 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
5566 /* We may have multiple elements with the same score, what we need
5567 * is to find the element with both the right score and object. */
5569 if (x
&& score
== x
->score
&& equalStringObjects(x
->obj
,obj
)) {
5570 zslDeleteNode(zsl
, x
, update
);
5574 return 0; /* not found */
5576 return 0; /* not found */
5579 /* Delete all the elements with score between min and max from the skiplist.
5580 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
5581 * Note that this function takes the reference to the hash table view of the
5582 * sorted set, in order to remove the elements from the hash table too. */
5583 static unsigned long zslDeleteRangeByScore(zskiplist
*zsl
, double min
, double max
, dict
*dict
) {
5584 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5585 unsigned long removed
= 0;
5589 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5590 while (x
->forward
[i
] && x
->forward
[i
]->score
< min
)
5594 /* We may have multiple elements with the same score, what we need
5595 * is to find the element with both the right score and object. */
5597 while (x
&& x
->score
<= max
) {
5598 zskiplistNode
*next
= x
->forward
[0];
5599 zslDeleteNode(zsl
, x
, update
);
5600 dictDelete(dict
,x
->obj
);
5605 return removed
; /* not found */
5608 /* Delete all the elements with rank between start and end from the skiplist.
5609 * Start and end are inclusive. Note that start and end need to be 1-based */
5610 static unsigned long zslDeleteRangeByRank(zskiplist
*zsl
, unsigned int start
, unsigned int end
, dict
*dict
) {
5611 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5612 unsigned long traversed
= 0, removed
= 0;
5616 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5617 while (x
->forward
[i
] && (traversed
+ (i
> 0 ? x
->span
[i
-1] : 1)) < start
) {
5618 traversed
+= i
> 0 ? x
->span
[i
-1] : 1;
5626 while (x
&& traversed
<= end
) {
5627 zskiplistNode
*next
= x
->forward
[0];
5628 zslDeleteNode(zsl
, x
, update
);
5629 dictDelete(dict
,x
->obj
);
5638 /* Find the first node having a score equal or greater than the specified one.
5639 * Returns NULL if there is no match. */
5640 static zskiplistNode
*zslFirstWithScore(zskiplist
*zsl
, double score
) {
5645 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5646 while (x
->forward
[i
] && x
->forward
[i
]->score
< score
)
5649 /* We may have multiple elements with the same score, what we need
5650 * is to find the element with both the right score and object. */
5651 return x
->forward
[0];
5654 /* Find the rank for an element by both score and key.
5655 * Returns 0 when the element cannot be found, rank otherwise.
5656 * Note that the rank is 1-based due to the span of zsl->header to the
5658 static unsigned long zslGetRank(zskiplist
*zsl
, double score
, robj
*o
) {
5660 unsigned long rank
= 0;
5664 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5665 while (x
->forward
[i
] &&
5666 (x
->forward
[i
]->score
< score
||
5667 (x
->forward
[i
]->score
== score
&&
5668 compareStringObjects(x
->forward
[i
]->obj
,o
) <= 0))) {
5669 rank
+= i
> 0 ? x
->span
[i
-1] : 1;
5673 /* x might be equal to zsl->header, so test if obj is non-NULL */
5674 if (x
->obj
&& equalStringObjects(x
->obj
,o
)) {
5681 /* Finds an element by its rank. The rank argument needs to be 1-based. */
5682 zskiplistNode
* zslGetElementByRank(zskiplist
*zsl
, unsigned long rank
) {
5684 unsigned long traversed
= 0;
5688 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5689 while (x
->forward
[i
] && (traversed
+ (i
>0 ? x
->span
[i
-1] : 1)) <= rank
)
5691 traversed
+= i
> 0 ? x
->span
[i
-1] : 1;
5694 if (traversed
== rank
) {
5701 /* The actual Z-commands implementations */
5703 /* This generic command implements both ZADD and ZINCRBY.
5704 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
5705 * the increment if the operation is a ZINCRBY (doincrement == 1). */
5706 static void zaddGenericCommand(redisClient
*c
, robj
*key
, robj
*ele
, double scoreval
, int doincrement
) {
5711 zsetobj
= lookupKeyWrite(c
->db
,key
);
5712 if (zsetobj
== NULL
) {
5713 zsetobj
= createZsetObject();
5714 dictAdd(c
->db
->dict
,key
,zsetobj
);
5717 if (zsetobj
->type
!= REDIS_ZSET
) {
5718 addReply(c
,shared
.wrongtypeerr
);
5724 /* Ok now since we implement both ZADD and ZINCRBY here the code
5725 * needs to handle the two different conditions. It's all about setting
5726 * '*score', that is, the new score to set, to the right value. */
5727 score
= zmalloc(sizeof(double));
5731 /* Read the old score. If the element was not present starts from 0 */
5732 de
= dictFind(zs
->dict
,ele
);
5734 double *oldscore
= dictGetEntryVal(de
);
5735 *score
= *oldscore
+ scoreval
;
5743 /* What follows is a simple remove and re-insert operation that is common
5744 * to both ZADD and ZINCRBY... */
5745 if (dictAdd(zs
->dict
,ele
,score
) == DICT_OK
) {
5746 /* case 1: New element */
5747 incrRefCount(ele
); /* added to hash */
5748 zslInsert(zs
->zsl
,*score
,ele
);
5749 incrRefCount(ele
); /* added to skiplist */
5752 addReplyDouble(c
,*score
);
5754 addReply(c
,shared
.cone
);
5759 /* case 2: Score update operation */
5760 de
= dictFind(zs
->dict
,ele
);
5761 redisAssert(de
!= NULL
);
5762 oldscore
= dictGetEntryVal(de
);
5763 if (*score
!= *oldscore
) {
5766 /* Remove and insert the element in the skip list with new score */
5767 deleted
= zslDelete(zs
->zsl
,*oldscore
,ele
);
5768 redisAssert(deleted
!= 0);
5769 zslInsert(zs
->zsl
,*score
,ele
);
5771 /* Update the score in the hash table */
5772 dictReplace(zs
->dict
,ele
,score
);
5778 addReplyDouble(c
,*score
);
5780 addReply(c
,shared
.czero
);
5784 static void zaddCommand(redisClient
*c
) {
5787 if (getDoubleFromObjectOrReply(c
, c
->argv
[2], &scoreval
, NULL
) != REDIS_OK
) return;
5788 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,0);
5791 static void zincrbyCommand(redisClient
*c
) {
5794 if (getDoubleFromObjectOrReply(c
, c
->argv
[2], &scoreval
, NULL
) != REDIS_OK
) return;
5795 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,1);
5798 static void zremCommand(redisClient
*c
) {
5805 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5806 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
5809 de
= dictFind(zs
->dict
,c
->argv
[2]);
5811 addReply(c
,shared
.czero
);
5814 /* Delete from the skiplist */
5815 oldscore
= dictGetEntryVal(de
);
5816 deleted
= zslDelete(zs
->zsl
,*oldscore
,c
->argv
[2]);
5817 redisAssert(deleted
!= 0);
5819 /* Delete from the hash table */
5820 dictDelete(zs
->dict
,c
->argv
[2]);
5821 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
5822 if (dictSize(zs
->dict
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5824 addReply(c
,shared
.cone
);
5827 static void zremrangebyscoreCommand(redisClient
*c
) {
5834 if ((getDoubleFromObjectOrReply(c
, c
->argv
[2], &min
, NULL
) != REDIS_OK
) ||
5835 (getDoubleFromObjectOrReply(c
, c
->argv
[3], &max
, NULL
) != REDIS_OK
)) return;
5837 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5838 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
5841 deleted
= zslDeleteRangeByScore(zs
->zsl
,min
,max
,zs
->dict
);
5842 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
5843 if (dictSize(zs
->dict
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5844 server
.dirty
+= deleted
;
5845 addReplyLongLong(c
,deleted
);
5848 static void zremrangebyrankCommand(redisClient
*c
) {
5856 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
5857 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
5859 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5860 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
5862 llen
= zs
->zsl
->length
;
5864 /* convert negative indexes */
5865 if (start
< 0) start
= llen
+start
;
5866 if (end
< 0) end
= llen
+end
;
5867 if (start
< 0) start
= 0;
5868 if (end
< 0) end
= 0;
5870 /* indexes sanity checks */
5871 if (start
> end
|| start
>= llen
) {
5872 addReply(c
,shared
.czero
);
5875 if (end
>= llen
) end
= llen
-1;
5877 /* increment start and end because zsl*Rank functions
5878 * use 1-based rank */
5879 deleted
= zslDeleteRangeByRank(zs
->zsl
,start
+1,end
+1,zs
->dict
);
5880 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
5881 if (dictSize(zs
->dict
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5882 server
.dirty
+= deleted
;
5883 addReplyLongLong(c
, deleted
);
5891 static int qsortCompareZsetopsrcByCardinality(const void *s1
, const void *s2
) {
5892 zsetopsrc
*d1
= (void*) s1
, *d2
= (void*) s2
;
5893 unsigned long size1
, size2
;
5894 size1
= d1
->dict
? dictSize(d1
->dict
) : 0;
5895 size2
= d2
->dict
? dictSize(d2
->dict
) : 0;
5896 return size1
- size2
;
5899 #define REDIS_AGGR_SUM 1
5900 #define REDIS_AGGR_MIN 2
5901 #define REDIS_AGGR_MAX 3
5903 inline static void zunionInterAggregate(double *target
, double val
, int aggregate
) {
5904 if (aggregate
== REDIS_AGGR_SUM
) {
5905 *target
= *target
+ val
;
5906 } else if (aggregate
== REDIS_AGGR_MIN
) {
5907 *target
= val
< *target
? val
: *target
;
5908 } else if (aggregate
== REDIS_AGGR_MAX
) {
5909 *target
= val
> *target
? val
: *target
;
5912 redisPanic("Unknown ZUNION/INTER aggregate type");
5916 static void zunionInterGenericCommand(redisClient
*c
, robj
*dstkey
, int op
) {
5918 int aggregate
= REDIS_AGGR_SUM
;
5925 /* expect zsetnum input keys to be given */
5926 zsetnum
= atoi(c
->argv
[2]->ptr
);
5928 addReplySds(c
,sdsnew("-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE\r\n"));
5932 /* test if the expected number of keys would overflow */
5933 if (3+zsetnum
> c
->argc
) {
5934 addReply(c
,shared
.syntaxerr
);
5938 /* read keys to be used for input */
5939 src
= zmalloc(sizeof(zsetopsrc
) * zsetnum
);
5940 for (i
= 0, j
= 3; i
< zsetnum
; i
++, j
++) {
5941 robj
*zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
5945 if (zsetobj
->type
!= REDIS_ZSET
) {
5947 addReply(c
,shared
.wrongtypeerr
);
5950 src
[i
].dict
= ((zset
*)zsetobj
->ptr
)->dict
;
5953 /* default all weights to 1 */
5954 src
[i
].weight
= 1.0;
5957 /* parse optional extra arguments */
5959 int remaining
= c
->argc
- j
;
5962 if (remaining
>= (zsetnum
+ 1) && !strcasecmp(c
->argv
[j
]->ptr
,"weights")) {
5964 for (i
= 0; i
< zsetnum
; i
++, j
++, remaining
--) {
5965 if (getDoubleFromObjectOrReply(c
, c
->argv
[j
], &src
[i
].weight
, NULL
) != REDIS_OK
)
5968 } else if (remaining
>= 2 && !strcasecmp(c
->argv
[j
]->ptr
,"aggregate")) {
5970 if (!strcasecmp(c
->argv
[j
]->ptr
,"sum")) {
5971 aggregate
= REDIS_AGGR_SUM
;
5972 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"min")) {
5973 aggregate
= REDIS_AGGR_MIN
;
5974 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"max")) {
5975 aggregate
= REDIS_AGGR_MAX
;
5978 addReply(c
,shared
.syntaxerr
);
5984 addReply(c
,shared
.syntaxerr
);
5990 /* sort sets from the smallest to largest, this will improve our
5991 * algorithm's performance */
5992 qsort(src
,zsetnum
,sizeof(zsetopsrc
), qsortCompareZsetopsrcByCardinality
);
5994 dstobj
= createZsetObject();
5995 dstzset
= dstobj
->ptr
;
5997 if (op
== REDIS_OP_INTER
) {
5998 /* skip going over all entries if the smallest zset is NULL or empty */
5999 if (src
[0].dict
&& dictSize(src
[0].dict
) > 0) {
6000 /* precondition: as src[0].dict is non-empty and the zsets are ordered
6001 * from small to large, all src[i > 0].dict are non-empty too */
6002 di
= dictGetIterator(src
[0].dict
);
6003 while((de
= dictNext(di
)) != NULL
) {
6004 double *score
= zmalloc(sizeof(double)), value
;
6005 *score
= src
[0].weight
* (*(double*)dictGetEntryVal(de
));
6007 for (j
= 1; j
< zsetnum
; j
++) {
6008 dictEntry
*other
= dictFind(src
[j
].dict
,dictGetEntryKey(de
));
6010 value
= src
[j
].weight
* (*(double*)dictGetEntryVal(other
));
6011 zunionInterAggregate(score
, value
, aggregate
);
6017 /* skip entry when not present in every source dict */
6021 robj
*o
= dictGetEntryKey(de
);
6022 dictAdd(dstzset
->dict
,o
,score
);
6023 incrRefCount(o
); /* added to dictionary */
6024 zslInsert(dstzset
->zsl
,*score
,o
);
6025 incrRefCount(o
); /* added to skiplist */
6028 dictReleaseIterator(di
);
6030 } else if (op
== REDIS_OP_UNION
) {
6031 for (i
= 0; i
< zsetnum
; i
++) {
6032 if (!src
[i
].dict
) continue;
6034 di
= dictGetIterator(src
[i
].dict
);
6035 while((de
= dictNext(di
)) != NULL
) {
6036 /* skip key when already processed */
6037 if (dictFind(dstzset
->dict
,dictGetEntryKey(de
)) != NULL
) continue;
6039 double *score
= zmalloc(sizeof(double)), value
;
6040 *score
= src
[i
].weight
* (*(double*)dictGetEntryVal(de
));
6042 /* because the zsets are sorted by size, its only possible
6043 * for sets at larger indices to hold this entry */
6044 for (j
= (i
+1); j
< zsetnum
; j
++) {
6045 dictEntry
*other
= dictFind(src
[j
].dict
,dictGetEntryKey(de
));
6047 value
= src
[j
].weight
* (*(double*)dictGetEntryVal(other
));
6048 zunionInterAggregate(score
, value
, aggregate
);
6052 robj
*o
= dictGetEntryKey(de
);
6053 dictAdd(dstzset
->dict
,o
,score
);
6054 incrRefCount(o
); /* added to dictionary */
6055 zslInsert(dstzset
->zsl
,*score
,o
);
6056 incrRefCount(o
); /* added to skiplist */
6058 dictReleaseIterator(di
);
6061 /* unknown operator */
6062 redisAssert(op
== REDIS_OP_INTER
|| op
== REDIS_OP_UNION
);
6065 deleteKey(c
->db
,dstkey
);
6066 if (dstzset
->zsl
->length
) {
6067 dictAdd(c
->db
->dict
,dstkey
,dstobj
);
6068 incrRefCount(dstkey
);
6069 addReplyLongLong(c
, dstzset
->zsl
->length
);
6072 decrRefCount(dstobj
);
6073 addReply(c
, shared
.czero
);
6078 static void zunionstoreCommand(redisClient
*c
) {
6079 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_UNION
);
6082 static void zinterstoreCommand(redisClient
*c
) {
6083 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_INTER
);
6086 static void zrangeGenericCommand(redisClient
*c
, int reverse
) {
6098 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
6099 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
6101 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
6103 } else if (c
->argc
>= 5) {
6104 addReply(c
,shared
.syntaxerr
);
6108 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.emptymultibulk
)) == NULL
6109 || checkType(c
,o
,REDIS_ZSET
)) return;
6114 /* convert negative indexes */
6115 if (start
< 0) start
= llen
+start
;
6116 if (end
< 0) end
= llen
+end
;
6117 if (start
< 0) start
= 0;
6118 if (end
< 0) end
= 0;
6120 /* indexes sanity checks */
6121 if (start
> end
|| start
>= llen
) {
6122 /* Out of range start or start > end result in empty list */
6123 addReply(c
,shared
.emptymultibulk
);
6126 if (end
>= llen
) end
= llen
-1;
6127 rangelen
= (end
-start
)+1;
6129 /* check if starting point is trivial, before searching
6130 * the element in log(N) time */
6132 ln
= start
== 0 ? zsl
->tail
: zslGetElementByRank(zsl
, llen
-start
);
6135 zsl
->header
->forward
[0] : zslGetElementByRank(zsl
, start
+1);
6138 /* Return the result in form of a multi-bulk reply */
6139 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",
6140 withscores
? (rangelen
*2) : rangelen
));
6141 for (j
= 0; j
< rangelen
; j
++) {
6143 addReplyBulk(c
,ele
);
6145 addReplyDouble(c
,ln
->score
);
6146 ln
= reverse
? ln
->backward
: ln
->forward
[0];
6150 static void zrangeCommand(redisClient
*c
) {
6151 zrangeGenericCommand(c
,0);
6154 static void zrevrangeCommand(redisClient
*c
) {
6155 zrangeGenericCommand(c
,1);
6158 /* This command implements both ZRANGEBYSCORE and ZCOUNT.
6159 * If justcount is non-zero, just the count is returned. */
6160 static void genericZrangebyscoreCommand(redisClient
*c
, int justcount
) {
6163 int minex
= 0, maxex
= 0; /* are min or max exclusive? */
6164 int offset
= 0, limit
= -1;
6168 /* Parse the min-max interval. If one of the values is prefixed
6169 * by the "(" character, it's considered "open". For instance
6170 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
6171 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
6172 if (((char*)c
->argv
[2]->ptr
)[0] == '(') {
6173 min
= strtod((char*)c
->argv
[2]->ptr
+1,NULL
);
6176 min
= strtod(c
->argv
[2]->ptr
,NULL
);
6178 if (((char*)c
->argv
[3]->ptr
)[0] == '(') {
6179 max
= strtod((char*)c
->argv
[3]->ptr
+1,NULL
);
6182 max
= strtod(c
->argv
[3]->ptr
,NULL
);
6185 /* Parse "WITHSCORES": note that if the command was called with
6186 * the name ZCOUNT then we are sure that c->argc == 4, so we'll never
6187 * enter the following paths to parse WITHSCORES and LIMIT. */
6188 if (c
->argc
== 5 || c
->argc
== 8) {
6189 if (strcasecmp(c
->argv
[c
->argc
-1]->ptr
,"withscores") == 0)
6194 if (c
->argc
!= (4 + withscores
) && c
->argc
!= (7 + withscores
))
6198 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
6203 if (c
->argc
== (7 + withscores
) && strcasecmp(c
->argv
[4]->ptr
,"limit")) {
6204 addReply(c
,shared
.syntaxerr
);
6206 } else if (c
->argc
== (7 + withscores
)) {
6207 offset
= atoi(c
->argv
[5]->ptr
);
6208 limit
= atoi(c
->argv
[6]->ptr
);
6209 if (offset
< 0) offset
= 0;
6212 /* Ok, lookup the key and get the range */
6213 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
6215 addReply(c
,justcount
? shared
.czero
: shared
.emptymultibulk
);
6217 if (o
->type
!= REDIS_ZSET
) {
6218 addReply(c
,shared
.wrongtypeerr
);
6220 zset
*zsetobj
= o
->ptr
;
6221 zskiplist
*zsl
= zsetobj
->zsl
;
6223 robj
*ele
, *lenobj
= NULL
;
6224 unsigned long rangelen
= 0;
6226 /* Get the first node with the score >= min, or with
6227 * score > min if 'minex' is true. */
6228 ln
= zslFirstWithScore(zsl
,min
);
6229 while (minex
&& ln
&& ln
->score
== min
) ln
= ln
->forward
[0];
6232 /* No element matching the speciifed interval */
6233 addReply(c
,justcount
? shared
.czero
: shared
.emptymultibulk
);
6237 /* We don't know in advance how many matching elements there
6238 * are in the list, so we push this object that will represent
6239 * the multi-bulk length in the output buffer, and will "fix"
6242 lenobj
= createObject(REDIS_STRING
,NULL
);
6244 decrRefCount(lenobj
);
6247 while(ln
&& (maxex
? (ln
->score
< max
) : (ln
->score
<= max
))) {
6250 ln
= ln
->forward
[0];
6253 if (limit
== 0) break;
6256 addReplyBulk(c
,ele
);
6258 addReplyDouble(c
,ln
->score
);
6260 ln
= ln
->forward
[0];
6262 if (limit
> 0) limit
--;
6265 addReplyLongLong(c
,(long)rangelen
);
6267 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",
6268 withscores
? (rangelen
*2) : rangelen
);
6274 static void zrangebyscoreCommand(redisClient
*c
) {
6275 genericZrangebyscoreCommand(c
,0);
6278 static void zcountCommand(redisClient
*c
) {
6279 genericZrangebyscoreCommand(c
,1);
6282 static void zcardCommand(redisClient
*c
) {
6286 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
6287 checkType(c
,o
,REDIS_ZSET
)) return;
6290 addReplyUlong(c
,zs
->zsl
->length
);
6293 static void zscoreCommand(redisClient
*c
) {
6298 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
6299 checkType(c
,o
,REDIS_ZSET
)) return;
6302 de
= dictFind(zs
->dict
,c
->argv
[2]);
6304 addReply(c
,shared
.nullbulk
);
6306 double *score
= dictGetEntryVal(de
);
6308 addReplyDouble(c
,*score
);
6312 static void zrankGenericCommand(redisClient
*c
, int reverse
) {
6320 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
6321 checkType(c
,o
,REDIS_ZSET
)) return;
6325 de
= dictFind(zs
->dict
,c
->argv
[2]);
6327 addReply(c
,shared
.nullbulk
);
6331 score
= dictGetEntryVal(de
);
6332 rank
= zslGetRank(zsl
, *score
, c
->argv
[2]);
6335 addReplyLongLong(c
, zsl
->length
- rank
);
6337 addReplyLongLong(c
, rank
-1);
6340 addReply(c
,shared
.nullbulk
);
6344 static void zrankCommand(redisClient
*c
) {
6345 zrankGenericCommand(c
, 0);
6348 static void zrevrankCommand(redisClient
*c
) {
6349 zrankGenericCommand(c
, 1);
6352 /* ========================= Hashes utility functions ======================= */
6353 #define REDIS_HASH_KEY 1
6354 #define REDIS_HASH_VALUE 2
6356 /* Check the length of a number of objects to see if we need to convert a
6357 * zipmap to a real hash. Note that we only check string encoded objects
6358 * as their string length can be queried in constant time. */
6359 static void hashTryConversion(robj
*subject
, robj
**argv
, int start
, int end
) {
6361 if (subject
->encoding
!= REDIS_ENCODING_ZIPMAP
) return;
6363 for (i
= start
; i
<= end
; i
++) {
6364 if (argv
[i
]->encoding
== REDIS_ENCODING_RAW
&&
6365 sdslen(argv
[i
]->ptr
) > server
.hash_max_zipmap_value
)
6367 convertToRealHash(subject
);
6373 /* Encode given objects in-place when the hash uses a dict. */
6374 static void hashTryObjectEncoding(robj
*subject
, robj
**o1
, robj
**o2
) {
6375 if (subject
->encoding
== REDIS_ENCODING_HT
) {
6376 if (o1
) *o1
= tryObjectEncoding(*o1
);
6377 if (o2
) *o2
= tryObjectEncoding(*o2
);
6381 /* Get the value from a hash identified by key. Returns either a string
6382 * object or NULL if the value cannot be found. The refcount of the object
6383 * is always increased by 1 when the value was found. */
6384 static robj
*hashGet(robj
*o
, robj
*key
) {
6386 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6389 key
= getDecodedObject(key
);
6390 if (zipmapGet(o
->ptr
,key
->ptr
,sdslen(key
->ptr
),&v
,&vlen
)) {
6391 value
= createStringObject((char*)v
,vlen
);
6395 dictEntry
*de
= dictFind(o
->ptr
,key
);
6397 value
= dictGetEntryVal(de
);
6398 incrRefCount(value
);
6404 /* Test if the key exists in the given hash. Returns 1 if the key
6405 * exists and 0 when it doesn't. */
6406 static int hashExists(robj
*o
, robj
*key
) {
6407 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6408 key
= getDecodedObject(key
);
6409 if (zipmapExists(o
->ptr
,key
->ptr
,sdslen(key
->ptr
))) {
6415 if (dictFind(o
->ptr
,key
) != NULL
) {
6422 /* Add an element, discard the old if the key already exists.
6423 * Return 0 on insert and 1 on update. */
6424 static int hashSet(robj
*o
, robj
*key
, robj
*value
) {
6426 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6427 key
= getDecodedObject(key
);
6428 value
= getDecodedObject(value
);
6429 o
->ptr
= zipmapSet(o
->ptr
,
6430 key
->ptr
,sdslen(key
->ptr
),
6431 value
->ptr
,sdslen(value
->ptr
), &update
);
6433 decrRefCount(value
);
6435 /* Check if the zipmap needs to be upgraded to a real hash table */
6436 if (zipmapLen(o
->ptr
) > server
.hash_max_zipmap_entries
)
6437 convertToRealHash(o
);
6439 if (dictReplace(o
->ptr
,key
,value
)) {
6446 incrRefCount(value
);
6451 /* Delete an element from a hash.
6452 * Return 1 on deleted and 0 on not found. */
6453 static int hashDelete(robj
*o
, robj
*key
) {
6455 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6456 key
= getDecodedObject(key
);
6457 o
->ptr
= zipmapDel(o
->ptr
,key
->ptr
,sdslen(key
->ptr
), &deleted
);
6460 deleted
= dictDelete((dict
*)o
->ptr
,key
) == DICT_OK
;
6461 /* Always check if the dictionary needs a resize after a delete. */
6462 if (deleted
&& htNeedsResize(o
->ptr
)) dictResize(o
->ptr
);
6467 /* Return the number of elements in a hash. */
6468 static unsigned long hashLength(robj
*o
) {
6469 return (o
->encoding
== REDIS_ENCODING_ZIPMAP
) ?
6470 zipmapLen((unsigned char*)o
->ptr
) : dictSize((dict
*)o
->ptr
);
6473 /* Structure to hold hash iteration abstration. Note that iteration over
6474 * hashes involves both fields and values. Because it is possible that
6475 * not both are required, store pointers in the iterator to avoid
6476 * unnecessary memory allocation for fields/values. */
6480 unsigned char *zk
, *zv
;
6481 unsigned int zklen
, zvlen
;
6487 static hashIterator
*hashInitIterator(robj
*subject
) {
6488 hashIterator
*hi
= zmalloc(sizeof(hashIterator
));
6489 hi
->encoding
= subject
->encoding
;
6490 if (hi
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6491 hi
->zi
= zipmapRewind(subject
->ptr
);
6492 } else if (hi
->encoding
== REDIS_ENCODING_HT
) {
6493 hi
->di
= dictGetIterator(subject
->ptr
);
6500 static void hashReleaseIterator(hashIterator
*hi
) {
6501 if (hi
->encoding
== REDIS_ENCODING_HT
) {
6502 dictReleaseIterator(hi
->di
);
6507 /* Move to the next entry in the hash. Return REDIS_OK when the next entry
6508 * could be found and REDIS_ERR when the iterator reaches the end. */
6509 static int hashNext(hashIterator
*hi
) {
6510 if (hi
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6511 if ((hi
->zi
= zipmapNext(hi
->zi
, &hi
->zk
, &hi
->zklen
,
6512 &hi
->zv
, &hi
->zvlen
)) == NULL
) return REDIS_ERR
;
6514 if ((hi
->de
= dictNext(hi
->di
)) == NULL
) return REDIS_ERR
;
6519 /* Get key or value object at current iteration position.
6520 * This increases the refcount of the field object by 1. */
6521 static robj
*hashCurrent(hashIterator
*hi
, int what
) {
6523 if (hi
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6524 if (what
& REDIS_HASH_KEY
) {
6525 o
= createStringObject((char*)hi
->zk
,hi
->zklen
);
6527 o
= createStringObject((char*)hi
->zv
,hi
->zvlen
);
6530 if (what
& REDIS_HASH_KEY
) {
6531 o
= dictGetEntryKey(hi
->de
);
6533 o
= dictGetEntryVal(hi
->de
);
6540 static robj
*hashLookupWriteOrCreate(redisClient
*c
, robj
*key
) {
6541 robj
*o
= lookupKeyWrite(c
->db
,key
);
6543 o
= createHashObject();
6544 dictAdd(c
->db
->dict
,key
,o
);
6547 if (o
->type
!= REDIS_HASH
) {
6548 addReply(c
,shared
.wrongtypeerr
);
6555 /* ============================= Hash commands ============================== */
6556 static void hsetCommand(redisClient
*c
) {
6560 if ((o
= hashLookupWriteOrCreate(c
,c
->argv
[1])) == NULL
) return;
6561 hashTryConversion(o
,c
->argv
,2,3);
6562 hashTryObjectEncoding(o
,&c
->argv
[2], &c
->argv
[3]);
6563 update
= hashSet(o
,c
->argv
[2],c
->argv
[3]);
6564 addReply(c
, update
? shared
.czero
: shared
.cone
);
6568 static void hsetnxCommand(redisClient
*c
) {
6570 if ((o
= hashLookupWriteOrCreate(c
,c
->argv
[1])) == NULL
) return;
6571 hashTryConversion(o
,c
->argv
,2,3);
6573 if (hashExists(o
, c
->argv
[2])) {
6574 addReply(c
, shared
.czero
);
6576 hashTryObjectEncoding(o
,&c
->argv
[2], &c
->argv
[3]);
6577 hashSet(o
,c
->argv
[2],c
->argv
[3]);
6578 addReply(c
, shared
.cone
);
6583 static void hmsetCommand(redisClient
*c
) {
6587 if ((c
->argc
% 2) == 1) {
6588 addReplySds(c
,sdsnew("-ERR wrong number of arguments for HMSET\r\n"));
6592 if ((o
= hashLookupWriteOrCreate(c
,c
->argv
[1])) == NULL
) return;
6593 hashTryConversion(o
,c
->argv
,2,c
->argc
-1);
6594 for (i
= 2; i
< c
->argc
; i
+= 2) {
6595 hashTryObjectEncoding(o
,&c
->argv
[i
], &c
->argv
[i
+1]);
6596 hashSet(o
,c
->argv
[i
],c
->argv
[i
+1]);
6598 addReply(c
, shared
.ok
);
6602 static void hincrbyCommand(redisClient
*c
) {
6603 long long value
, incr
;
6604 robj
*o
, *current
, *new;
6606 if (getLongLongFromObjectOrReply(c
,c
->argv
[3],&incr
,NULL
) != REDIS_OK
) return;
6607 if ((o
= hashLookupWriteOrCreate(c
,c
->argv
[1])) == NULL
) return;
6608 if ((current
= hashGet(o
,c
->argv
[2])) != NULL
) {
6609 if (getLongLongFromObjectOrReply(c
,current
,&value
,
6610 "hash value is not an integer") != REDIS_OK
) {
6611 decrRefCount(current
);
6614 decrRefCount(current
);
6620 new = createStringObjectFromLongLong(value
);
6621 hashTryObjectEncoding(o
,&c
->argv
[2],NULL
);
6622 hashSet(o
,c
->argv
[2],new);
6624 addReplyLongLong(c
,value
);
6628 static void hgetCommand(redisClient
*c
) {
6630 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
6631 checkType(c
,o
,REDIS_HASH
)) return;
6633 if ((value
= hashGet(o
,c
->argv
[2])) != NULL
) {
6634 addReplyBulk(c
,value
);
6635 decrRefCount(value
);
6637 addReply(c
,shared
.nullbulk
);
6641 static void hmgetCommand(redisClient
*c
) {
6644 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
6645 if (o
!= NULL
&& o
->type
!= REDIS_HASH
) {
6646 addReply(c
,shared
.wrongtypeerr
);
6649 /* Note the check for o != NULL happens inside the loop. This is
6650 * done because objects that cannot be found are considered to be
6651 * an empty hash. The reply should then be a series of NULLs. */
6652 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-2));
6653 for (i
= 2; i
< c
->argc
; i
++) {
6654 if (o
!= NULL
&& (value
= hashGet(o
,c
->argv
[i
])) != NULL
) {
6655 addReplyBulk(c
,value
);
6656 decrRefCount(value
);
6658 addReply(c
,shared
.nullbulk
);
6663 static void hdelCommand(redisClient
*c
) {
6665 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
6666 checkType(c
,o
,REDIS_HASH
)) return;
6668 if (hashDelete(o
,c
->argv
[2])) {
6669 if (hashLength(o
) == 0) deleteKey(c
->db
,c
->argv
[1]);
6670 addReply(c
,shared
.cone
);
6673 addReply(c
,shared
.czero
);
6677 static void hlenCommand(redisClient
*c
) {
6679 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
6680 checkType(c
,o
,REDIS_HASH
)) return;
6682 addReplyUlong(c
,hashLength(o
));
6685 static void genericHgetallCommand(redisClient
*c
, int flags
) {
6686 robj
*o
, *lenobj
, *obj
;
6687 unsigned long count
= 0;
6690 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.emptymultibulk
)) == NULL
6691 || checkType(c
,o
,REDIS_HASH
)) return;
6693 lenobj
= createObject(REDIS_STRING
,NULL
);
6695 decrRefCount(lenobj
);
6697 hi
= hashInitIterator(o
);
6698 while (hashNext(hi
) != REDIS_ERR
) {
6699 if (flags
& REDIS_HASH_KEY
) {
6700 obj
= hashCurrent(hi
,REDIS_HASH_KEY
);
6701 addReplyBulk(c
,obj
);
6705 if (flags
& REDIS_HASH_VALUE
) {
6706 obj
= hashCurrent(hi
,REDIS_HASH_VALUE
);
6707 addReplyBulk(c
,obj
);
6712 hashReleaseIterator(hi
);
6714 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",count
);
6717 static void hkeysCommand(redisClient
*c
) {
6718 genericHgetallCommand(c
,REDIS_HASH_KEY
);
6721 static void hvalsCommand(redisClient
*c
) {
6722 genericHgetallCommand(c
,REDIS_HASH_VALUE
);
6725 static void hgetallCommand(redisClient
*c
) {
6726 genericHgetallCommand(c
,REDIS_HASH_KEY
|REDIS_HASH_VALUE
);
6729 static void hexistsCommand(redisClient
*c
) {
6731 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
6732 checkType(c
,o
,REDIS_HASH
)) return;
6734 addReply(c
, hashExists(o
,c
->argv
[2]) ? shared
.cone
: shared
.czero
);
6737 static void convertToRealHash(robj
*o
) {
6738 unsigned char *key
, *val
, *p
, *zm
= o
->ptr
;
6739 unsigned int klen
, vlen
;
6740 dict
*dict
= dictCreate(&hashDictType
,NULL
);
6742 assert(o
->type
== REDIS_HASH
&& o
->encoding
!= REDIS_ENCODING_HT
);
6743 p
= zipmapRewind(zm
);
6744 while((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) != NULL
) {
6745 robj
*keyobj
, *valobj
;
6747 keyobj
= createStringObject((char*)key
,klen
);
6748 valobj
= createStringObject((char*)val
,vlen
);
6749 keyobj
= tryObjectEncoding(keyobj
);
6750 valobj
= tryObjectEncoding(valobj
);
6751 dictAdd(dict
,keyobj
,valobj
);
6753 o
->encoding
= REDIS_ENCODING_HT
;
6758 /* ========================= Non type-specific commands ==================== */
6760 static void flushdbCommand(redisClient
*c
) {
6761 server
.dirty
+= dictSize(c
->db
->dict
);
6762 dictEmpty(c
->db
->dict
);
6763 dictEmpty(c
->db
->expires
);
6764 addReply(c
,shared
.ok
);
6767 static void flushallCommand(redisClient
*c
) {
6768 server
.dirty
+= emptyDb();
6769 addReply(c
,shared
.ok
);
6770 if (server
.bgsavechildpid
!= -1) {
6771 kill(server
.bgsavechildpid
,SIGKILL
);
6772 rdbRemoveTempFile(server
.bgsavechildpid
);
6774 rdbSave(server
.dbfilename
);
6778 static redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
6779 redisSortOperation
*so
= zmalloc(sizeof(*so
));
6781 so
->pattern
= pattern
;
6785 /* Return the value associated to the key with a name obtained
6786 * substituting the first occurence of '*' in 'pattern' with 'subst'.
6787 * The returned object will always have its refcount increased by 1
6788 * when it is non-NULL. */
6789 static robj
*lookupKeyByPattern(redisDb
*db
, robj
*pattern
, robj
*subst
) {
6792 robj keyobj
, fieldobj
, *o
;
6793 int prefixlen
, sublen
, postfixlen
, fieldlen
;
6794 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
6798 char buf
[REDIS_SORTKEY_MAX
+1];
6799 } keyname
, fieldname
;
6801 /* If the pattern is "#" return the substitution object itself in order
6802 * to implement the "SORT ... GET #" feature. */
6803 spat
= pattern
->ptr
;
6804 if (spat
[0] == '#' && spat
[1] == '\0') {
6805 incrRefCount(subst
);
6809 /* The substitution object may be specially encoded. If so we create
6810 * a decoded object on the fly. Otherwise getDecodedObject will just
6811 * increment the ref count, that we'll decrement later. */
6812 subst
= getDecodedObject(subst
);
6815 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
6816 p
= strchr(spat
,'*');
6818 decrRefCount(subst
);
6822 /* Find out if we're dealing with a hash dereference. */
6823 if ((f
= strstr(p
+1, "->")) != NULL
) {
6824 fieldlen
= sdslen(spat
)-(f
-spat
);
6825 /* this also copies \0 character */
6826 memcpy(fieldname
.buf
,f
+2,fieldlen
-1);
6827 fieldname
.len
= fieldlen
-2;
6833 sublen
= sdslen(ssub
);
6834 postfixlen
= sdslen(spat
)-(prefixlen
+1)-fieldlen
;
6835 memcpy(keyname
.buf
,spat
,prefixlen
);
6836 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
6837 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
6838 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
6839 keyname
.len
= prefixlen
+sublen
+postfixlen
;
6840 decrRefCount(subst
);
6842 /* Lookup substituted key */
6843 initStaticStringObject(keyobj
,((char*)&keyname
)+(sizeof(long)*2));
6844 o
= lookupKeyRead(db
,&keyobj
);
6845 if (o
== NULL
) return NULL
;
6848 if (o
->type
!= REDIS_HASH
|| fieldname
.len
< 1) return NULL
;
6850 /* Retrieve value from hash by the field name. This operation
6851 * already increases the refcount of the returned object. */
6852 initStaticStringObject(fieldobj
,((char*)&fieldname
)+(sizeof(long)*2));
6853 o
= hashGet(o
, &fieldobj
);
6855 if (o
->type
!= REDIS_STRING
) return NULL
;
6857 /* Every object that this function returns needs to have its refcount
6858 * increased. sortCommand decreases it again. */
6865 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
6866 * the additional parameter is not standard but a BSD-specific we have to
6867 * pass sorting parameters via the global 'server' structure */
6868 static int sortCompare(const void *s1
, const void *s2
) {
6869 const redisSortObject
*so1
= s1
, *so2
= s2
;
6872 if (!server
.sort_alpha
) {
6873 /* Numeric sorting. Here it's trivial as we precomputed scores */
6874 if (so1
->u
.score
> so2
->u
.score
) {
6876 } else if (so1
->u
.score
< so2
->u
.score
) {
6882 /* Alphanumeric sorting */
6883 if (server
.sort_bypattern
) {
6884 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
6885 /* At least one compare object is NULL */
6886 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
6888 else if (so1
->u
.cmpobj
== NULL
)
6893 /* We have both the objects, use strcoll */
6894 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
6897 /* Compare elements directly. */
6898 cmp
= compareStringObjects(so1
->obj
,so2
->obj
);
6901 return server
.sort_desc
? -cmp
: cmp
;
6904 /* The SORT command is the most complex command in Redis. Warning: this code
6905 * is optimized for speed and a bit less for readability */
6906 static void sortCommand(redisClient
*c
) {
6909 int desc
= 0, alpha
= 0;
6910 int limit_start
= 0, limit_count
= -1, start
, end
;
6911 int j
, dontsort
= 0, vectorlen
;
6912 int getop
= 0; /* GET operation counter */
6913 robj
*sortval
, *sortby
= NULL
, *storekey
= NULL
;
6914 redisSortObject
*vector
; /* Resulting vector to sort */
6916 /* Lookup the key to sort. It must be of the right types */
6917 sortval
= lookupKeyRead(c
->db
,c
->argv
[1]);
6918 if (sortval
== NULL
) {
6919 addReply(c
,shared
.emptymultibulk
);
6922 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
&&
6923 sortval
->type
!= REDIS_ZSET
)
6925 addReply(c
,shared
.wrongtypeerr
);
6929 /* Create a list of operations to perform for every sorted element.
6930 * Operations can be GET/DEL/INCR/DECR */
6931 operations
= listCreate();
6932 listSetFreeMethod(operations
,zfree
);
6935 /* Now we need to protect sortval incrementing its count, in the future
6936 * SORT may have options able to overwrite/delete keys during the sorting
6937 * and the sorted key itself may get destroied */
6938 incrRefCount(sortval
);
6940 /* The SORT command has an SQL-alike syntax, parse it */
6941 while(j
< c
->argc
) {
6942 int leftargs
= c
->argc
-j
-1;
6943 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
6945 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
6947 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
6949 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
6950 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
6951 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
6953 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"store") && leftargs
>= 1) {
6954 storekey
= c
->argv
[j
+1];
6956 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
6957 sortby
= c
->argv
[j
+1];
6958 /* If the BY pattern does not contain '*', i.e. it is constant,
6959 * we don't need to sort nor to lookup the weight keys. */
6960 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
6962 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
6963 listAddNodeTail(operations
,createSortOperation(
6964 REDIS_SORT_GET
,c
->argv
[j
+1]));
6968 decrRefCount(sortval
);
6969 listRelease(operations
);
6970 addReply(c
,shared
.syntaxerr
);
6976 /* Load the sorting vector with all the objects to sort */
6977 switch(sortval
->type
) {
6978 case REDIS_LIST
: vectorlen
= listLength((list
*)sortval
->ptr
); break;
6979 case REDIS_SET
: vectorlen
= dictSize((dict
*)sortval
->ptr
); break;
6980 case REDIS_ZSET
: vectorlen
= dictSize(((zset
*)sortval
->ptr
)->dict
); break;
6981 default: vectorlen
= 0; redisPanic("Bad SORT type"); /* Avoid GCC warning */
6983 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
6986 if (sortval
->type
== REDIS_LIST
) {
6987 list
*list
= sortval
->ptr
;
6991 listRewind(list
,&li
);
6992 while((ln
= listNext(&li
))) {
6993 robj
*ele
= ln
->value
;
6994 vector
[j
].obj
= ele
;
6995 vector
[j
].u
.score
= 0;
6996 vector
[j
].u
.cmpobj
= NULL
;
7004 if (sortval
->type
== REDIS_SET
) {
7007 zset
*zs
= sortval
->ptr
;
7011 di
= dictGetIterator(set
);
7012 while((setele
= dictNext(di
)) != NULL
) {
7013 vector
[j
].obj
= dictGetEntryKey(setele
);
7014 vector
[j
].u
.score
= 0;
7015 vector
[j
].u
.cmpobj
= NULL
;
7018 dictReleaseIterator(di
);
7020 redisAssert(j
== vectorlen
);
7022 /* Now it's time to load the right scores in the sorting vector */
7023 if (dontsort
== 0) {
7024 for (j
= 0; j
< vectorlen
; j
++) {
7027 /* lookup value to sort by */
7028 byval
= lookupKeyByPattern(c
->db
,sortby
,vector
[j
].obj
);
7029 if (!byval
) continue;
7031 /* use object itself to sort by */
7032 byval
= vector
[j
].obj
;
7036 if (sortby
) vector
[j
].u
.cmpobj
= getDecodedObject(byval
);
7038 if (byval
->encoding
== REDIS_ENCODING_RAW
) {
7039 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
7040 } else if (byval
->encoding
== REDIS_ENCODING_INT
) {
7041 /* Don't need to decode the object if it's
7042 * integer-encoded (the only encoding supported) so
7043 * far. We can just cast it */
7044 vector
[j
].u
.score
= (long)byval
->ptr
;
7046 redisAssert(1 != 1);
7050 /* when the object was retrieved using lookupKeyByPattern,
7051 * its refcount needs to be decreased. */
7053 decrRefCount(byval
);
7058 /* We are ready to sort the vector... perform a bit of sanity check
7059 * on the LIMIT option too. We'll use a partial version of quicksort. */
7060 start
= (limit_start
< 0) ? 0 : limit_start
;
7061 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
7062 if (start
>= vectorlen
) {
7063 start
= vectorlen
-1;
7066 if (end
>= vectorlen
) end
= vectorlen
-1;
7068 if (dontsort
== 0) {
7069 server
.sort_desc
= desc
;
7070 server
.sort_alpha
= alpha
;
7071 server
.sort_bypattern
= sortby
? 1 : 0;
7072 if (sortby
&& (start
!= 0 || end
!= vectorlen
-1))
7073 pqsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
, start
,end
);
7075 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
7078 /* Send command output to the output buffer, performing the specified
7079 * GET/DEL/INCR/DECR operations if any. */
7080 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
7081 if (storekey
== NULL
) {
7082 /* STORE option not specified, sent the sorting result to client */
7083 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
7084 for (j
= start
; j
<= end
; j
++) {
7088 if (!getop
) addReplyBulk(c
,vector
[j
].obj
);
7089 listRewind(operations
,&li
);
7090 while((ln
= listNext(&li
))) {
7091 redisSortOperation
*sop
= ln
->value
;
7092 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
7095 if (sop
->type
== REDIS_SORT_GET
) {
7097 addReply(c
,shared
.nullbulk
);
7099 addReplyBulk(c
,val
);
7103 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
7108 robj
*listObject
= createListObject();
7109 list
*listPtr
= (list
*) listObject
->ptr
;
7111 /* STORE option specified, set the sorting result as a List object */
7112 for (j
= start
; j
<= end
; j
++) {
7117 listAddNodeTail(listPtr
,vector
[j
].obj
);
7118 incrRefCount(vector
[j
].obj
);
7120 listRewind(operations
,&li
);
7121 while((ln
= listNext(&li
))) {
7122 redisSortOperation
*sop
= ln
->value
;
7123 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
7126 if (sop
->type
== REDIS_SORT_GET
) {
7128 listAddNodeTail(listPtr
,createStringObject("",0));
7130 /* We should do a incrRefCount on val because it is
7131 * added to the list, but also a decrRefCount because
7132 * it is returned by lookupKeyByPattern. This results
7133 * in doing nothing at all. */
7134 listAddNodeTail(listPtr
,val
);
7137 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
7141 if (dictReplace(c
->db
->dict
,storekey
,listObject
)) {
7142 incrRefCount(storekey
);
7144 /* Note: we add 1 because the DB is dirty anyway since even if the
7145 * SORT result is empty a new key is set and maybe the old content
7147 server
.dirty
+= 1+outputlen
;
7148 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",outputlen
));
7152 decrRefCount(sortval
);
7153 listRelease(operations
);
7154 for (j
= 0; j
< vectorlen
; j
++) {
7155 if (alpha
&& vector
[j
].u
.cmpobj
)
7156 decrRefCount(vector
[j
].u
.cmpobj
);
7161 /* Convert an amount of bytes into a human readable string in the form
7162 * of 100B, 2G, 100M, 4K, and so forth. */
7163 static void bytesToHuman(char *s
, unsigned long long n
) {
7168 sprintf(s
,"%lluB",n
);
7170 } else if (n
< (1024*1024)) {
7171 d
= (double)n
/(1024);
7172 sprintf(s
,"%.2fK",d
);
7173 } else if (n
< (1024LL*1024*1024)) {
7174 d
= (double)n
/(1024*1024);
7175 sprintf(s
,"%.2fM",d
);
7176 } else if (n
< (1024LL*1024*1024*1024)) {
7177 d
= (double)n
/(1024LL*1024*1024);
7178 sprintf(s
,"%.2fG",d
);
7182 /* Create the string returned by the INFO command. This is decoupled
7183 * by the INFO command itself as we need to report the same information
7184 * on memory corruption problems. */
7185 static sds
genRedisInfoString(void) {
7187 time_t uptime
= time(NULL
)-server
.stat_starttime
;
7191 bytesToHuman(hmem
,zmalloc_used_memory());
7192 info
= sdscatprintf(sdsempty(),
7193 "redis_version:%s\r\n"
7194 "redis_git_sha1:%s\r\n"
7195 "redis_git_dirty:%d\r\n"
7197 "multiplexing_api:%s\r\n"
7198 "process_id:%ld\r\n"
7199 "uptime_in_seconds:%ld\r\n"
7200 "uptime_in_days:%ld\r\n"
7201 "connected_clients:%d\r\n"
7202 "connected_slaves:%d\r\n"
7203 "blocked_clients:%d\r\n"
7204 "used_memory:%zu\r\n"
7205 "used_memory_human:%s\r\n"
7206 "changes_since_last_save:%lld\r\n"
7207 "bgsave_in_progress:%d\r\n"
7208 "last_save_time:%ld\r\n"
7209 "bgrewriteaof_in_progress:%d\r\n"
7210 "total_connections_received:%lld\r\n"
7211 "total_commands_processed:%lld\r\n"
7212 "expired_keys:%lld\r\n"
7213 "hash_max_zipmap_entries:%zu\r\n"
7214 "hash_max_zipmap_value:%zu\r\n"
7215 "pubsub_channels:%ld\r\n"
7216 "pubsub_patterns:%u\r\n"
7221 strtol(REDIS_GIT_DIRTY
,NULL
,10) > 0,
7222 (sizeof(long) == 8) ? "64" : "32",
7227 listLength(server
.clients
)-listLength(server
.slaves
),
7228 listLength(server
.slaves
),
7229 server
.blpop_blocked_clients
,
7230 zmalloc_used_memory(),
7233 server
.bgsavechildpid
!= -1,
7235 server
.bgrewritechildpid
!= -1,
7236 server
.stat_numconnections
,
7237 server
.stat_numcommands
,
7238 server
.stat_expiredkeys
,
7239 server
.hash_max_zipmap_entries
,
7240 server
.hash_max_zipmap_value
,
7241 dictSize(server
.pubsub_channels
),
7242 listLength(server
.pubsub_patterns
),
7243 server
.vm_enabled
!= 0,
7244 server
.masterhost
== NULL
? "master" : "slave"
7246 if (server
.masterhost
) {
7247 info
= sdscatprintf(info
,
7248 "master_host:%s\r\n"
7249 "master_port:%d\r\n"
7250 "master_link_status:%s\r\n"
7251 "master_last_io_seconds_ago:%d\r\n"
7254 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
7256 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1
7259 if (server
.vm_enabled
) {
7261 info
= sdscatprintf(info
,
7262 "vm_conf_max_memory:%llu\r\n"
7263 "vm_conf_page_size:%llu\r\n"
7264 "vm_conf_pages:%llu\r\n"
7265 "vm_stats_used_pages:%llu\r\n"
7266 "vm_stats_swapped_objects:%llu\r\n"
7267 "vm_stats_swappin_count:%llu\r\n"
7268 "vm_stats_swappout_count:%llu\r\n"
7269 "vm_stats_io_newjobs_len:%lu\r\n"
7270 "vm_stats_io_processing_len:%lu\r\n"
7271 "vm_stats_io_processed_len:%lu\r\n"
7272 "vm_stats_io_active_threads:%lu\r\n"
7273 "vm_stats_blocked_clients:%lu\r\n"
7274 ,(unsigned long long) server
.vm_max_memory
,
7275 (unsigned long long) server
.vm_page_size
,
7276 (unsigned long long) server
.vm_pages
,
7277 (unsigned long long) server
.vm_stats_used_pages
,
7278 (unsigned long long) server
.vm_stats_swapped_objects
,
7279 (unsigned long long) server
.vm_stats_swapins
,
7280 (unsigned long long) server
.vm_stats_swapouts
,
7281 (unsigned long) listLength(server
.io_newjobs
),
7282 (unsigned long) listLength(server
.io_processing
),
7283 (unsigned long) listLength(server
.io_processed
),
7284 (unsigned long) server
.io_active_threads
,
7285 (unsigned long) server
.vm_blocked_clients
7289 for (j
= 0; j
< server
.dbnum
; j
++) {
7290 long long keys
, vkeys
;
7292 keys
= dictSize(server
.db
[j
].dict
);
7293 vkeys
= dictSize(server
.db
[j
].expires
);
7294 if (keys
|| vkeys
) {
7295 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
7302 static void infoCommand(redisClient
*c
) {
7303 sds info
= genRedisInfoString();
7304 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
7305 (unsigned long)sdslen(info
)));
7306 addReplySds(c
,info
);
7307 addReply(c
,shared
.crlf
);
7310 static void monitorCommand(redisClient
*c
) {
7311 /* ignore MONITOR if aleady slave or in monitor mode */
7312 if (c
->flags
& REDIS_SLAVE
) return;
7314 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
7316 listAddNodeTail(server
.monitors
,c
);
7317 addReply(c
,shared
.ok
);
7320 /* ================================= Expire ================================= */
7321 static int removeExpire(redisDb
*db
, robj
*key
) {
7322 if (dictDelete(db
->expires
,key
) == DICT_OK
) {
7329 static int setExpire(redisDb
*db
, robj
*key
, time_t when
) {
7330 if (dictAdd(db
->expires
,key
,(void*)when
) == DICT_ERR
) {
7338 /* Return the expire time of the specified key, or -1 if no expire
7339 * is associated with this key (i.e. the key is non volatile) */
7340 static time_t getExpire(redisDb
*db
, robj
*key
) {
7343 /* No expire? return ASAP */
7344 if (dictSize(db
->expires
) == 0 ||
7345 (de
= dictFind(db
->expires
,key
)) == NULL
) return -1;
7347 return (time_t) dictGetEntryVal(de
);
7350 static int expireIfNeeded(redisDb
*db
, robj
*key
) {
7354 /* No expire? return ASAP */
7355 if (dictSize(db
->expires
) == 0 ||
7356 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
7358 /* Lookup the expire */
7359 when
= (time_t) dictGetEntryVal(de
);
7360 if (time(NULL
) <= when
) return 0;
7362 /* Delete the key */
7363 dictDelete(db
->expires
,key
);
7364 server
.stat_expiredkeys
++;
7365 return dictDelete(db
->dict
,key
) == DICT_OK
;
7368 static int deleteIfVolatile(redisDb
*db
, robj
*key
) {
7371 /* No expire? return ASAP */
7372 if (dictSize(db
->expires
) == 0 ||
7373 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
7375 /* Delete the key */
7377 server
.stat_expiredkeys
++;
7378 dictDelete(db
->expires
,key
);
7379 return dictDelete(db
->dict
,key
) == DICT_OK
;
7382 static void expireGenericCommand(redisClient
*c
, robj
*key
, robj
*param
, long offset
) {
7386 if (getLongFromObjectOrReply(c
, param
, &seconds
, NULL
) != REDIS_OK
) return;
7390 de
= dictFind(c
->db
->dict
,key
);
7392 addReply(c
,shared
.czero
);
7396 if (deleteKey(c
->db
,key
)) server
.dirty
++;
7397 addReply(c
, shared
.cone
);
7400 time_t when
= time(NULL
)+seconds
;
7401 if (setExpire(c
->db
,key
,when
)) {
7402 addReply(c
,shared
.cone
);
7405 addReply(c
,shared
.czero
);
7411 static void expireCommand(redisClient
*c
) {
7412 expireGenericCommand(c
,c
->argv
[1],c
->argv
[2],0);
7415 static void expireatCommand(redisClient
*c
) {
7416 expireGenericCommand(c
,c
->argv
[1],c
->argv
[2],time(NULL
));
7419 static void ttlCommand(redisClient
*c
) {
7423 expire
= getExpire(c
->db
,c
->argv
[1]);
7425 ttl
= (int) (expire
-time(NULL
));
7426 if (ttl
< 0) ttl
= -1;
7428 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",ttl
));
7431 /* ================================ MULTI/EXEC ============================== */
7433 /* Client state initialization for MULTI/EXEC */
7434 static void initClientMultiState(redisClient
*c
) {
7435 c
->mstate
.commands
= NULL
;
7436 c
->mstate
.count
= 0;
7439 /* Release all the resources associated with MULTI/EXEC state */
7440 static void freeClientMultiState(redisClient
*c
) {
7443 for (j
= 0; j
< c
->mstate
.count
; j
++) {
7445 multiCmd
*mc
= c
->mstate
.commands
+j
;
7447 for (i
= 0; i
< mc
->argc
; i
++)
7448 decrRefCount(mc
->argv
[i
]);
7451 zfree(c
->mstate
.commands
);
7454 /* Add a new command into the MULTI commands queue */
7455 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
) {
7459 c
->mstate
.commands
= zrealloc(c
->mstate
.commands
,
7460 sizeof(multiCmd
)*(c
->mstate
.count
+1));
7461 mc
= c
->mstate
.commands
+c
->mstate
.count
;
7464 mc
->argv
= zmalloc(sizeof(robj
*)*c
->argc
);
7465 memcpy(mc
->argv
,c
->argv
,sizeof(robj
*)*c
->argc
);
7466 for (j
= 0; j
< c
->argc
; j
++)
7467 incrRefCount(mc
->argv
[j
]);
7471 static void multiCommand(redisClient
*c
) {
7472 c
->flags
|= REDIS_MULTI
;
7473 addReply(c
,shared
.ok
);
7476 static void discardCommand(redisClient
*c
) {
7477 if (!(c
->flags
& REDIS_MULTI
)) {
7478 addReplySds(c
,sdsnew("-ERR DISCARD without MULTI\r\n"));
7482 freeClientMultiState(c
);
7483 initClientMultiState(c
);
7484 c
->flags
&= (~REDIS_MULTI
);
7485 addReply(c
,shared
.ok
);
7488 /* Send a MULTI command to all the slaves and AOF file. Check the execCommand
7489 * implememntation for more information. */
7490 static void execCommandReplicateMulti(redisClient
*c
) {
7491 struct redisCommand
*cmd
;
7492 robj
*multistring
= createStringObject("MULTI",5);
7494 cmd
= lookupCommand("multi");
7495 if (server
.appendonly
)
7496 feedAppendOnlyFile(cmd
,c
->db
->id
,&multistring
,1);
7497 if (listLength(server
.slaves
))
7498 replicationFeedSlaves(server
.slaves
,c
->db
->id
,&multistring
,1);
7499 decrRefCount(multistring
);
7502 static void execCommand(redisClient
*c
) {
7507 if (!(c
->flags
& REDIS_MULTI
)) {
7508 addReplySds(c
,sdsnew("-ERR EXEC without MULTI\r\n"));
7512 /* Replicate a MULTI request now that we are sure the block is executed.
7513 * This way we'll deliver the MULTI/..../EXEC block as a whole and
7514 * both the AOF and the replication link will have the same consistency
7515 * and atomicity guarantees. */
7516 execCommandReplicateMulti(c
);
7518 /* Exec all the queued commands */
7519 orig_argv
= c
->argv
;
7520 orig_argc
= c
->argc
;
7521 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->mstate
.count
));
7522 for (j
= 0; j
< c
->mstate
.count
; j
++) {
7523 c
->argc
= c
->mstate
.commands
[j
].argc
;
7524 c
->argv
= c
->mstate
.commands
[j
].argv
;
7525 call(c
,c
->mstate
.commands
[j
].cmd
);
7527 c
->argv
= orig_argv
;
7528 c
->argc
= orig_argc
;
7529 freeClientMultiState(c
);
7530 initClientMultiState(c
);
7531 c
->flags
&= (~REDIS_MULTI
);
7532 /* Make sure the EXEC command is always replicated / AOF, since we
7533 * always send the MULTI command (we can't know beforehand if the
7534 * next operations will contain at least a modification to the DB). */
7538 /* =========================== Blocking Operations ========================= */
7540 /* Currently Redis blocking operations support is limited to list POP ops,
7541 * so the current implementation is not fully generic, but it is also not
7542 * completely specific so it will not require a rewrite to support new
7543 * kind of blocking operations in the future.
7545 * Still it's important to note that list blocking operations can be already
7546 * used as a notification mechanism in order to implement other blocking
7547 * operations at application level, so there must be a very strong evidence
7548 * of usefulness and generality before new blocking operations are implemented.
7550 * This is how the current blocking POP works, we use BLPOP as example:
7551 * - If the user calls BLPOP and the key exists and contains a non empty list
7552 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
7553 * if there is not to block.
7554 * - If instead BLPOP is called and the key does not exists or the list is
7555 * empty we need to block. In order to do so we remove the notification for
7556 * new data to read in the client socket (so that we'll not serve new
7557 * requests if the blocking request is not served). Also we put the client
7558 * in a dictionary (db->blockingkeys) mapping keys to a list of clients
7559 * blocking for this keys.
7560 * - If a PUSH operation against a key with blocked clients waiting is
7561 * performed, we serve the first in the list: basically instead to push
7562 * the new element inside the list we return it to the (first / oldest)
7563 * blocking client, unblock the client, and remove it form the list.
7565 * The above comment and the source code should be enough in order to understand
7566 * the implementation and modify / fix it later.
7569 /* Set a client in blocking mode for the specified key, with the specified
7571 static void blockForKeys(redisClient
*c
, robj
**keys
, int numkeys
, time_t timeout
) {
7576 c
->blockingkeys
= zmalloc(sizeof(robj
*)*numkeys
);
7577 c
->blockingkeysnum
= numkeys
;
7578 c
->blockingto
= timeout
;
7579 for (j
= 0; j
< numkeys
; j
++) {
7580 /* Add the key in the client structure, to map clients -> keys */
7581 c
->blockingkeys
[j
] = keys
[j
];
7582 incrRefCount(keys
[j
]);
7584 /* And in the other "side", to map keys -> clients */
7585 de
= dictFind(c
->db
->blockingkeys
,keys
[j
]);
7589 /* For every key we take a list of clients blocked for it */
7591 retval
= dictAdd(c
->db
->blockingkeys
,keys
[j
],l
);
7592 incrRefCount(keys
[j
]);
7593 assert(retval
== DICT_OK
);
7595 l
= dictGetEntryVal(de
);
7597 listAddNodeTail(l
,c
);
7599 /* Mark the client as a blocked client */
7600 c
->flags
|= REDIS_BLOCKED
;
7601 server
.blpop_blocked_clients
++;
7604 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
7605 static void unblockClientWaitingData(redisClient
*c
) {
7610 assert(c
->blockingkeys
!= NULL
);
7611 /* The client may wait for multiple keys, so unblock it for every key. */
7612 for (j
= 0; j
< c
->blockingkeysnum
; j
++) {
7613 /* Remove this client from the list of clients waiting for this key. */
7614 de
= dictFind(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
7616 l
= dictGetEntryVal(de
);
7617 listDelNode(l
,listSearchKey(l
,c
));
7618 /* If the list is empty we need to remove it to avoid wasting memory */
7619 if (listLength(l
) == 0)
7620 dictDelete(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
7621 decrRefCount(c
->blockingkeys
[j
]);
7623 /* Cleanup the client structure */
7624 zfree(c
->blockingkeys
);
7625 c
->blockingkeys
= NULL
;
7626 c
->flags
&= (~REDIS_BLOCKED
);
7627 server
.blpop_blocked_clients
--;
7628 /* We want to process data if there is some command waiting
7629 * in the input buffer. Note that this is safe even if
7630 * unblockClientWaitingData() gets called from freeClient() because
7631 * freeClient() will be smart enough to call this function
7632 * *after* c->querybuf was set to NULL. */
7633 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0) processInputBuffer(c
);
7636 /* This should be called from any function PUSHing into lists.
7637 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
7638 * 'ele' is the element pushed.
7640 * If the function returns 0 there was no client waiting for a list push
7643 * If the function returns 1 there was a client waiting for a list push
7644 * against this key, the element was passed to this client thus it's not
7645 * needed to actually add it to the list and the caller should return asap. */
7646 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
) {
7647 struct dictEntry
*de
;
7648 redisClient
*receiver
;
7652 de
= dictFind(c
->db
->blockingkeys
,key
);
7653 if (de
== NULL
) return 0;
7654 l
= dictGetEntryVal(de
);
7657 receiver
= ln
->value
;
7659 addReplySds(receiver
,sdsnew("*2\r\n"));
7660 addReplyBulk(receiver
,key
);
7661 addReplyBulk(receiver
,ele
);
7662 unblockClientWaitingData(receiver
);
7666 /* Blocking RPOP/LPOP */
7667 static void blockingPopGenericCommand(redisClient
*c
, int where
) {
7672 for (j
= 1; j
< c
->argc
-1; j
++) {
7673 o
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
7675 if (o
->type
!= REDIS_LIST
) {
7676 addReply(c
,shared
.wrongtypeerr
);
7679 list
*list
= o
->ptr
;
7680 if (listLength(list
) != 0) {
7681 /* If the list contains elements fall back to the usual
7682 * non-blocking POP operation */
7683 robj
*argv
[2], **orig_argv
;
7686 /* We need to alter the command arguments before to call
7687 * popGenericCommand() as the command takes a single key. */
7688 orig_argv
= c
->argv
;
7689 orig_argc
= c
->argc
;
7690 argv
[1] = c
->argv
[j
];
7694 /* Also the return value is different, we need to output
7695 * the multi bulk reply header and the key name. The
7696 * "real" command will add the last element (the value)
7697 * for us. If this souds like an hack to you it's just
7698 * because it is... */
7699 addReplySds(c
,sdsnew("*2\r\n"));
7700 addReplyBulk(c
,argv
[1]);
7701 popGenericCommand(c
,where
);
7703 /* Fix the client structure with the original stuff */
7704 c
->argv
= orig_argv
;
7705 c
->argc
= orig_argc
;
7711 /* If the list is empty or the key does not exists we must block */
7712 timeout
= strtol(c
->argv
[c
->argc
-1]->ptr
,NULL
,10);
7713 if (timeout
> 0) timeout
+= time(NULL
);
7714 blockForKeys(c
,c
->argv
+1,c
->argc
-2,timeout
);
7717 static void blpopCommand(redisClient
*c
) {
7718 blockingPopGenericCommand(c
,REDIS_HEAD
);
7721 static void brpopCommand(redisClient
*c
) {
7722 blockingPopGenericCommand(c
,REDIS_TAIL
);
7725 /* =============================== Replication ============================= */
7727 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) {
7728 ssize_t nwritten
, ret
= size
;
7729 time_t start
= time(NULL
);
7733 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
7734 nwritten
= write(fd
,ptr
,size
);
7735 if (nwritten
== -1) return -1;
7739 if ((time(NULL
)-start
) > timeout
) {
7747 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) {
7748 ssize_t nread
, totread
= 0;
7749 time_t start
= time(NULL
);
7753 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
7754 nread
= read(fd
,ptr
,size
);
7755 if (nread
== -1) return -1;
7760 if ((time(NULL
)-start
) > timeout
) {
7768 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
7775 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
7778 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
7789 static void syncCommand(redisClient
*c
) {
7790 /* ignore SYNC if aleady slave or in monitor mode */
7791 if (c
->flags
& REDIS_SLAVE
) return;
7793 /* SYNC can't be issued when the server has pending data to send to
7794 * the client about already issued commands. We need a fresh reply
7795 * buffer registering the differences between the BGSAVE and the current
7796 * dataset, so that we can copy to other slaves if needed. */
7797 if (listLength(c
->reply
) != 0) {
7798 addReplySds(c
,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
7802 redisLog(REDIS_NOTICE
,"Slave ask for synchronization");
7803 /* Here we need to check if there is a background saving operation
7804 * in progress, or if it is required to start one */
7805 if (server
.bgsavechildpid
!= -1) {
7806 /* Ok a background save is in progress. Let's check if it is a good
7807 * one for replication, i.e. if there is another slave that is
7808 * registering differences since the server forked to save */
7813 listRewind(server
.slaves
,&li
);
7814 while((ln
= listNext(&li
))) {
7816 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) break;
7819 /* Perfect, the server is already registering differences for
7820 * another slave. Set the right state, and copy the buffer. */
7821 listRelease(c
->reply
);
7822 c
->reply
= listDup(slave
->reply
);
7823 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
7824 redisLog(REDIS_NOTICE
,"Waiting for end of BGSAVE for SYNC");
7826 /* No way, we need to wait for the next BGSAVE in order to
7827 * register differences */
7828 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
7829 redisLog(REDIS_NOTICE
,"Waiting for next BGSAVE for SYNC");
7832 /* Ok we don't have a BGSAVE in progress, let's start one */
7833 redisLog(REDIS_NOTICE
,"Starting BGSAVE for SYNC");
7834 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
7835 redisLog(REDIS_NOTICE
,"Replication failed, can't BGSAVE");
7836 addReplySds(c
,sdsnew("-ERR Unalbe to perform background save\r\n"));
7839 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
7842 c
->flags
|= REDIS_SLAVE
;
7844 listAddNodeTail(server
.slaves
,c
);
7848 static void sendBulkToSlave(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
7849 redisClient
*slave
= privdata
;
7851 REDIS_NOTUSED(mask
);
7852 char buf
[REDIS_IOBUF_LEN
];
7853 ssize_t nwritten
, buflen
;
7855 if (slave
->repldboff
== 0) {
7856 /* Write the bulk write count before to transfer the DB. In theory here
7857 * we don't know how much room there is in the output buffer of the
7858 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
7859 * operations) will never be smaller than the few bytes we need. */
7862 bulkcount
= sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
7864 if (write(fd
,bulkcount
,sdslen(bulkcount
)) != (signed)sdslen(bulkcount
))
7872 lseek(slave
->repldbfd
,slave
->repldboff
,SEEK_SET
);
7873 buflen
= read(slave
->repldbfd
,buf
,REDIS_IOBUF_LEN
);
7875 redisLog(REDIS_WARNING
,"Read error sending DB to slave: %s",
7876 (buflen
== 0) ? "premature EOF" : strerror(errno
));
7880 if ((nwritten
= write(fd
,buf
,buflen
)) == -1) {
7881 redisLog(REDIS_VERBOSE
,"Write error sending DB to slave: %s",
7886 slave
->repldboff
+= nwritten
;
7887 if (slave
->repldboff
== slave
->repldbsize
) {
7888 close(slave
->repldbfd
);
7889 slave
->repldbfd
= -1;
7890 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
7891 slave
->replstate
= REDIS_REPL_ONLINE
;
7892 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
,
7893 sendReplyToClient
, slave
) == AE_ERR
) {
7897 addReplySds(slave
,sdsempty());
7898 redisLog(REDIS_NOTICE
,"Synchronization with slave succeeded");
7902 /* This function is called at the end of every backgrond saving.
7903 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
7904 * otherwise REDIS_ERR is passed to the function.
7906 * The goal of this function is to handle slaves waiting for a successful
7907 * background saving in order to perform non-blocking synchronization. */
7908 static void updateSlavesWaitingBgsave(int bgsaveerr
) {
7910 int startbgsave
= 0;
7913 listRewind(server
.slaves
,&li
);
7914 while((ln
= listNext(&li
))) {
7915 redisClient
*slave
= ln
->value
;
7917 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) {
7919 slave
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
7920 } else if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) {
7921 struct redis_stat buf
;
7923 if (bgsaveerr
!= REDIS_OK
) {
7925 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE child returned an error");
7928 if ((slave
->repldbfd
= open(server
.dbfilename
,O_RDONLY
)) == -1 ||
7929 redis_fstat(slave
->repldbfd
,&buf
) == -1) {
7931 redisLog(REDIS_WARNING
,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno
));
7934 slave
->repldboff
= 0;
7935 slave
->repldbsize
= buf
.st_size
;
7936 slave
->replstate
= REDIS_REPL_SEND_BULK
;
7937 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
7938 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
, sendBulkToSlave
, slave
) == AE_ERR
) {
7945 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
7948 listRewind(server
.slaves
,&li
);
7949 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE failed");
7950 while((ln
= listNext(&li
))) {
7951 redisClient
*slave
= ln
->value
;
7953 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
)
7960 static int syncWithMaster(void) {
7961 char buf
[1024], tmpfile
[256], authcmd
[1024];
7963 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
7964 int dfd
, maxtries
= 5;
7967 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
7972 /* AUTH with the master if required. */
7973 if(server
.masterauth
) {
7974 snprintf(authcmd
, 1024, "AUTH %s\r\n", server
.masterauth
);
7975 if (syncWrite(fd
, authcmd
, strlen(server
.masterauth
)+7, 5) == -1) {
7977 redisLog(REDIS_WARNING
,"Unable to AUTH to MASTER: %s",
7981 /* Read the AUTH result. */
7982 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
7984 redisLog(REDIS_WARNING
,"I/O error reading auth result from MASTER: %s",
7988 if (buf
[0] != '+') {
7990 redisLog(REDIS_WARNING
,"Cannot AUTH to MASTER, is the masterauth password correct?");
7995 /* Issue the SYNC command */
7996 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
7998 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
8002 /* Read the bulk write count */
8003 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
8005 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
8009 if (buf
[0] != '$') {
8011 redisLog(REDIS_WARNING
,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
8014 dumpsize
= strtol(buf
+1,NULL
,10);
8015 redisLog(REDIS_NOTICE
,"Receiving %ld bytes data dump from MASTER",dumpsize
);
8016 /* Read the bulk write data on a temp file */
8018 snprintf(tmpfile
,256,
8019 "temp-%d.%ld.rdb",(int)time(NULL
),(long int)getpid());
8020 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
|O_EXCL
,0644);
8021 if (dfd
!= -1) break;
8026 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
8030 int nread
, nwritten
;
8032 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
8034 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
8040 nwritten
= write(dfd
,buf
,nread
);
8041 if (nwritten
== -1) {
8042 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
8050 if (rename(tmpfile
,server
.dbfilename
) == -1) {
8051 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
8057 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
8058 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
8062 server
.master
= createClient(fd
);
8063 server
.master
->flags
|= REDIS_MASTER
;
8064 server
.master
->authenticated
= 1;
8065 server
.replstate
= REDIS_REPL_CONNECTED
;
8069 static void slaveofCommand(redisClient
*c
) {
8070 if (!strcasecmp(c
->argv
[1]->ptr
,"no") &&
8071 !strcasecmp(c
->argv
[2]->ptr
,"one")) {
8072 if (server
.masterhost
) {
8073 sdsfree(server
.masterhost
);
8074 server
.masterhost
= NULL
;
8075 if (server
.master
) freeClient(server
.master
);
8076 server
.replstate
= REDIS_REPL_NONE
;
8077 redisLog(REDIS_NOTICE
,"MASTER MODE enabled (user request)");
8080 sdsfree(server
.masterhost
);
8081 server
.masterhost
= sdsdup(c
->argv
[1]->ptr
);
8082 server
.masterport
= atoi(c
->argv
[2]->ptr
);
8083 if (server
.master
) freeClient(server
.master
);
8084 server
.replstate
= REDIS_REPL_CONNECT
;
8085 redisLog(REDIS_NOTICE
,"SLAVE OF %s:%d enabled (user request)",
8086 server
.masterhost
, server
.masterport
);
8088 addReply(c
,shared
.ok
);
8091 /* ============================ Maxmemory directive ======================== */
8093 /* Try to free one object form the pre-allocated objects free list.
8094 * This is useful under low mem conditions as by default we take 1 million
8095 * free objects allocated. On success REDIS_OK is returned, otherwise
8097 static int tryFreeOneObjectFromFreelist(void) {
8100 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
8101 if (listLength(server
.objfreelist
)) {
8102 listNode
*head
= listFirst(server
.objfreelist
);
8103 o
= listNodeValue(head
);
8104 listDelNode(server
.objfreelist
,head
);
8105 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
8109 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
8114 /* This function gets called when 'maxmemory' is set on the config file to limit
8115 * the max memory used by the server, and we are out of memory.
8116 * This function will try to, in order:
8118 * - Free objects from the free list
8119 * - Try to remove keys with an EXPIRE set
8121 * It is not possible to free enough memory to reach used-memory < maxmemory
8122 * the server will start refusing commands that will enlarge even more the
8125 static void freeMemoryIfNeeded(void) {
8126 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
8127 int j
, k
, freed
= 0;
8129 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
8130 for (j
= 0; j
< server
.dbnum
; j
++) {
8132 robj
*minkey
= NULL
;
8133 struct dictEntry
*de
;
8135 if (dictSize(server
.db
[j
].expires
)) {
8137 /* From a sample of three keys drop the one nearest to
8138 * the natural expire */
8139 for (k
= 0; k
< 3; k
++) {
8142 de
= dictGetRandomKey(server
.db
[j
].expires
);
8143 t
= (time_t) dictGetEntryVal(de
);
8144 if (minttl
== -1 || t
< minttl
) {
8145 minkey
= dictGetEntryKey(de
);
8149 deleteKey(server
.db
+j
,minkey
);
8152 if (!freed
) return; /* nothing to free... */
8156 /* ============================== Append Only file ========================== */
8158 /* Write the append only file buffer on disk.
8160 * Since we are required to write the AOF before replying to the client,
8161 * and the only way the client socket can get a write is entering when the
8162 * the event loop, we accumulate all the AOF writes in a memory
8163 * buffer and write it on disk using this function just before entering
8164 * the event loop again. */
8165 static void flushAppendOnlyFile(void) {
8169 if (sdslen(server
.aofbuf
) == 0) return;
8171 /* We want to perform a single write. This should be guaranteed atomic
8172 * at least if the filesystem we are writing is a real physical one.
8173 * While this will save us against the server being killed I don't think
8174 * there is much to do about the whole server stopping for power problems
8176 nwritten
= write(server
.appendfd
,server
.aofbuf
,sdslen(server
.aofbuf
));
8177 if (nwritten
!= (signed)sdslen(server
.aofbuf
)) {
8178 /* Ooops, we are in troubles. The best thing to do for now is
8179 * aborting instead of giving the illusion that everything is
8180 * working as expected. */
8181 if (nwritten
== -1) {
8182 redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
));
8184 redisLog(REDIS_WARNING
,"Exiting on short write while writing to the append-only file: %s",strerror(errno
));
8188 sdsfree(server
.aofbuf
);
8189 server
.aofbuf
= sdsempty();
8191 /* Fsync if needed */
8193 if (server
.appendfsync
== APPENDFSYNC_ALWAYS
||
8194 (server
.appendfsync
== APPENDFSYNC_EVERYSEC
&&
8195 now
-server
.lastfsync
> 1))
8197 /* aof_fsync is defined as fdatasync() for Linux in order to avoid
8198 * flushing metadata. */
8199 aof_fsync(server
.appendfd
); /* Let's try to get this data on the disk */
8200 server
.lastfsync
= now
;
8204 static sds
catAppendOnlyGenericCommand(sds buf
, int argc
, robj
**argv
) {
8206 buf
= sdscatprintf(buf
,"*%d\r\n",argc
);
8207 for (j
= 0; j
< argc
; j
++) {
8208 robj
*o
= getDecodedObject(argv
[j
]);
8209 buf
= sdscatprintf(buf
,"$%lu\r\n",(unsigned long)sdslen(o
->ptr
));
8210 buf
= sdscatlen(buf
,o
->ptr
,sdslen(o
->ptr
));
8211 buf
= sdscatlen(buf
,"\r\n",2);
8217 static sds
catAppendOnlyExpireAtCommand(sds buf
, robj
*key
, robj
*seconds
) {
8222 /* Make sure we can use strtol */
8223 seconds
= getDecodedObject(seconds
);
8224 when
= time(NULL
)+strtol(seconds
->ptr
,NULL
,10);
8225 decrRefCount(seconds
);
8227 argv
[0] = createStringObject("EXPIREAT",8);
8229 argv
[2] = createObject(REDIS_STRING
,
8230 sdscatprintf(sdsempty(),"%ld",when
));
8231 buf
= catAppendOnlyGenericCommand(buf
, argc
, argv
);
8232 decrRefCount(argv
[0]);
8233 decrRefCount(argv
[2]);
8237 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
8238 sds buf
= sdsempty();
8241 /* The DB this command was targetting is not the same as the last command
8242 * we appendend. To issue a SELECT command is needed. */
8243 if (dictid
!= server
.appendseldb
) {
8246 snprintf(seldb
,sizeof(seldb
),"%d",dictid
);
8247 buf
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
8248 (unsigned long)strlen(seldb
),seldb
);
8249 server
.appendseldb
= dictid
;
8252 if (cmd
->proc
== expireCommand
) {
8253 /* Translate EXPIRE into EXPIREAT */
8254 buf
= catAppendOnlyExpireAtCommand(buf
,argv
[1],argv
[2]);
8255 } else if (cmd
->proc
== setexCommand
) {
8256 /* Translate SETEX to SET and EXPIREAT */
8257 tmpargv
[0] = createStringObject("SET",3);
8258 tmpargv
[1] = argv
[1];
8259 tmpargv
[2] = argv
[3];
8260 buf
= catAppendOnlyGenericCommand(buf
,3,tmpargv
);
8261 decrRefCount(tmpargv
[0]);
8262 buf
= catAppendOnlyExpireAtCommand(buf
,argv
[1],argv
[2]);
8264 buf
= catAppendOnlyGenericCommand(buf
,argc
,argv
);
8267 /* Append to the AOF buffer. This will be flushed on disk just before
8268 * of re-entering the event loop, so before the client will get a
8269 * positive reply about the operation performed. */
8270 server
.aofbuf
= sdscatlen(server
.aofbuf
,buf
,sdslen(buf
));
8272 /* If a background append only file rewriting is in progress we want to
8273 * accumulate the differences between the child DB and the current one
8274 * in a buffer, so that when the child process will do its work we
8275 * can append the differences to the new append only file. */
8276 if (server
.bgrewritechildpid
!= -1)
8277 server
.bgrewritebuf
= sdscatlen(server
.bgrewritebuf
,buf
,sdslen(buf
));
8282 /* In Redis commands are always executed in the context of a client, so in
8283 * order to load the append only file we need to create a fake client. */
8284 static struct redisClient
*createFakeClient(void) {
8285 struct redisClient
*c
= zmalloc(sizeof(*c
));
8289 c
->querybuf
= sdsempty();
8293 /* We set the fake client as a slave waiting for the synchronization
8294 * so that Redis will not try to send replies to this client. */
8295 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
8296 c
->reply
= listCreate();
8297 listSetFreeMethod(c
->reply
,decrRefCount
);
8298 listSetDupMethod(c
->reply
,dupClientReplyValue
);
8299 initClientMultiState(c
);
8303 static void freeFakeClient(struct redisClient
*c
) {
8304 sdsfree(c
->querybuf
);
8305 listRelease(c
->reply
);
8306 freeClientMultiState(c
);
8310 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
8311 * error (the append only file is zero-length) REDIS_ERR is returned. On
8312 * fatal error an error message is logged and the program exists. */
8313 int loadAppendOnlyFile(char *filename
) {
8314 struct redisClient
*fakeClient
;
8315 FILE *fp
= fopen(filename
,"r");
8316 struct redis_stat sb
;
8317 unsigned long long loadedkeys
= 0;
8318 int appendonly
= server
.appendonly
;
8320 if (redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0)
8324 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
8328 /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
8329 * to the same file we're about to read. */
8330 server
.appendonly
= 0;
8332 fakeClient
= createFakeClient();
8339 struct redisCommand
*cmd
;
8341 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
8347 if (buf
[0] != '*') goto fmterr
;
8349 argv
= zmalloc(sizeof(robj
*)*argc
);
8350 for (j
= 0; j
< argc
; j
++) {
8351 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
8352 if (buf
[0] != '$') goto fmterr
;
8353 len
= strtol(buf
+1,NULL
,10);
8354 argsds
= sdsnewlen(NULL
,len
);
8355 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
8356 argv
[j
] = createObject(REDIS_STRING
,argsds
);
8357 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
8360 /* Command lookup */
8361 cmd
= lookupCommand(argv
[0]->ptr
);
8363 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
8366 /* Try object encoding */
8367 if (cmd
->flags
& REDIS_CMD_BULK
)
8368 argv
[argc
-1] = tryObjectEncoding(argv
[argc
-1]);
8369 /* Run the command in the context of a fake client */
8370 fakeClient
->argc
= argc
;
8371 fakeClient
->argv
= argv
;
8372 cmd
->proc(fakeClient
);
8373 /* Discard the reply objects list from the fake client */
8374 while(listLength(fakeClient
->reply
))
8375 listDelNode(fakeClient
->reply
,listFirst(fakeClient
->reply
));
8376 /* Clean up, ready for the next command */
8377 for (j
= 0; j
< argc
; j
++) decrRefCount(argv
[j
]);
8379 /* Handle swapping while loading big datasets when VM is on */
8381 if (server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
8382 while (zmalloc_used_memory() > server
.vm_max_memory
) {
8383 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
8388 /* This point can only be reached when EOF is reached without errors.
8389 * If the client is in the middle of a MULTI/EXEC, log error and quit. */
8390 if (fakeClient
->flags
& REDIS_MULTI
) goto readerr
;
8393 freeFakeClient(fakeClient
);
8394 server
.appendonly
= appendonly
;
8399 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
8401 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
8405 redisLog(REDIS_WARNING
,"Bad file format reading the append only file");
8409 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
8410 static int fwriteBulkObject(FILE *fp
, robj
*obj
) {
8414 /* Avoid the incr/decr ref count business if possible to help
8415 * copy-on-write (we are often in a child process when this function
8417 * Also makes sure that key objects don't get incrRefCount-ed when VM
8419 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
8420 obj
= getDecodedObject(obj
);
8423 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(long)sdslen(obj
->ptr
));
8424 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) goto err
;
8425 if (sdslen(obj
->ptr
) && fwrite(obj
->ptr
,sdslen(obj
->ptr
),1,fp
) == 0)
8427 if (fwrite("\r\n",2,1,fp
) == 0) goto err
;
8428 if (decrrc
) decrRefCount(obj
);
8431 if (decrrc
) decrRefCount(obj
);
8435 /* Write binary-safe string into a file in the bulkformat
8436 * $<count>\r\n<payload>\r\n */
8437 static int fwriteBulkString(FILE *fp
, char *s
, unsigned long len
) {
8440 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(unsigned long)len
);
8441 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
8442 if (len
&& fwrite(s
,len
,1,fp
) == 0) return 0;
8443 if (fwrite("\r\n",2,1,fp
) == 0) return 0;
8447 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
8448 static int fwriteBulkDouble(FILE *fp
, double d
) {
8449 char buf
[128], dbuf
[128];
8451 snprintf(dbuf
,sizeof(dbuf
),"%.17g\r\n",d
);
8452 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(dbuf
)-2);
8453 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
8454 if (fwrite(dbuf
,strlen(dbuf
),1,fp
) == 0) return 0;
8458 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
8459 static int fwriteBulkLong(FILE *fp
, long l
) {
8460 char buf
[128], lbuf
[128];
8462 snprintf(lbuf
,sizeof(lbuf
),"%ld\r\n",l
);
8463 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(lbuf
)-2);
8464 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
8465 if (fwrite(lbuf
,strlen(lbuf
),1,fp
) == 0) return 0;
8469 /* Write a sequence of commands able to fully rebuild the dataset into
8470 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
8471 static int rewriteAppendOnlyFile(char *filename
) {
8472 dictIterator
*di
= NULL
;
8477 time_t now
= time(NULL
);
8479 /* Note that we have to use a different temp name here compared to the
8480 * one used by rewriteAppendOnlyFileBackground() function. */
8481 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
8482 fp
= fopen(tmpfile
,"w");
8484 redisLog(REDIS_WARNING
, "Failed rewriting the append only file: %s", strerror(errno
));
8487 for (j
= 0; j
< server
.dbnum
; j
++) {
8488 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
8489 redisDb
*db
= server
.db
+j
;
8491 if (dictSize(d
) == 0) continue;
8492 di
= dictGetIterator(d
);
8498 /* SELECT the new DB */
8499 if (fwrite(selectcmd
,sizeof(selectcmd
)-1,1,fp
) == 0) goto werr
;
8500 if (fwriteBulkLong(fp
,j
) == 0) goto werr
;
8502 /* Iterate this DB writing every entry */
8503 while((de
= dictNext(di
)) != NULL
) {
8508 key
= dictGetEntryKey(de
);
8509 /* If the value for this key is swapped, load a preview in memory.
8510 * We use a "swapped" flag to remember if we need to free the
8511 * value object instead to just increment the ref count anyway
8512 * in order to avoid copy-on-write of pages if we are forked() */
8513 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
8514 key
->storage
== REDIS_VM_SWAPPING
) {
8515 o
= dictGetEntryVal(de
);
8518 o
= vmPreviewObject(key
);
8521 expiretime
= getExpire(db
,key
);
8523 /* Save the key and associated value */
8524 if (o
->type
== REDIS_STRING
) {
8525 /* Emit a SET command */
8526 char cmd
[]="*3\r\n$3\r\nSET\r\n";
8527 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8529 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8530 if (fwriteBulkObject(fp
,o
) == 0) goto werr
;
8531 } else if (o
->type
== REDIS_LIST
) {
8532 /* Emit the RPUSHes needed to rebuild the list */
8533 list
*list
= o
->ptr
;
8537 listRewind(list
,&li
);
8538 while((ln
= listNext(&li
))) {
8539 char cmd
[]="*3\r\n$5\r\nRPUSH\r\n";
8540 robj
*eleobj
= listNodeValue(ln
);
8542 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8543 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8544 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
8546 } else if (o
->type
== REDIS_SET
) {
8547 /* Emit the SADDs needed to rebuild the set */
8549 dictIterator
*di
= dictGetIterator(set
);
8552 while((de
= dictNext(di
)) != NULL
) {
8553 char cmd
[]="*3\r\n$4\r\nSADD\r\n";
8554 robj
*eleobj
= dictGetEntryKey(de
);
8556 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8557 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8558 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
8560 dictReleaseIterator(di
);
8561 } else if (o
->type
== REDIS_ZSET
) {
8562 /* Emit the ZADDs needed to rebuild the sorted set */
8564 dictIterator
*di
= dictGetIterator(zs
->dict
);
8567 while((de
= dictNext(di
)) != NULL
) {
8568 char cmd
[]="*4\r\n$4\r\nZADD\r\n";
8569 robj
*eleobj
= dictGetEntryKey(de
);
8570 double *score
= dictGetEntryVal(de
);
8572 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8573 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8574 if (fwriteBulkDouble(fp
,*score
) == 0) goto werr
;
8575 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
8577 dictReleaseIterator(di
);
8578 } else if (o
->type
== REDIS_HASH
) {
8579 char cmd
[]="*4\r\n$4\r\nHSET\r\n";
8581 /* Emit the HSETs needed to rebuild the hash */
8582 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
8583 unsigned char *p
= zipmapRewind(o
->ptr
);
8584 unsigned char *field
, *val
;
8585 unsigned int flen
, vlen
;
8587 while((p
= zipmapNext(p
,&field
,&flen
,&val
,&vlen
)) != NULL
) {
8588 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8589 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8590 if (fwriteBulkString(fp
,(char*)field
,flen
) == -1)
8592 if (fwriteBulkString(fp
,(char*)val
,vlen
) == -1)
8596 dictIterator
*di
= dictGetIterator(o
->ptr
);
8599 while((de
= dictNext(di
)) != NULL
) {
8600 robj
*field
= dictGetEntryKey(de
);
8601 robj
*val
= dictGetEntryVal(de
);
8603 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8604 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8605 if (fwriteBulkObject(fp
,field
) == -1) return -1;
8606 if (fwriteBulkObject(fp
,val
) == -1) return -1;
8608 dictReleaseIterator(di
);
8611 redisPanic("Unknown object type");
8613 /* Save the expire time */
8614 if (expiretime
!= -1) {
8615 char cmd
[]="*3\r\n$8\r\nEXPIREAT\r\n";
8616 /* If this key is already expired skip it */
8617 if (expiretime
< now
) continue;
8618 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8619 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8620 if (fwriteBulkLong(fp
,expiretime
) == 0) goto werr
;
8622 if (swapped
) decrRefCount(o
);
8624 dictReleaseIterator(di
);
8627 /* Make sure data will not remain on the OS's output buffers */
8632 /* Use RENAME to make sure the DB file is changed atomically only
8633 * if the generate DB file is ok. */
8634 if (rename(tmpfile
,filename
) == -1) {
8635 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
8639 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
8645 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
8646 if (di
) dictReleaseIterator(di
);
8650 /* This is how rewriting of the append only file in background works:
8652 * 1) The user calls BGREWRITEAOF
8653 * 2) Redis calls this function, that forks():
8654 * 2a) the child rewrite the append only file in a temp file.
8655 * 2b) the parent accumulates differences in server.bgrewritebuf.
8656 * 3) When the child finished '2a' exists.
8657 * 4) The parent will trap the exit code, if it's OK, will append the
8658 * data accumulated into server.bgrewritebuf into the temp file, and
8659 * finally will rename(2) the temp file in the actual file name.
8660 * The the new file is reopened as the new append only file. Profit!
8662 static int rewriteAppendOnlyFileBackground(void) {
8665 if (server
.bgrewritechildpid
!= -1) return REDIS_ERR
;
8666 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
8667 if ((childpid
= fork()) == 0) {
8671 if (server
.vm_enabled
) vmReopenSwapFile();
8673 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
8674 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
8681 if (childpid
== -1) {
8682 redisLog(REDIS_WARNING
,
8683 "Can't rewrite append only file in background: fork: %s",
8687 redisLog(REDIS_NOTICE
,
8688 "Background append only file rewriting started by pid %d",childpid
);
8689 server
.bgrewritechildpid
= childpid
;
8690 updateDictResizePolicy();
8691 /* We set appendseldb to -1 in order to force the next call to the
8692 * feedAppendOnlyFile() to issue a SELECT command, so the differences
8693 * accumulated by the parent into server.bgrewritebuf will start
8694 * with a SELECT statement and it will be safe to merge. */
8695 server
.appendseldb
= -1;
8698 return REDIS_OK
; /* unreached */
8701 static void bgrewriteaofCommand(redisClient
*c
) {
8702 if (server
.bgrewritechildpid
!= -1) {
8703 addReplySds(c
,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
8706 if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
8707 char *status
= "+Background append only file rewriting started\r\n";
8708 addReplySds(c
,sdsnew(status
));
8710 addReply(c
,shared
.err
);
8714 static void aofRemoveTempFile(pid_t childpid
) {
8717 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
8721 /* Virtual Memory is composed mainly of two subsystems:
8722 * - Blocking Virutal Memory
8723 * - Threaded Virtual Memory I/O
8724 * The two parts are not fully decoupled, but functions are split among two
8725 * different sections of the source code (delimited by comments) in order to
8726 * make more clear what functionality is about the blocking VM and what about
8727 * the threaded (not blocking) VM.
8731 * Redis VM is a blocking VM (one that blocks reading swapped values from
8732 * disk into memory when a value swapped out is needed in memory) that is made
8733 * unblocking by trying to examine the command argument vector in order to
8734 * load in background values that will likely be needed in order to exec
8735 * the command. The command is executed only once all the relevant keys
8736 * are loaded into memory.
8738 * This basically is almost as simple of a blocking VM, but almost as parallel
8739 * as a fully non-blocking VM.
8742 /* Called when the user switches from "appendonly yes" to "appendonly no"
8743 * at runtime using the CONFIG command. */
8744 static void stopAppendOnly(void) {
8745 flushAppendOnlyFile();
8746 fsync(server
.appendfd
);
8747 close(server
.appendfd
);
8749 server
.appendfd
= -1;
8750 server
.appendseldb
= -1;
8751 server
.appendonly
= 0;
8752 /* rewrite operation in progress? kill it, wait child exit */
8753 if (server
.bgsavechildpid
!= -1) {
8756 if (kill(server
.bgsavechildpid
,SIGKILL
) != -1)
8757 wait3(&statloc
,0,NULL
);
8758 /* reset the buffer accumulating changes while the child saves */
8759 sdsfree(server
.bgrewritebuf
);
8760 server
.bgrewritebuf
= sdsempty();
8761 server
.bgsavechildpid
= -1;
8765 /* Called when the user switches from "appendonly no" to "appendonly yes"
8766 * at runtime using the CONFIG command. */
8767 static int startAppendOnly(void) {
8768 server
.appendonly
= 1;
8769 server
.lastfsync
= time(NULL
);
8770 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
8771 if (server
.appendfd
== -1) {
8772 redisLog(REDIS_WARNING
,"Used tried to switch on AOF via CONFIG, but I can't open the AOF file: %s",strerror(errno
));
8775 if (rewriteAppendOnlyFileBackground() == REDIS_ERR
) {
8776 server
.appendonly
= 0;
8777 close(server
.appendfd
);
8778 redisLog(REDIS_WARNING
,"Used tried to switch on AOF via CONFIG, I can't trigger a background AOF rewrite operation. Check the above logs for more info about the error.",strerror(errno
));
8784 /* =================== Virtual Memory - Blocking Side ====================== */
8786 static void vmInit(void) {
8792 if (server
.vm_max_threads
!= 0)
8793 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
8795 redisLog(REDIS_NOTICE
,"Using '%s' as swap file",server
.vm_swap_file
);
8796 /* Try to open the old swap file, otherwise create it */
8797 if ((server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b")) == NULL
) {
8798 server
.vm_fp
= fopen(server
.vm_swap_file
,"w+b");
8800 if (server
.vm_fp
== NULL
) {
8801 redisLog(REDIS_WARNING
,
8802 "Can't open the swap file: %s. Exiting.",
8806 server
.vm_fd
= fileno(server
.vm_fp
);
8807 /* Lock the swap file for writing, this is useful in order to avoid
8808 * another instance to use the same swap file for a config error. */
8809 fl
.l_type
= F_WRLCK
;
8810 fl
.l_whence
= SEEK_SET
;
8811 fl
.l_start
= fl
.l_len
= 0;
8812 if (fcntl(server
.vm_fd
,F_SETLK
,&fl
) == -1) {
8813 redisLog(REDIS_WARNING
,
8814 "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
));
8818 server
.vm_next_page
= 0;
8819 server
.vm_near_pages
= 0;
8820 server
.vm_stats_used_pages
= 0;
8821 server
.vm_stats_swapped_objects
= 0;
8822 server
.vm_stats_swapouts
= 0;
8823 server
.vm_stats_swapins
= 0;
8824 totsize
= server
.vm_pages
*server
.vm_page_size
;
8825 redisLog(REDIS_NOTICE
,"Allocating %lld bytes of swap file",totsize
);
8826 if (ftruncate(server
.vm_fd
,totsize
) == -1) {
8827 redisLog(REDIS_WARNING
,"Can't ftruncate swap file: %s. Exiting.",
8831 redisLog(REDIS_NOTICE
,"Swap file allocated with success");
8833 server
.vm_bitmap
= zmalloc((server
.vm_pages
+7)/8);
8834 redisLog(REDIS_VERBOSE
,"Allocated %lld bytes page table for %lld pages",
8835 (long long) (server
.vm_pages
+7)/8, server
.vm_pages
);
8836 memset(server
.vm_bitmap
,0,(server
.vm_pages
+7)/8);
8838 /* Initialize threaded I/O (used by Virtual Memory) */
8839 server
.io_newjobs
= listCreate();
8840 server
.io_processing
= listCreate();
8841 server
.io_processed
= listCreate();
8842 server
.io_ready_clients
= listCreate();
8843 pthread_mutex_init(&server
.io_mutex
,NULL
);
8844 pthread_mutex_init(&server
.obj_freelist_mutex
,NULL
);
8845 pthread_mutex_init(&server
.io_swapfile_mutex
,NULL
);
8846 server
.io_active_threads
= 0;
8847 if (pipe(pipefds
) == -1) {
8848 redisLog(REDIS_WARNING
,"Unable to intialized VM: pipe(2): %s. Exiting."
8852 server
.io_ready_pipe_read
= pipefds
[0];
8853 server
.io_ready_pipe_write
= pipefds
[1];
8854 redisAssert(anetNonBlock(NULL
,server
.io_ready_pipe_read
) != ANET_ERR
);
8855 /* LZF requires a lot of stack */
8856 pthread_attr_init(&server
.io_threads_attr
);
8857 pthread_attr_getstacksize(&server
.io_threads_attr
, &stacksize
);
8858 while (stacksize
< REDIS_THREAD_STACK_SIZE
) stacksize
*= 2;
8859 pthread_attr_setstacksize(&server
.io_threads_attr
, stacksize
);
8860 /* Listen for events in the threaded I/O pipe */
8861 if (aeCreateFileEvent(server
.el
, server
.io_ready_pipe_read
, AE_READABLE
,
8862 vmThreadedIOCompletedJob
, NULL
) == AE_ERR
)
8863 oom("creating file event");
8866 /* Mark the page as used */
8867 static void vmMarkPageUsed(off_t page
) {
8868 off_t byte
= page
/8;
8870 redisAssert(vmFreePage(page
) == 1);
8871 server
.vm_bitmap
[byte
] |= 1<<bit
;
8874 /* Mark N contiguous pages as used, with 'page' being the first. */
8875 static void vmMarkPagesUsed(off_t page
, off_t count
) {
8878 for (j
= 0; j
< count
; j
++)
8879 vmMarkPageUsed(page
+j
);
8880 server
.vm_stats_used_pages
+= count
;
8881 redisLog(REDIS_DEBUG
,"Mark USED pages: %lld pages at %lld\n",
8882 (long long)count
, (long long)page
);
8885 /* Mark the page as free */
8886 static void vmMarkPageFree(off_t page
) {
8887 off_t byte
= page
/8;
8889 redisAssert(vmFreePage(page
) == 0);
8890 server
.vm_bitmap
[byte
] &= ~(1<<bit
);
8893 /* Mark N contiguous pages as free, with 'page' being the first. */
8894 static void vmMarkPagesFree(off_t page
, off_t count
) {
8897 for (j
= 0; j
< count
; j
++)
8898 vmMarkPageFree(page
+j
);
8899 server
.vm_stats_used_pages
-= count
;
8900 redisLog(REDIS_DEBUG
,"Mark FREE pages: %lld pages at %lld\n",
8901 (long long)count
, (long long)page
);
8904 /* Test if the page is free */
8905 static int vmFreePage(off_t page
) {
8906 off_t byte
= page
/8;
8908 return (server
.vm_bitmap
[byte
] & (1<<bit
)) == 0;
8911 /* Find N contiguous free pages storing the first page of the cluster in *first.
8912 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
8913 * REDIS_ERR is returned.
8915 * This function uses a simple algorithm: we try to allocate
8916 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
8917 * again from the start of the swap file searching for free spaces.
8919 * If it looks pretty clear that there are no free pages near our offset
8920 * we try to find less populated places doing a forward jump of
8921 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
8922 * without hurry, and then we jump again and so forth...
8924 * This function can be improved using a free list to avoid to guess
8925 * too much, since we could collect data about freed pages.
8927 * note: I implemented this function just after watching an episode of
8928 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
8930 static int vmFindContiguousPages(off_t
*first
, off_t n
) {
8931 off_t base
, offset
= 0, since_jump
= 0, numfree
= 0;
8933 if (server
.vm_near_pages
== REDIS_VM_MAX_NEAR_PAGES
) {
8934 server
.vm_near_pages
= 0;
8935 server
.vm_next_page
= 0;
8937 server
.vm_near_pages
++; /* Yet another try for pages near to the old ones */
8938 base
= server
.vm_next_page
;
8940 while(offset
< server
.vm_pages
) {
8941 off_t
this = base
+offset
;
8943 /* If we overflow, restart from page zero */
8944 if (this >= server
.vm_pages
) {
8945 this -= server
.vm_pages
;
8947 /* Just overflowed, what we found on tail is no longer
8948 * interesting, as it's no longer contiguous. */
8952 if (vmFreePage(this)) {
8953 /* This is a free page */
8955 /* Already got N free pages? Return to the caller, with success */
8957 *first
= this-(n
-1);
8958 server
.vm_next_page
= this+1;
8959 redisLog(REDIS_DEBUG
, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n
, (long long) *first
);
8963 /* The current one is not a free page */
8967 /* Fast-forward if the current page is not free and we already
8968 * searched enough near this place. */
8970 if (!numfree
&& since_jump
>= REDIS_VM_MAX_RANDOM_JUMP
/4) {
8971 offset
+= random() % REDIS_VM_MAX_RANDOM_JUMP
;
8973 /* Note that even if we rewind after the jump, we are don't need
8974 * to make sure numfree is set to zero as we only jump *if* it
8975 * is set to zero. */
8977 /* Otherwise just check the next page */
8984 /* Write the specified object at the specified page of the swap file */
8985 static int vmWriteObjectOnSwap(robj
*o
, off_t page
) {
8986 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
8987 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
8988 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
8989 redisLog(REDIS_WARNING
,
8990 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
8994 rdbSaveObject(server
.vm_fp
,o
);
8995 fflush(server
.vm_fp
);
8996 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
9000 /* Swap the 'val' object relative to 'key' into disk. Store all the information
9001 * needed to later retrieve the object into the key object.
9002 * If we can't find enough contiguous empty pages to swap the object on disk
9003 * REDIS_ERR is returned. */
9004 static int vmSwapObjectBlocking(robj
*key
, robj
*val
) {
9005 off_t pages
= rdbSavedObjectPages(val
,NULL
);
9008 assert(key
->storage
== REDIS_VM_MEMORY
);
9009 assert(key
->refcount
== 1);
9010 if (vmFindContiguousPages(&page
,pages
) == REDIS_ERR
) return REDIS_ERR
;
9011 if (vmWriteObjectOnSwap(val
,page
) == REDIS_ERR
) return REDIS_ERR
;
9012 key
->vm
.page
= page
;
9013 key
->vm
.usedpages
= pages
;
9014 key
->storage
= REDIS_VM_SWAPPED
;
9015 key
->vtype
= val
->type
;
9016 decrRefCount(val
); /* Deallocate the object from memory. */
9017 vmMarkPagesUsed(page
,pages
);
9018 redisLog(REDIS_DEBUG
,"VM: object %s swapped out at %lld (%lld pages)",
9019 (unsigned char*) key
->ptr
,
9020 (unsigned long long) page
, (unsigned long long) pages
);
9021 server
.vm_stats_swapped_objects
++;
9022 server
.vm_stats_swapouts
++;
9026 static robj
*vmReadObjectFromSwap(off_t page
, int type
) {
9029 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
9030 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
9031 redisLog(REDIS_WARNING
,
9032 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
9036 o
= rdbLoadObject(type
,server
.vm_fp
);
9038 redisLog(REDIS_WARNING
, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno
));
9041 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
9045 /* Load the value object relative to the 'key' object from swap to memory.
9046 * The newly allocated object is returned.
9048 * If preview is true the unserialized object is returned to the caller but
9049 * no changes are made to the key object, nor the pages are marked as freed */
9050 static robj
*vmGenericLoadObject(robj
*key
, int preview
) {
9053 redisAssert(key
->storage
== REDIS_VM_SWAPPED
|| key
->storage
== REDIS_VM_LOADING
);
9054 val
= vmReadObjectFromSwap(key
->vm
.page
,key
->vtype
);
9056 key
->storage
= REDIS_VM_MEMORY
;
9057 key
->vm
.atime
= server
.unixtime
;
9058 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
9059 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk",
9060 (unsigned char*) key
->ptr
);
9061 server
.vm_stats_swapped_objects
--;
9063 redisLog(REDIS_DEBUG
, "VM: object %s previewed from disk",
9064 (unsigned char*) key
->ptr
);
9066 server
.vm_stats_swapins
++;
9070 /* Plain object loading, from swap to memory */
9071 static robj
*vmLoadObject(robj
*key
) {
9072 /* If we are loading the object in background, stop it, we
9073 * need to load this object synchronously ASAP. */
9074 if (key
->storage
== REDIS_VM_LOADING
)
9075 vmCancelThreadedIOJob(key
);
9076 return vmGenericLoadObject(key
,0);
9079 /* Just load the value on disk, without to modify the key.
9080 * This is useful when we want to perform some operation on the value
9081 * without to really bring it from swap to memory, like while saving the
9082 * dataset or rewriting the append only log. */
9083 static robj
*vmPreviewObject(robj
*key
) {
9084 return vmGenericLoadObject(key
,1);
9087 /* How a good candidate is this object for swapping?
9088 * The better candidate it is, the greater the returned value.
9090 * Currently we try to perform a fast estimation of the object size in
9091 * memory, and combine it with aging informations.
9093 * Basically swappability = idle-time * log(estimated size)
9095 * Bigger objects are preferred over smaller objects, but not
9096 * proportionally, this is why we use the logarithm. This algorithm is
9097 * just a first try and will probably be tuned later. */
9098 static double computeObjectSwappability(robj
*o
) {
9099 time_t age
= server
.unixtime
- o
->vm
.atime
;
9103 struct dictEntry
*de
;
9106 if (age
<= 0) return 0;
9109 if (o
->encoding
!= REDIS_ENCODING_RAW
) {
9112 asize
= sdslen(o
->ptr
)+sizeof(*o
)+sizeof(long)*2;
9117 listNode
*ln
= listFirst(l
);
9119 asize
= sizeof(list
);
9121 robj
*ele
= ln
->value
;
9124 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
9125 (sizeof(*o
)+sdslen(ele
->ptr
)) :
9127 asize
+= (sizeof(listNode
)+elesize
)*listLength(l
);
9132 z
= (o
->type
== REDIS_ZSET
);
9133 d
= z
? ((zset
*)o
->ptr
)->dict
: o
->ptr
;
9135 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
9136 if (z
) asize
+= sizeof(zset
)-sizeof(dict
);
9141 de
= dictGetRandomKey(d
);
9142 ele
= dictGetEntryKey(de
);
9143 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
9144 (sizeof(*o
)+sdslen(ele
->ptr
)) :
9146 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
9147 if (z
) asize
+= sizeof(zskiplistNode
)*dictSize(d
);
9151 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
9152 unsigned char *p
= zipmapRewind((unsigned char*)o
->ptr
);
9153 unsigned int len
= zipmapLen((unsigned char*)o
->ptr
);
9154 unsigned int klen
, vlen
;
9155 unsigned char *key
, *val
;
9157 if ((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) == NULL
) {
9161 asize
= len
*(klen
+vlen
+3);
9162 } else if (o
->encoding
== REDIS_ENCODING_HT
) {
9164 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
9169 de
= dictGetRandomKey(d
);
9170 ele
= dictGetEntryKey(de
);
9171 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
9172 (sizeof(*o
)+sdslen(ele
->ptr
)) :
9174 ele
= dictGetEntryVal(de
);
9175 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
9176 (sizeof(*o
)+sdslen(ele
->ptr
)) :
9178 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
9183 return (double)age
*log(1+asize
);
9186 /* Try to swap an object that's a good candidate for swapping.
9187 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
9188 * to swap any object at all.
9190 * If 'usethreaded' is true, Redis will try to swap the object in background
9191 * using I/O threads. */
9192 static int vmSwapOneObject(int usethreads
) {
9194 struct dictEntry
*best
= NULL
;
9195 double best_swappability
= 0;
9196 redisDb
*best_db
= NULL
;
9199 for (j
= 0; j
< server
.dbnum
; j
++) {
9200 redisDb
*db
= server
.db
+j
;
9201 /* Why maxtries is set to 100?
9202 * Because this way (usually) we'll find 1 object even if just 1% - 2%
9203 * are swappable objects */
9206 if (dictSize(db
->dict
) == 0) continue;
9207 for (i
= 0; i
< 5; i
++) {
9209 double swappability
;
9211 if (maxtries
) maxtries
--;
9212 de
= dictGetRandomKey(db
->dict
);
9213 key
= dictGetEntryKey(de
);
9214 val
= dictGetEntryVal(de
);
9215 /* Only swap objects that are currently in memory.
9217 * Also don't swap shared objects if threaded VM is on, as we
9218 * try to ensure that the main thread does not touch the
9219 * object while the I/O thread is using it, but we can't
9220 * control other keys without adding additional mutex. */
9221 if (key
->storage
!= REDIS_VM_MEMORY
||
9222 (server
.vm_max_threads
!= 0 && val
->refcount
!= 1)) {
9223 if (maxtries
) i
--; /* don't count this try */
9226 swappability
= computeObjectSwappability(val
);
9227 if (!best
|| swappability
> best_swappability
) {
9229 best_swappability
= swappability
;
9234 if (best
== NULL
) return REDIS_ERR
;
9235 key
= dictGetEntryKey(best
);
9236 val
= dictGetEntryVal(best
);
9238 redisLog(REDIS_DEBUG
,"Key with best swappability: %s, %f",
9239 key
->ptr
, best_swappability
);
9241 /* Unshare the key if needed */
9242 if (key
->refcount
> 1) {
9243 robj
*newkey
= dupStringObject(key
);
9245 key
= dictGetEntryKey(best
) = newkey
;
9249 vmSwapObjectThreaded(key
,val
,best_db
);
9252 if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
9253 dictGetEntryVal(best
) = NULL
;
9261 static int vmSwapOneObjectBlocking() {
9262 return vmSwapOneObject(0);
9265 static int vmSwapOneObjectThreaded() {
9266 return vmSwapOneObject(1);
9269 /* Return true if it's safe to swap out objects in a given moment.
9270 * Basically we don't want to swap objects out while there is a BGSAVE
9271 * or a BGAEOREWRITE running in backgroud. */
9272 static int vmCanSwapOut(void) {
9273 return (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1);
9276 /* Delete a key if swapped. Returns 1 if the key was found, was swapped
9277 * and was deleted. Otherwise 0 is returned. */
9278 static int deleteIfSwapped(redisDb
*db
, robj
*key
) {
9282 if ((de
= dictFind(db
->dict
,key
)) == NULL
) return 0;
9283 foundkey
= dictGetEntryKey(de
);
9284 if (foundkey
->storage
== REDIS_VM_MEMORY
) return 0;
9289 /* =================== Virtual Memory - Threaded I/O ======================= */
9291 static void freeIOJob(iojob
*j
) {
9292 if ((j
->type
== REDIS_IOJOB_PREPARE_SWAP
||
9293 j
->type
== REDIS_IOJOB_DO_SWAP
||
9294 j
->type
== REDIS_IOJOB_LOAD
) && j
->val
!= NULL
)
9295 decrRefCount(j
->val
);
9296 /* We don't decrRefCount the j->key field as we did't incremented
9297 * the count creating IO Jobs. This is because the key field here is
9298 * just used as an indentifier and if a key is removed the Job should
9299 * never be touched again. */
9303 /* Every time a thread finished a Job, it writes a byte into the write side
9304 * of an unix pipe in order to "awake" the main thread, and this function
9306 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
,
9310 int retval
, processed
= 0, toprocess
= -1, trytoswap
= 1;
9312 REDIS_NOTUSED(mask
);
9313 REDIS_NOTUSED(privdata
);
9315 /* For every byte we read in the read side of the pipe, there is one
9316 * I/O job completed to process. */
9317 while((retval
= read(fd
,buf
,1)) == 1) {
9321 struct dictEntry
*de
;
9323 redisLog(REDIS_DEBUG
,"Processing I/O completed job");
9325 /* Get the processed element (the oldest one) */
9327 assert(listLength(server
.io_processed
) != 0);
9328 if (toprocess
== -1) {
9329 toprocess
= (listLength(server
.io_processed
)*REDIS_MAX_COMPLETED_JOBS_PROCESSED
)/100;
9330 if (toprocess
<= 0) toprocess
= 1;
9332 ln
= listFirst(server
.io_processed
);
9334 listDelNode(server
.io_processed
,ln
);
9336 /* If this job is marked as canceled, just ignore it */
9341 /* Post process it in the main thread, as there are things we
9342 * can do just here to avoid race conditions and/or invasive locks */
9343 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
);
9344 de
= dictFind(j
->db
->dict
,j
->key
);
9346 key
= dictGetEntryKey(de
);
9347 if (j
->type
== REDIS_IOJOB_LOAD
) {
9350 /* Key loaded, bring it at home */
9351 key
->storage
= REDIS_VM_MEMORY
;
9352 key
->vm
.atime
= server
.unixtime
;
9353 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
9354 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk (threaded)",
9355 (unsigned char*) key
->ptr
);
9356 server
.vm_stats_swapped_objects
--;
9357 server
.vm_stats_swapins
++;
9358 dictGetEntryVal(de
) = j
->val
;
9359 incrRefCount(j
->val
);
9362 /* Handle clients waiting for this key to be loaded. */
9363 handleClientsBlockedOnSwappedKey(db
,key
);
9364 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
9365 /* Now we know the amount of pages required to swap this object.
9366 * Let's find some space for it, and queue this task again
9367 * rebranded as REDIS_IOJOB_DO_SWAP. */
9368 if (!vmCanSwapOut() ||
9369 vmFindContiguousPages(&j
->page
,j
->pages
) == REDIS_ERR
)
9371 /* Ooops... no space or we can't swap as there is
9372 * a fork()ed Redis trying to save stuff on disk. */
9374 key
->storage
= REDIS_VM_MEMORY
; /* undo operation */
9376 /* Note that we need to mark this pages as used now,
9377 * if the job will be canceled, we'll mark them as freed
9379 vmMarkPagesUsed(j
->page
,j
->pages
);
9380 j
->type
= REDIS_IOJOB_DO_SWAP
;
9385 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
9388 /* Key swapped. We can finally free some memory. */
9389 if (key
->storage
!= REDIS_VM_SWAPPING
) {
9390 printf("key->storage: %d\n",key
->storage
);
9391 printf("key->name: %s\n",(char*)key
->ptr
);
9392 printf("key->refcount: %d\n",key
->refcount
);
9393 printf("val: %p\n",(void*)j
->val
);
9394 printf("val->type: %d\n",j
->val
->type
);
9395 printf("val->ptr: %s\n",(char*)j
->val
->ptr
);
9397 redisAssert(key
->storage
== REDIS_VM_SWAPPING
);
9398 val
= dictGetEntryVal(de
);
9399 key
->vm
.page
= j
->page
;
9400 key
->vm
.usedpages
= j
->pages
;
9401 key
->storage
= REDIS_VM_SWAPPED
;
9402 key
->vtype
= j
->val
->type
;
9403 decrRefCount(val
); /* Deallocate the object from memory. */
9404 dictGetEntryVal(de
) = NULL
;
9405 redisLog(REDIS_DEBUG
,
9406 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
9407 (unsigned char*) key
->ptr
,
9408 (unsigned long long) j
->page
, (unsigned long long) j
->pages
);
9409 server
.vm_stats_swapped_objects
++;
9410 server
.vm_stats_swapouts
++;
9412 /* Put a few more swap requests in queue if we are still
9414 if (trytoswap
&& vmCanSwapOut() &&
9415 zmalloc_used_memory() > server
.vm_max_memory
)
9420 more
= listLength(server
.io_newjobs
) <
9421 (unsigned) server
.vm_max_threads
;
9423 /* Don't waste CPU time if swappable objects are rare. */
9424 if (vmSwapOneObjectThreaded() == REDIS_ERR
) {
9432 if (processed
== toprocess
) return;
9434 if (retval
< 0 && errno
!= EAGAIN
) {
9435 redisLog(REDIS_WARNING
,
9436 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
9441 static void lockThreadedIO(void) {
9442 pthread_mutex_lock(&server
.io_mutex
);
9445 static void unlockThreadedIO(void) {
9446 pthread_mutex_unlock(&server
.io_mutex
);
9449 /* Remove the specified object from the threaded I/O queue if still not
9450 * processed, otherwise make sure to flag it as canceled. */
9451 static void vmCancelThreadedIOJob(robj
*o
) {
9453 server
.io_newjobs
, /* 0 */
9454 server
.io_processing
, /* 1 */
9455 server
.io_processed
/* 2 */
9459 assert(o
->storage
== REDIS_VM_LOADING
|| o
->storage
== REDIS_VM_SWAPPING
);
9462 /* Search for a matching key in one of the queues */
9463 for (i
= 0; i
< 3; i
++) {
9467 listRewind(lists
[i
],&li
);
9468 while ((ln
= listNext(&li
)) != NULL
) {
9469 iojob
*job
= ln
->value
;
9471 if (job
->canceled
) continue; /* Skip this, already canceled. */
9472 if (job
->key
== o
) {
9473 redisLog(REDIS_DEBUG
,"*** CANCELED %p (%s) (type %d) (LIST ID %d)\n",
9474 (void*)job
, (char*)o
->ptr
, job
->type
, i
);
9475 /* Mark the pages as free since the swap didn't happened
9476 * or happened but is now discarded. */
9477 if (i
!= 1 && job
->type
== REDIS_IOJOB_DO_SWAP
)
9478 vmMarkPagesFree(job
->page
,job
->pages
);
9479 /* Cancel the job. It depends on the list the job is
9482 case 0: /* io_newjobs */
9483 /* If the job was yet not processed the best thing to do
9484 * is to remove it from the queue at all */
9486 listDelNode(lists
[i
],ln
);
9488 case 1: /* io_processing */
9489 /* Oh Shi- the thread is messing with the Job:
9491 * Probably it's accessing the object if this is a
9492 * PREPARE_SWAP or DO_SWAP job.
9493 * If it's a LOAD job it may be reading from disk and
9494 * if we don't wait for the job to terminate before to
9495 * cancel it, maybe in a few microseconds data can be
9496 * corrupted in this pages. So the short story is:
9498 * Better to wait for the job to move into the
9499 * next queue (processed)... */
9501 /* We try again and again until the job is completed. */
9503 /* But let's wait some time for the I/O thread
9504 * to finish with this job. After all this condition
9505 * should be very rare. */
9508 case 2: /* io_processed */
9509 /* The job was already processed, that's easy...
9510 * just mark it as canceled so that we'll ignore it
9511 * when processing completed jobs. */
9515 /* Finally we have to adjust the storage type of the object
9516 * in order to "UNDO" the operaiton. */
9517 if (o
->storage
== REDIS_VM_LOADING
)
9518 o
->storage
= REDIS_VM_SWAPPED
;
9519 else if (o
->storage
== REDIS_VM_SWAPPING
)
9520 o
->storage
= REDIS_VM_MEMORY
;
9527 assert(1 != 1); /* We should never reach this */
9530 static void *IOThreadEntryPoint(void *arg
) {
9535 pthread_detach(pthread_self());
9537 /* Get a new job to process */
9539 if (listLength(server
.io_newjobs
) == 0) {
9540 /* No new jobs in queue, exit. */
9541 redisLog(REDIS_DEBUG
,"Thread %ld exiting, nothing to do",
9542 (long) pthread_self());
9543 server
.io_active_threads
--;
9547 ln
= listFirst(server
.io_newjobs
);
9549 listDelNode(server
.io_newjobs
,ln
);
9550 /* Add the job in the processing queue */
9551 j
->thread
= pthread_self();
9552 listAddNodeTail(server
.io_processing
,j
);
9553 ln
= listLast(server
.io_processing
); /* We use ln later to remove it */
9555 redisLog(REDIS_DEBUG
,"Thread %ld got a new job (type %d): %p about key '%s'",
9556 (long) pthread_self(), j
->type
, (void*)j
, (char*)j
->key
->ptr
);
9558 /* Process the Job */
9559 if (j
->type
== REDIS_IOJOB_LOAD
) {
9560 j
->val
= vmReadObjectFromSwap(j
->page
,j
->key
->vtype
);
9561 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
9562 FILE *fp
= fopen("/dev/null","w+");
9563 j
->pages
= rdbSavedObjectPages(j
->val
,fp
);
9565 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
9566 if (vmWriteObjectOnSwap(j
->val
,j
->page
) == REDIS_ERR
)
9570 /* Done: insert the job into the processed queue */
9571 redisLog(REDIS_DEBUG
,"Thread %ld completed the job: %p (key %s)",
9572 (long) pthread_self(), (void*)j
, (char*)j
->key
->ptr
);
9574 listDelNode(server
.io_processing
,ln
);
9575 listAddNodeTail(server
.io_processed
,j
);
9578 /* Signal the main thread there is new stuff to process */
9579 assert(write(server
.io_ready_pipe_write
,"x",1) == 1);
9581 return NULL
; /* never reached */
9584 static void spawnIOThread(void) {
9586 sigset_t mask
, omask
;
9590 sigaddset(&mask
,SIGCHLD
);
9591 sigaddset(&mask
,SIGHUP
);
9592 sigaddset(&mask
,SIGPIPE
);
9593 pthread_sigmask(SIG_SETMASK
, &mask
, &omask
);
9594 while ((err
= pthread_create(&thread
,&server
.io_threads_attr
,IOThreadEntryPoint
,NULL
)) != 0) {
9595 redisLog(REDIS_WARNING
,"Unable to spawn an I/O thread: %s",
9599 pthread_sigmask(SIG_SETMASK
, &omask
, NULL
);
9600 server
.io_active_threads
++;
9603 /* We need to wait for the last thread to exit before we are able to
9604 * fork() in order to BGSAVE or BGREWRITEAOF. */
9605 static void waitEmptyIOJobsQueue(void) {
9607 int io_processed_len
;
9610 if (listLength(server
.io_newjobs
) == 0 &&
9611 listLength(server
.io_processing
) == 0 &&
9612 server
.io_active_threads
== 0)
9617 /* While waiting for empty jobs queue condition we post-process some
9618 * finshed job, as I/O threads may be hanging trying to write against
9619 * the io_ready_pipe_write FD but there are so much pending jobs that
9621 io_processed_len
= listLength(server
.io_processed
);
9623 if (io_processed_len
) {
9624 vmThreadedIOCompletedJob(NULL
,server
.io_ready_pipe_read
,NULL
,0);
9625 usleep(1000); /* 1 millisecond */
9627 usleep(10000); /* 10 milliseconds */
9632 static void vmReopenSwapFile(void) {
9633 /* Note: we don't close the old one as we are in the child process
9634 * and don't want to mess at all with the original file object. */
9635 server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b");
9636 if (server
.vm_fp
== NULL
) {
9637 redisLog(REDIS_WARNING
,"Can't re-open the VM swap file: %s. Exiting.",
9638 server
.vm_swap_file
);
9641 server
.vm_fd
= fileno(server
.vm_fp
);
9644 /* This function must be called while with threaded IO locked */
9645 static void queueIOJob(iojob
*j
) {
9646 redisLog(REDIS_DEBUG
,"Queued IO Job %p type %d about key '%s'\n",
9647 (void*)j
, j
->type
, (char*)j
->key
->ptr
);
9648 listAddNodeTail(server
.io_newjobs
,j
);
9649 if (server
.io_active_threads
< server
.vm_max_threads
)
9653 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
) {
9656 assert(key
->storage
== REDIS_VM_MEMORY
);
9657 assert(key
->refcount
== 1);
9659 j
= zmalloc(sizeof(*j
));
9660 j
->type
= REDIS_IOJOB_PREPARE_SWAP
;
9666 j
->thread
= (pthread_t
) -1;
9667 key
->storage
= REDIS_VM_SWAPPING
;
9675 /* ============ Virtual Memory - Blocking clients on missing keys =========== */
9677 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
9678 * If there is not already a job loading the key, it is craeted.
9679 * The key is added to the io_keys list in the client structure, and also
9680 * in the hash table mapping swapped keys to waiting clients, that is,
9681 * server.io_waited_keys. */
9682 static int waitForSwappedKey(redisClient
*c
, robj
*key
) {
9683 struct dictEntry
*de
;
9687 /* If the key does not exist or is already in RAM we don't need to
9688 * block the client at all. */
9689 de
= dictFind(c
->db
->dict
,key
);
9690 if (de
== NULL
) return 0;
9691 o
= dictGetEntryKey(de
);
9692 if (o
->storage
== REDIS_VM_MEMORY
) {
9694 } else if (o
->storage
== REDIS_VM_SWAPPING
) {
9695 /* We were swapping the key, undo it! */
9696 vmCancelThreadedIOJob(o
);
9700 /* OK: the key is either swapped, or being loaded just now. */
9702 /* Add the key to the list of keys this client is waiting for.
9703 * This maps clients to keys they are waiting for. */
9704 listAddNodeTail(c
->io_keys
,key
);
9707 /* Add the client to the swapped keys => clients waiting map. */
9708 de
= dictFind(c
->db
->io_keys
,key
);
9712 /* For every key we take a list of clients blocked for it */
9714 retval
= dictAdd(c
->db
->io_keys
,key
,l
);
9716 assert(retval
== DICT_OK
);
9718 l
= dictGetEntryVal(de
);
9720 listAddNodeTail(l
,c
);
9722 /* Are we already loading the key from disk? If not create a job */
9723 if (o
->storage
== REDIS_VM_SWAPPED
) {
9726 o
->storage
= REDIS_VM_LOADING
;
9727 j
= zmalloc(sizeof(*j
));
9728 j
->type
= REDIS_IOJOB_LOAD
;
9731 j
->key
->vtype
= o
->vtype
;
9732 j
->page
= o
->vm
.page
;
9735 j
->thread
= (pthread_t
) -1;
9743 /* Preload keys for any command with first, last and step values for
9744 * the command keys prototype, as defined in the command table. */
9745 static void waitForMultipleSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
9747 if (cmd
->vm_firstkey
== 0) return;
9748 last
= cmd
->vm_lastkey
;
9749 if (last
< 0) last
= argc
+last
;
9750 for (j
= cmd
->vm_firstkey
; j
<= last
; j
+= cmd
->vm_keystep
) {
9751 redisAssert(j
< argc
);
9752 waitForSwappedKey(c
,argv
[j
]);
9756 /* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
9757 * Note that the number of keys to preload is user-defined, so we need to
9758 * apply a sanity check against argc. */
9759 static void zunionInterBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
9763 num
= atoi(argv
[2]->ptr
);
9764 if (num
> (argc
-3)) return;
9765 for (i
= 0; i
< num
; i
++) {
9766 waitForSwappedKey(c
,argv
[3+i
]);
9770 /* Preload keys needed to execute the entire MULTI/EXEC block.
9772 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
9773 * and will block the client when any command requires a swapped out value. */
9774 static void execBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
9776 struct redisCommand
*mcmd
;
9779 REDIS_NOTUSED(argc
);
9780 REDIS_NOTUSED(argv
);
9782 if (!(c
->flags
& REDIS_MULTI
)) return;
9783 for (i
= 0; i
< c
->mstate
.count
; i
++) {
9784 mcmd
= c
->mstate
.commands
[i
].cmd
;
9785 margc
= c
->mstate
.commands
[i
].argc
;
9786 margv
= c
->mstate
.commands
[i
].argv
;
9788 if (mcmd
->vm_preload_proc
!= NULL
) {
9789 mcmd
->vm_preload_proc(c
,mcmd
,margc
,margv
);
9791 waitForMultipleSwappedKeys(c
,mcmd
,margc
,margv
);
9796 /* Is this client attempting to run a command against swapped keys?
9797 * If so, block it ASAP, load the keys in background, then resume it.
9799 * The important idea about this function is that it can fail! If keys will
9800 * still be swapped when the client is resumed, this key lookups will
9801 * just block loading keys from disk. In practical terms this should only
9802 * happen with SORT BY command or if there is a bug in this function.
9804 * Return 1 if the client is marked as blocked, 0 if the client can
9805 * continue as the keys it is going to access appear to be in memory. */
9806 static int blockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
) {
9807 if (cmd
->vm_preload_proc
!= NULL
) {
9808 cmd
->vm_preload_proc(c
,cmd
,c
->argc
,c
->argv
);
9810 waitForMultipleSwappedKeys(c
,cmd
,c
->argc
,c
->argv
);
9813 /* If the client was blocked for at least one key, mark it as blocked. */
9814 if (listLength(c
->io_keys
)) {
9815 c
->flags
|= REDIS_IO_WAIT
;
9816 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
9817 server
.vm_blocked_clients
++;
9824 /* Remove the 'key' from the list of blocked keys for a given client.
9826 * The function returns 1 when there are no longer blocking keys after
9827 * the current one was removed (and the client can be unblocked). */
9828 static int dontWaitForSwappedKey(redisClient
*c
, robj
*key
) {
9832 struct dictEntry
*de
;
9834 /* Remove the key from the list of keys this client is waiting for. */
9835 listRewind(c
->io_keys
,&li
);
9836 while ((ln
= listNext(&li
)) != NULL
) {
9837 if (equalStringObjects(ln
->value
,key
)) {
9838 listDelNode(c
->io_keys
,ln
);
9844 /* Remove the client form the key => waiting clients map. */
9845 de
= dictFind(c
->db
->io_keys
,key
);
9847 l
= dictGetEntryVal(de
);
9848 ln
= listSearchKey(l
,c
);
9851 if (listLength(l
) == 0)
9852 dictDelete(c
->db
->io_keys
,key
);
9854 return listLength(c
->io_keys
) == 0;
9857 static void handleClientsBlockedOnSwappedKey(redisDb
*db
, robj
*key
) {
9858 struct dictEntry
*de
;
9863 de
= dictFind(db
->io_keys
,key
);
9866 l
= dictGetEntryVal(de
);
9867 len
= listLength(l
);
9868 /* Note: we can't use something like while(listLength(l)) as the list
9869 * can be freed by the calling function when we remove the last element. */
9872 redisClient
*c
= ln
->value
;
9874 if (dontWaitForSwappedKey(c
,key
)) {
9875 /* Put the client in the list of clients ready to go as we
9876 * loaded all the keys about it. */
9877 listAddNodeTail(server
.io_ready_clients
,c
);
9882 /* =========================== Remote Configuration ========================= */
9884 static void configSetCommand(redisClient
*c
) {
9885 robj
*o
= getDecodedObject(c
->argv
[3]);
9888 if (!strcasecmp(c
->argv
[2]->ptr
,"dbfilename")) {
9889 zfree(server
.dbfilename
);
9890 server
.dbfilename
= zstrdup(o
->ptr
);
9891 } else if (!strcasecmp(c
->argv
[2]->ptr
,"requirepass")) {
9892 zfree(server
.requirepass
);
9893 server
.requirepass
= zstrdup(o
->ptr
);
9894 } else if (!strcasecmp(c
->argv
[2]->ptr
,"masterauth")) {
9895 zfree(server
.masterauth
);
9896 server
.masterauth
= zstrdup(o
->ptr
);
9897 } else if (!strcasecmp(c
->argv
[2]->ptr
,"maxmemory")) {
9898 if (getLongLongFromObject(o
,&ll
) == REDIS_ERR
||
9899 ll
< 0) goto badfmt
;
9900 server
.maxmemory
= ll
;
9901 } else if (!strcasecmp(c
->argv
[2]->ptr
,"timeout")) {
9902 if (getLongLongFromObject(o
,&ll
) == REDIS_ERR
||
9903 ll
< 0 || ll
> LONG_MAX
) goto badfmt
;
9904 server
.maxidletime
= ll
;
9905 } else if (!strcasecmp(c
->argv
[2]->ptr
,"appendfsync")) {
9906 if (!strcasecmp(o
->ptr
,"no")) {
9907 server
.appendfsync
= APPENDFSYNC_NO
;
9908 } else if (!strcasecmp(o
->ptr
,"everysec")) {
9909 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
9910 } else if (!strcasecmp(o
->ptr
,"always")) {
9911 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
9915 } else if (!strcasecmp(c
->argv
[2]->ptr
,"appendonly")) {
9916 int old
= server
.appendonly
;
9917 int new = yesnotoi(o
->ptr
);
9919 if (new == -1) goto badfmt
;
9924 if (startAppendOnly() == REDIS_ERR
) {
9925 addReplySds(c
,sdscatprintf(sdsempty(),
9926 "-ERR Unable to turn on AOF. Check server logs.\r\n"));
9932 } else if (!strcasecmp(c
->argv
[2]->ptr
,"save")) {
9934 sds
*v
= sdssplitlen(o
->ptr
,sdslen(o
->ptr
)," ",1,&vlen
);
9936 /* Perform sanity check before setting the new config:
9937 * - Even number of args
9938 * - Seconds >= 1, changes >= 0 */
9940 sdsfreesplitres(v
,vlen
);
9943 for (j
= 0; j
< vlen
; j
++) {
9947 val
= strtoll(v
[j
], &eptr
, 10);
9948 if (eptr
[0] != '\0' ||
9949 ((j
& 1) == 0 && val
< 1) ||
9950 ((j
& 1) == 1 && val
< 0)) {
9951 sdsfreesplitres(v
,vlen
);
9955 /* Finally set the new config */
9956 resetServerSaveParams();
9957 for (j
= 0; j
< vlen
; j
+= 2) {
9961 seconds
= strtoll(v
[j
],NULL
,10);
9962 changes
= strtoll(v
[j
+1],NULL
,10);
9963 appendServerSaveParams(seconds
, changes
);
9965 sdsfreesplitres(v
,vlen
);
9967 addReplySds(c
,sdscatprintf(sdsempty(),
9968 "-ERR not supported CONFIG parameter %s\r\n",
9969 (char*)c
->argv
[2]->ptr
));
9974 addReply(c
,shared
.ok
);
9977 badfmt
: /* Bad format errors */
9978 addReplySds(c
,sdscatprintf(sdsempty(),
9979 "-ERR invalid argument '%s' for CONFIG SET '%s'\r\n",
9981 (char*)c
->argv
[2]->ptr
));
9985 static void configGetCommand(redisClient
*c
) {
9986 robj
*o
= getDecodedObject(c
->argv
[2]);
9987 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
9988 char *pattern
= o
->ptr
;
9992 decrRefCount(lenobj
);
9994 if (stringmatch(pattern
,"dbfilename",0)) {
9995 addReplyBulkCString(c
,"dbfilename");
9996 addReplyBulkCString(c
,server
.dbfilename
);
9999 if (stringmatch(pattern
,"requirepass",0)) {
10000 addReplyBulkCString(c
,"requirepass");
10001 addReplyBulkCString(c
,server
.requirepass
);
10004 if (stringmatch(pattern
,"masterauth",0)) {
10005 addReplyBulkCString(c
,"masterauth");
10006 addReplyBulkCString(c
,server
.masterauth
);
10009 if (stringmatch(pattern
,"maxmemory",0)) {
10012 ll2string(buf
,128,server
.maxmemory
);
10013 addReplyBulkCString(c
,"maxmemory");
10014 addReplyBulkCString(c
,buf
);
10017 if (stringmatch(pattern
,"timeout",0)) {
10020 ll2string(buf
,128,server
.maxidletime
);
10021 addReplyBulkCString(c
,"timeout");
10022 addReplyBulkCString(c
,buf
);
10025 if (stringmatch(pattern
,"appendonly",0)) {
10026 addReplyBulkCString(c
,"appendonly");
10027 addReplyBulkCString(c
,server
.appendonly
? "yes" : "no");
10030 if (stringmatch(pattern
,"appendfsync",0)) {
10033 switch(server
.appendfsync
) {
10034 case APPENDFSYNC_NO
: policy
= "no"; break;
10035 case APPENDFSYNC_EVERYSEC
: policy
= "everysec"; break;
10036 case APPENDFSYNC_ALWAYS
: policy
= "always"; break;
10037 default: policy
= "unknown"; break; /* too harmless to panic */
10039 addReplyBulkCString(c
,"appendfsync");
10040 addReplyBulkCString(c
,policy
);
10043 if (stringmatch(pattern
,"save",0)) {
10044 sds buf
= sdsempty();
10047 for (j
= 0; j
< server
.saveparamslen
; j
++) {
10048 buf
= sdscatprintf(buf
,"%ld %d",
10049 server
.saveparams
[j
].seconds
,
10050 server
.saveparams
[j
].changes
);
10051 if (j
!= server
.saveparamslen
-1)
10052 buf
= sdscatlen(buf
," ",1);
10054 addReplyBulkCString(c
,"save");
10055 addReplyBulkCString(c
,buf
);
10060 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%d\r\n",matches
*2);
10063 static void configCommand(redisClient
*c
) {
10064 if (!strcasecmp(c
->argv
[1]->ptr
,"set")) {
10065 if (c
->argc
!= 4) goto badarity
;
10066 configSetCommand(c
);
10067 } else if (!strcasecmp(c
->argv
[1]->ptr
,"get")) {
10068 if (c
->argc
!= 3) goto badarity
;
10069 configGetCommand(c
);
10070 } else if (!strcasecmp(c
->argv
[1]->ptr
,"resetstat")) {
10071 if (c
->argc
!= 2) goto badarity
;
10072 server
.stat_numcommands
= 0;
10073 server
.stat_numconnections
= 0;
10074 server
.stat_expiredkeys
= 0;
10075 server
.stat_starttime
= time(NULL
);
10076 addReply(c
,shared
.ok
);
10078 addReplySds(c
,sdscatprintf(sdsempty(),
10079 "-ERR CONFIG subcommand must be one of GET, SET, RESETSTAT\r\n"));
10084 addReplySds(c
,sdscatprintf(sdsempty(),
10085 "-ERR Wrong number of arguments for CONFIG %s\r\n",
10086 (char*) c
->argv
[1]->ptr
));
10089 /* =========================== Pubsub implementation ======================== */
10091 static void freePubsubPattern(void *p
) {
10092 pubsubPattern
*pat
= p
;
10094 decrRefCount(pat
->pattern
);
10098 static int listMatchPubsubPattern(void *a
, void *b
) {
10099 pubsubPattern
*pa
= a
, *pb
= b
;
10101 return (pa
->client
== pb
->client
) &&
10102 (equalStringObjects(pa
->pattern
,pb
->pattern
));
10105 /* Subscribe a client to a channel. Returns 1 if the operation succeeded, or
10106 * 0 if the client was already subscribed to that channel. */
10107 static int pubsubSubscribeChannel(redisClient
*c
, robj
*channel
) {
10108 struct dictEntry
*de
;
10109 list
*clients
= NULL
;
10112 /* Add the channel to the client -> channels hash table */
10113 if (dictAdd(c
->pubsub_channels
,channel
,NULL
) == DICT_OK
) {
10115 incrRefCount(channel
);
10116 /* Add the client to the channel -> list of clients hash table */
10117 de
= dictFind(server
.pubsub_channels
,channel
);
10119 clients
= listCreate();
10120 dictAdd(server
.pubsub_channels
,channel
,clients
);
10121 incrRefCount(channel
);
10123 clients
= dictGetEntryVal(de
);
10125 listAddNodeTail(clients
,c
);
10127 /* Notify the client */
10128 addReply(c
,shared
.mbulk3
);
10129 addReply(c
,shared
.subscribebulk
);
10130 addReplyBulk(c
,channel
);
10131 addReplyLongLong(c
,dictSize(c
->pubsub_channels
)+listLength(c
->pubsub_patterns
));
10135 /* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10136 * 0 if the client was not subscribed to the specified channel. */
10137 static int pubsubUnsubscribeChannel(redisClient
*c
, robj
*channel
, int notify
) {
10138 struct dictEntry
*de
;
10143 /* Remove the channel from the client -> channels hash table */
10144 incrRefCount(channel
); /* channel may be just a pointer to the same object
10145 we have in the hash tables. Protect it... */
10146 if (dictDelete(c
->pubsub_channels
,channel
) == DICT_OK
) {
10148 /* Remove the client from the channel -> clients list hash table */
10149 de
= dictFind(server
.pubsub_channels
,channel
);
10150 assert(de
!= NULL
);
10151 clients
= dictGetEntryVal(de
);
10152 ln
= listSearchKey(clients
,c
);
10153 assert(ln
!= NULL
);
10154 listDelNode(clients
,ln
);
10155 if (listLength(clients
) == 0) {
10156 /* Free the list and associated hash entry at all if this was
10157 * the latest client, so that it will be possible to abuse
10158 * Redis PUBSUB creating millions of channels. */
10159 dictDelete(server
.pubsub_channels
,channel
);
10162 /* Notify the client */
10164 addReply(c
,shared
.mbulk3
);
10165 addReply(c
,shared
.unsubscribebulk
);
10166 addReplyBulk(c
,channel
);
10167 addReplyLongLong(c
,dictSize(c
->pubsub_channels
)+
10168 listLength(c
->pubsub_patterns
));
10171 decrRefCount(channel
); /* it is finally safe to release it */
10175 /* Subscribe a client to a pattern. Returns 1 if the operation succeeded, or 0 if the clinet was already subscribed to that pattern. */
10176 static int pubsubSubscribePattern(redisClient
*c
, robj
*pattern
) {
10179 if (listSearchKey(c
->pubsub_patterns
,pattern
) == NULL
) {
10181 pubsubPattern
*pat
;
10182 listAddNodeTail(c
->pubsub_patterns
,pattern
);
10183 incrRefCount(pattern
);
10184 pat
= zmalloc(sizeof(*pat
));
10185 pat
->pattern
= getDecodedObject(pattern
);
10187 listAddNodeTail(server
.pubsub_patterns
,pat
);
10189 /* Notify the client */
10190 addReply(c
,shared
.mbulk3
);
10191 addReply(c
,shared
.psubscribebulk
);
10192 addReplyBulk(c
,pattern
);
10193 addReplyLongLong(c
,dictSize(c
->pubsub_channels
)+listLength(c
->pubsub_patterns
));
10197 /* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10198 * 0 if the client was not subscribed to the specified channel. */
10199 static int pubsubUnsubscribePattern(redisClient
*c
, robj
*pattern
, int notify
) {
10204 incrRefCount(pattern
); /* Protect the object. May be the same we remove */
10205 if ((ln
= listSearchKey(c
->pubsub_patterns
,pattern
)) != NULL
) {
10207 listDelNode(c
->pubsub_patterns
,ln
);
10209 pat
.pattern
= pattern
;
10210 ln
= listSearchKey(server
.pubsub_patterns
,&pat
);
10211 listDelNode(server
.pubsub_patterns
,ln
);
10213 /* Notify the client */
10215 addReply(c
,shared
.mbulk3
);
10216 addReply(c
,shared
.punsubscribebulk
);
10217 addReplyBulk(c
,pattern
);
10218 addReplyLongLong(c
,dictSize(c
->pubsub_channels
)+
10219 listLength(c
->pubsub_patterns
));
10221 decrRefCount(pattern
);
10225 /* Unsubscribe from all the channels. Return the number of channels the
10226 * client was subscribed from. */
10227 static int pubsubUnsubscribeAllChannels(redisClient
*c
, int notify
) {
10228 dictIterator
*di
= dictGetIterator(c
->pubsub_channels
);
10232 while((de
= dictNext(di
)) != NULL
) {
10233 robj
*channel
= dictGetEntryKey(de
);
10235 count
+= pubsubUnsubscribeChannel(c
,channel
,notify
);
10237 dictReleaseIterator(di
);
10241 /* Unsubscribe from all the patterns. Return the number of patterns the
10242 * client was subscribed from. */
10243 static int pubsubUnsubscribeAllPatterns(redisClient
*c
, int notify
) {
10248 listRewind(c
->pubsub_patterns
,&li
);
10249 while ((ln
= listNext(&li
)) != NULL
) {
10250 robj
*pattern
= ln
->value
;
10252 count
+= pubsubUnsubscribePattern(c
,pattern
,notify
);
10257 /* Publish a message */
10258 static int pubsubPublishMessage(robj
*channel
, robj
*message
) {
10260 struct dictEntry
*de
;
10264 /* Send to clients listening for that channel */
10265 de
= dictFind(server
.pubsub_channels
,channel
);
10267 list
*list
= dictGetEntryVal(de
);
10271 listRewind(list
,&li
);
10272 while ((ln
= listNext(&li
)) != NULL
) {
10273 redisClient
*c
= ln
->value
;
10275 addReply(c
,shared
.mbulk3
);
10276 addReply(c
,shared
.messagebulk
);
10277 addReplyBulk(c
,channel
);
10278 addReplyBulk(c
,message
);
10282 /* Send to clients listening to matching channels */
10283 if (listLength(server
.pubsub_patterns
)) {
10284 listRewind(server
.pubsub_patterns
,&li
);
10285 channel
= getDecodedObject(channel
);
10286 while ((ln
= listNext(&li
)) != NULL
) {
10287 pubsubPattern
*pat
= ln
->value
;
10289 if (stringmatchlen((char*)pat
->pattern
->ptr
,
10290 sdslen(pat
->pattern
->ptr
),
10291 (char*)channel
->ptr
,
10292 sdslen(channel
->ptr
),0)) {
10293 addReply(pat
->client
,shared
.mbulk4
);
10294 addReply(pat
->client
,shared
.pmessagebulk
);
10295 addReplyBulk(pat
->client
,pat
->pattern
);
10296 addReplyBulk(pat
->client
,channel
);
10297 addReplyBulk(pat
->client
,message
);
10301 decrRefCount(channel
);
10306 static void subscribeCommand(redisClient
*c
) {
10309 for (j
= 1; j
< c
->argc
; j
++)
10310 pubsubSubscribeChannel(c
,c
->argv
[j
]);
10313 static void unsubscribeCommand(redisClient
*c
) {
10314 if (c
->argc
== 1) {
10315 pubsubUnsubscribeAllChannels(c
,1);
10320 for (j
= 1; j
< c
->argc
; j
++)
10321 pubsubUnsubscribeChannel(c
,c
->argv
[j
],1);
10325 static void psubscribeCommand(redisClient
*c
) {
10328 for (j
= 1; j
< c
->argc
; j
++)
10329 pubsubSubscribePattern(c
,c
->argv
[j
]);
10332 static void punsubscribeCommand(redisClient
*c
) {
10333 if (c
->argc
== 1) {
10334 pubsubUnsubscribeAllPatterns(c
,1);
10339 for (j
= 1; j
< c
->argc
; j
++)
10340 pubsubUnsubscribePattern(c
,c
->argv
[j
],1);
10344 static void publishCommand(redisClient
*c
) {
10345 int receivers
= pubsubPublishMessage(c
->argv
[1],c
->argv
[2]);
10346 addReplyLongLong(c
,receivers
);
10349 /* ================================= Debugging ============================== */
10351 /* Compute the sha1 of string at 's' with 'len' bytes long.
10352 * The SHA1 is then xored againt the string pointed by digest.
10353 * Since xor is commutative, this operation is used in order to
10354 * "add" digests relative to unordered elements.
10356 * So digest(a,b,c,d) will be the same of digest(b,a,c,d) */
10357 static void xorDigest(unsigned char *digest
, void *ptr
, size_t len
) {
10359 unsigned char hash
[20], *s
= ptr
;
10363 SHA1Update(&ctx
,s
,len
);
10364 SHA1Final(hash
,&ctx
);
10366 for (j
= 0; j
< 20; j
++)
10367 digest
[j
] ^= hash
[j
];
10370 static void xorObjectDigest(unsigned char *digest
, robj
*o
) {
10371 o
= getDecodedObject(o
);
10372 xorDigest(digest
,o
->ptr
,sdslen(o
->ptr
));
10376 /* This function instead of just computing the SHA1 and xoring it
10377 * against diget, also perform the digest of "digest" itself and
10378 * replace the old value with the new one.
10380 * So the final digest will be:
10382 * digest = SHA1(digest xor SHA1(data))
10384 * This function is used every time we want to preserve the order so
10385 * that digest(a,b,c,d) will be different than digest(b,c,d,a)
10387 * Also note that mixdigest("foo") followed by mixdigest("bar")
10388 * will lead to a different digest compared to "fo", "obar".
10390 static void mixDigest(unsigned char *digest
, void *ptr
, size_t len
) {
10394 xorDigest(digest
,s
,len
);
10396 SHA1Update(&ctx
,digest
,20);
10397 SHA1Final(digest
,&ctx
);
10400 static void mixObjectDigest(unsigned char *digest
, robj
*o
) {
10401 o
= getDecodedObject(o
);
10402 mixDigest(digest
,o
->ptr
,sdslen(o
->ptr
));
10406 /* Compute the dataset digest. Since keys, sets elements, hashes elements
10407 * are not ordered, we use a trick: every aggregate digest is the xor
10408 * of the digests of their elements. This way the order will not change
10409 * the result. For list instead we use a feedback entering the output digest
10410 * as input in order to ensure that a different ordered list will result in
10411 * a different digest. */
10412 static void computeDatasetDigest(unsigned char *final
) {
10413 unsigned char digest
[20];
10415 dictIterator
*di
= NULL
;
10420 memset(final
,0,20); /* Start with a clean result */
10422 for (j
= 0; j
< server
.dbnum
; j
++) {
10423 redisDb
*db
= server
.db
+j
;
10425 if (dictSize(db
->dict
) == 0) continue;
10426 di
= dictGetIterator(db
->dict
);
10428 /* hash the DB id, so the same dataset moved in a different
10429 * DB will lead to a different digest */
10431 mixDigest(final
,&aux
,sizeof(aux
));
10433 /* Iterate this DB writing every entry */
10434 while((de
= dictNext(di
)) != NULL
) {
10438 memset(digest
,0,20); /* This key-val digest */
10439 key
= dictGetEntryKey(de
);
10440 mixObjectDigest(digest
,key
);
10441 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
10442 key
->storage
== REDIS_VM_SWAPPING
) {
10443 o
= dictGetEntryVal(de
);
10446 o
= vmPreviewObject(key
);
10448 aux
= htonl(o
->type
);
10449 mixDigest(digest
,&aux
,sizeof(aux
));
10450 expiretime
= getExpire(db
,key
);
10452 /* Save the key and associated value */
10453 if (o
->type
== REDIS_STRING
) {
10454 mixObjectDigest(digest
,o
);
10455 } else if (o
->type
== REDIS_LIST
) {
10456 list
*list
= o
->ptr
;
10460 listRewind(list
,&li
);
10461 while((ln
= listNext(&li
))) {
10462 robj
*eleobj
= listNodeValue(ln
);
10464 mixObjectDigest(digest
,eleobj
);
10466 } else if (o
->type
== REDIS_SET
) {
10467 dict
*set
= o
->ptr
;
10468 dictIterator
*di
= dictGetIterator(set
);
10471 while((de
= dictNext(di
)) != NULL
) {
10472 robj
*eleobj
= dictGetEntryKey(de
);
10474 xorObjectDigest(digest
,eleobj
);
10476 dictReleaseIterator(di
);
10477 } else if (o
->type
== REDIS_ZSET
) {
10479 dictIterator
*di
= dictGetIterator(zs
->dict
);
10482 while((de
= dictNext(di
)) != NULL
) {
10483 robj
*eleobj
= dictGetEntryKey(de
);
10484 double *score
= dictGetEntryVal(de
);
10485 unsigned char eledigest
[20];
10487 snprintf(buf
,sizeof(buf
),"%.17g",*score
);
10488 memset(eledigest
,0,20);
10489 mixObjectDigest(eledigest
,eleobj
);
10490 mixDigest(eledigest
,buf
,strlen(buf
));
10491 xorDigest(digest
,eledigest
,20);
10493 dictReleaseIterator(di
);
10494 } else if (o
->type
== REDIS_HASH
) {
10498 hi
= hashInitIterator(o
);
10499 while (hashNext(hi
) != REDIS_ERR
) {
10500 unsigned char eledigest
[20];
10502 memset(eledigest
,0,20);
10503 obj
= hashCurrent(hi
,REDIS_HASH_KEY
);
10504 mixObjectDigest(eledigest
,obj
);
10506 obj
= hashCurrent(hi
,REDIS_HASH_VALUE
);
10507 mixObjectDigest(eledigest
,obj
);
10509 xorDigest(digest
,eledigest
,20);
10511 hashReleaseIterator(hi
);
10513 redisPanic("Unknown object type");
10516 /* If the key has an expire, add it to the mix */
10517 if (expiretime
!= -1) xorDigest(digest
,"!!expire!!",10);
10518 /* We can finally xor the key-val digest to the final digest */
10519 xorDigest(final
,digest
,20);
10521 dictReleaseIterator(di
);
10525 static void debugCommand(redisClient
*c
) {
10526 if (!strcasecmp(c
->argv
[1]->ptr
,"segfault")) {
10527 *((char*)-1) = 'x';
10528 } else if (!strcasecmp(c
->argv
[1]->ptr
,"reload")) {
10529 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
10530 addReply(c
,shared
.err
);
10534 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
10535 addReply(c
,shared
.err
);
10538 redisLog(REDIS_WARNING
,"DB reloaded by DEBUG RELOAD");
10539 addReply(c
,shared
.ok
);
10540 } else if (!strcasecmp(c
->argv
[1]->ptr
,"loadaof")) {
10542 if (loadAppendOnlyFile(server
.appendfilename
) != REDIS_OK
) {
10543 addReply(c
,shared
.err
);
10546 redisLog(REDIS_WARNING
,"Append Only File loaded by DEBUG LOADAOF");
10547 addReply(c
,shared
.ok
);
10548 } else if (!strcasecmp(c
->argv
[1]->ptr
,"object") && c
->argc
== 3) {
10549 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
10553 addReply(c
,shared
.nokeyerr
);
10556 key
= dictGetEntryKey(de
);
10557 val
= dictGetEntryVal(de
);
10558 if (!server
.vm_enabled
|| (key
->storage
== REDIS_VM_MEMORY
||
10559 key
->storage
== REDIS_VM_SWAPPING
)) {
10563 if (val
->encoding
< (sizeof(strencoding
)/sizeof(char*))) {
10564 strenc
= strencoding
[val
->encoding
];
10566 snprintf(buf
,64,"unknown encoding %d\n", val
->encoding
);
10569 addReplySds(c
,sdscatprintf(sdsempty(),
10570 "+Key at:%p refcount:%d, value at:%p refcount:%d "
10571 "encoding:%s serializedlength:%lld\r\n",
10572 (void*)key
, key
->refcount
, (void*)val
, val
->refcount
,
10573 strenc
, (long long) rdbSavedObjectLen(val
,NULL
)));
10575 addReplySds(c
,sdscatprintf(sdsempty(),
10576 "+Key at:%p refcount:%d, value swapped at: page %llu "
10577 "using %llu pages\r\n",
10578 (void*)key
, key
->refcount
, (unsigned long long) key
->vm
.page
,
10579 (unsigned long long) key
->vm
.usedpages
));
10581 } else if (!strcasecmp(c
->argv
[1]->ptr
,"swapin") && c
->argc
== 3) {
10582 lookupKeyRead(c
->db
,c
->argv
[2]);
10583 addReply(c
,shared
.ok
);
10584 } else if (!strcasecmp(c
->argv
[1]->ptr
,"swapout") && c
->argc
== 3) {
10585 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
10588 if (!server
.vm_enabled
) {
10589 addReplySds(c
,sdsnew("-ERR Virtual Memory is disabled\r\n"));
10593 addReply(c
,shared
.nokeyerr
);
10596 key
= dictGetEntryKey(de
);
10597 val
= dictGetEntryVal(de
);
10598 /* If the key is shared we want to create a copy */
10599 if (key
->refcount
> 1) {
10600 robj
*newkey
= dupStringObject(key
);
10602 key
= dictGetEntryKey(de
) = newkey
;
10605 if (key
->storage
!= REDIS_VM_MEMORY
) {
10606 addReplySds(c
,sdsnew("-ERR This key is not in memory\r\n"));
10607 } else if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
10608 dictGetEntryVal(de
) = NULL
;
10609 addReply(c
,shared
.ok
);
10611 addReply(c
,shared
.err
);
10613 } else if (!strcasecmp(c
->argv
[1]->ptr
,"populate") && c
->argc
== 3) {
10618 if (getLongFromObjectOrReply(c
, c
->argv
[2], &keys
, NULL
) != REDIS_OK
)
10620 for (j
= 0; j
< keys
; j
++) {
10621 snprintf(buf
,sizeof(buf
),"key:%lu",j
);
10622 key
= createStringObject(buf
,strlen(buf
));
10623 if (lookupKeyRead(c
->db
,key
) != NULL
) {
10627 snprintf(buf
,sizeof(buf
),"value:%lu",j
);
10628 val
= createStringObject(buf
,strlen(buf
));
10629 dictAdd(c
->db
->dict
,key
,val
);
10631 addReply(c
,shared
.ok
);
10632 } else if (!strcasecmp(c
->argv
[1]->ptr
,"digest") && c
->argc
== 2) {
10633 unsigned char digest
[20];
10634 sds d
= sdsnew("+");
10637 computeDatasetDigest(digest
);
10638 for (j
= 0; j
< 20; j
++)
10639 d
= sdscatprintf(d
, "%02x",digest
[j
]);
10641 d
= sdscatlen(d
,"\r\n",2);
10644 addReplySds(c
,sdsnew(
10645 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPIN <key>|SWAPOUT <key>|RELOAD]\r\n"));
10649 static void _redisAssert(char *estr
, char *file
, int line
) {
10650 redisLog(REDIS_WARNING
,"=== ASSERTION FAILED ===");
10651 redisLog(REDIS_WARNING
,"==> %s:%d '%s' is not true",file
,line
,estr
);
10652 #ifdef HAVE_BACKTRACE
10653 redisLog(REDIS_WARNING
,"(forcing SIGSEGV in order to print the stack trace)");
10654 *((char*)-1) = 'x';
10658 static void _redisPanic(char *msg
, char *file
, int line
) {
10659 redisLog(REDIS_WARNING
,"!!! Software Failure. Press left mouse button to continue");
10660 redisLog(REDIS_WARNING
,"Guru Meditation: %s #%s:%d",msg
,file
,line
);
10661 #ifdef HAVE_BACKTRACE
10662 redisLog(REDIS_WARNING
,"(forcing SIGSEGV in order to print the stack trace)");
10663 *((char*)-1) = 'x';
10667 /* =================================== Main! ================================ */
10670 int linuxOvercommitMemoryValue(void) {
10671 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
10674 if (!fp
) return -1;
10675 if (fgets(buf
,64,fp
) == NULL
) {
10684 void linuxOvercommitMemoryWarning(void) {
10685 if (linuxOvercommitMemoryValue() == 0) {
10686 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.");
10689 #endif /* __linux__ */
10691 static void daemonize(void) {
10695 if (fork() != 0) exit(0); /* parent exits */
10696 setsid(); /* create a new session */
10698 /* Every output goes to /dev/null. If Redis is daemonized but
10699 * the 'logfile' is set to 'stdout' in the configuration file
10700 * it will not log at all. */
10701 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
10702 dup2(fd
, STDIN_FILENO
);
10703 dup2(fd
, STDOUT_FILENO
);
10704 dup2(fd
, STDERR_FILENO
);
10705 if (fd
> STDERR_FILENO
) close(fd
);
10707 /* Try to write the pid file */
10708 fp
= fopen(server
.pidfile
,"w");
10710 fprintf(fp
,"%d\n",getpid());
10715 static void version() {
10716 printf("Redis server version %s\n", REDIS_VERSION
);
10720 static void usage() {
10721 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
10722 fprintf(stderr
," ./redis-server - (read config from stdin)\n");
10726 int main(int argc
, char **argv
) {
10729 initServerConfig();
10731 if (strcmp(argv
[1], "-v") == 0 ||
10732 strcmp(argv
[1], "--version") == 0) version();
10733 if (strcmp(argv
[1], "--help") == 0) usage();
10734 resetServerSaveParams();
10735 loadServerConfig(argv
[1]);
10736 } else if ((argc
> 2)) {
10739 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'");
10741 if (server
.daemonize
) daemonize();
10743 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
10745 linuxOvercommitMemoryWarning();
10747 start
= time(NULL
);
10748 if (server
.appendonly
) {
10749 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
10750 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %ld seconds",time(NULL
)-start
);
10752 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
10753 redisLog(REDIS_NOTICE
,"DB loaded from disk: %ld seconds",time(NULL
)-start
);
10755 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
10756 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
10758 aeDeleteEventLoop(server
.el
);
10762 /* ============================= Backtrace support ========================= */
10764 #ifdef HAVE_BACKTRACE
10765 static char *findFuncName(void *pointer
, unsigned long *offset
);
10767 static void *getMcontextEip(ucontext_t
*uc
) {
10768 #if defined(__FreeBSD__)
10769 return (void*) uc
->uc_mcontext
.mc_eip
;
10770 #elif defined(__dietlibc__)
10771 return (void*) uc
->uc_mcontext
.eip
;
10772 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
10774 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
10776 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
10778 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
10779 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
10780 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
10782 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
10784 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
10785 return (void*) uc
->uc_mcontext
.gregs
[REG_EIP
]; /* Linux 32/64 bit */
10786 #elif defined(__ia64__) /* Linux IA64 */
10787 return (void*) uc
->uc_mcontext
.sc_ip
;
10793 static void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
10795 char **messages
= NULL
;
10796 int i
, trace_size
= 0;
10797 unsigned long offset
=0;
10798 ucontext_t
*uc
= (ucontext_t
*) secret
;
10800 REDIS_NOTUSED(info
);
10802 redisLog(REDIS_WARNING
,
10803 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
10804 infostring
= genRedisInfoString();
10805 redisLog(REDIS_WARNING
, "%s",infostring
);
10806 /* It's not safe to sdsfree() the returned string under memory
10807 * corruption conditions. Let it leak as we are going to abort */
10809 trace_size
= backtrace(trace
, 100);
10810 /* overwrite sigaction with caller's address */
10811 if (getMcontextEip(uc
) != NULL
) {
10812 trace
[1] = getMcontextEip(uc
);
10814 messages
= backtrace_symbols(trace
, trace_size
);
10816 for (i
=1; i
<trace_size
; ++i
) {
10817 char *fn
= findFuncName(trace
[i
], &offset
), *p
;
10819 p
= strchr(messages
[i
],'+');
10820 if (!fn
|| (p
&& ((unsigned long)strtol(p
+1,NULL
,10)) < offset
)) {
10821 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
10823 redisLog(REDIS_WARNING
,"%d redis-server %p %s + %d", i
, trace
[i
], fn
, (unsigned int)offset
);
10826 /* free(messages); Don't call free() with possibly corrupted memory. */
10830 static void sigtermHandler(int sig
) {
10831 REDIS_NOTUSED(sig
);
10833 redisLog(REDIS_WARNING
,"SIGTERM received, scheduling shutting down...");
10834 server
.shutdown_asap
= 1;
10837 static void setupSigSegvAction(void) {
10838 struct sigaction act
;
10840 sigemptyset (&act
.sa_mask
);
10841 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
10842 * is used. Otherwise, sa_handler is used */
10843 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
10844 act
.sa_sigaction
= segvHandler
;
10845 sigaction (SIGSEGV
, &act
, NULL
);
10846 sigaction (SIGBUS
, &act
, NULL
);
10847 sigaction (SIGFPE
, &act
, NULL
);
10848 sigaction (SIGILL
, &act
, NULL
);
10849 sigaction (SIGBUS
, &act
, NULL
);
10851 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
10852 act
.sa_handler
= sigtermHandler
;
10853 sigaction (SIGTERM
, &act
, NULL
);
10857 #include "staticsymbols.h"
10858 /* This function try to convert a pointer into a function name. It's used in
10859 * oreder to provide a backtrace under segmentation fault that's able to
10860 * display functions declared as static (otherwise the backtrace is useless). */
10861 static char *findFuncName(void *pointer
, unsigned long *offset
){
10863 unsigned long off
, minoff
= 0;
10865 /* Try to match against the Symbol with the smallest offset */
10866 for (i
=0; symsTable
[i
].pointer
; i
++) {
10867 unsigned long lp
= (unsigned long) pointer
;
10869 if (lp
!= (unsigned long)-1 && lp
>= symsTable
[i
].pointer
) {
10870 off
=lp
-symsTable
[i
].pointer
;
10871 if (ret
< 0 || off
< minoff
) {
10877 if (ret
== -1) return NULL
;
10879 return symsTable
[ret
].name
;
10881 #else /* HAVE_BACKTRACE */
10882 static void setupSigSegvAction(void) {
10884 #endif /* HAVE_BACKTRACE */