2 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
8 * * Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * * Neither the name of Redis nor the names of its contributors may be used
14 * to endorse or promote products derived from this software without
15 * specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 * POSSIBILITY OF SUCH DAMAGE.
30 #define REDIS_VERSION "2.1.1"
45 #endif /* HAVE_BACKTRACE */
53 #include <arpa/inet.h>
57 #include <sys/resource.h>
65 #include "solarisfixes.h"
69 #include "ae.h" /* Event driven programming library */
70 #include "sds.h" /* Dynamic safe strings */
71 #include "anet.h" /* Networking the easy way */
72 #include "dict.h" /* Hash tables */
73 #include "adlist.h" /* Linked lists */
74 #include "zmalloc.h" /* total memory usage aware version of malloc/free */
75 #include "lzf.h" /* LZF compression library */
76 #include "pqsort.h" /* Partial qsort for SORT+LIMIT */
77 #include "zipmap.h" /* Compact dictionary-alike data structure */
78 #include "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
123 #define REDIS_VMPOINTER 8
125 /* Objects encoding. Some kind of objects like Strings and Hashes can be
126 * internally represented in multiple ways. The 'encoding' field of the object
127 * is set to one of this fields for this object. */
128 #define REDIS_ENCODING_RAW 0 /* Raw representation */
129 #define REDIS_ENCODING_INT 1 /* Encoded as integer */
130 #define REDIS_ENCODING_ZIPMAP 2 /* Encoded as zipmap */
131 #define REDIS_ENCODING_HT 3 /* Encoded as an hash table */
133 static char* strencoding
[] = {
134 "raw", "int", "zipmap", "hashtable"
137 /* Object types only used for dumping to disk */
138 #define REDIS_EXPIRETIME 253
139 #define REDIS_SELECTDB 254
140 #define REDIS_EOF 255
142 /* Defines related to the dump file format. To store 32 bits lengths for short
143 * keys requires a lot of space, so we check the most significant 2 bits of
144 * the first byte to interpreter the length:
146 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
147 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
148 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
149 * 11|000000 this means: specially encoded object will follow. The six bits
150 * number specify the kind of object that follows.
151 * See the REDIS_RDB_ENC_* defines.
153 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
154 * values, will fit inside. */
155 #define REDIS_RDB_6BITLEN 0
156 #define REDIS_RDB_14BITLEN 1
157 #define REDIS_RDB_32BITLEN 2
158 #define REDIS_RDB_ENCVAL 3
159 #define REDIS_RDB_LENERR UINT_MAX
161 /* When a length of a string object stored on disk has the first two bits
162 * set, the remaining two bits specify a special encoding for the object
163 * accordingly to the following defines: */
164 #define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
165 #define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
166 #define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
167 #define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
169 /* Virtual memory object->where field. */
170 #define REDIS_VM_MEMORY 0 /* The object is on memory */
171 #define REDIS_VM_SWAPPED 1 /* The object is on disk */
172 #define REDIS_VM_SWAPPING 2 /* Redis is swapping this object on disk */
173 #define REDIS_VM_LOADING 3 /* Redis is loading this object from disk */
175 /* Virtual memory static configuration stuff.
176 * Check vmFindContiguousPages() to know more about this magic numbers. */
177 #define REDIS_VM_MAX_NEAR_PAGES 65536
178 #define REDIS_VM_MAX_RANDOM_JUMP 4096
179 #define REDIS_VM_MAX_THREADS 32
180 #define REDIS_THREAD_STACK_SIZE (1024*1024*4)
181 /* The following is the *percentage* of completed I/O jobs to process when the
182 * handelr is called. While Virtual Memory I/O operations are performed by
183 * threads, this operations must be processed by the main thread when completed
184 * in order to take effect. */
185 #define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
188 #define REDIS_SLAVE 1 /* This client is a slave server */
189 #define REDIS_MASTER 2 /* This client is a master server */
190 #define REDIS_MONITOR 4 /* This client is a slave monitor, see MONITOR */
191 #define REDIS_MULTI 8 /* This client is in a MULTI context */
192 #define REDIS_BLOCKED 16 /* The client is waiting in a blocking operation */
193 #define REDIS_IO_WAIT 32 /* The client is waiting for Virtual Memory I/O */
194 #define REDIS_DIRTY_CAS 64 /* Watched keys modified. EXEC will fail. */
196 /* Slave replication state - slave side */
197 #define REDIS_REPL_NONE 0 /* No active replication */
198 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
199 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
201 /* Slave replication state - from the point of view of master
202 * Note that in SEND_BULK and ONLINE state the slave receives new updates
203 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
204 * to start the next background saving in order to send updates to it. */
205 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
206 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
207 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
208 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
210 /* List related stuff */
214 /* Sort operations */
215 #define REDIS_SORT_GET 0
216 #define REDIS_SORT_ASC 1
217 #define REDIS_SORT_DESC 2
218 #define REDIS_SORTKEY_MAX 1024
221 #define REDIS_DEBUG 0
222 #define REDIS_VERBOSE 1
223 #define REDIS_NOTICE 2
224 #define REDIS_WARNING 3
226 /* Anti-warning macro... */
227 #define REDIS_NOTUSED(V) ((void) V)
229 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
230 #define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
232 /* Append only defines */
233 #define APPENDFSYNC_NO 0
234 #define APPENDFSYNC_ALWAYS 1
235 #define APPENDFSYNC_EVERYSEC 2
237 /* Hashes related defaults */
238 #define REDIS_HASH_MAX_ZIPMAP_ENTRIES 64
239 #define REDIS_HASH_MAX_ZIPMAP_VALUE 512
241 /* We can print the stacktrace, so our assert is defined this way: */
242 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),_exit(1)))
243 #define redisPanic(_e) _redisPanic(#_e,__FILE__,__LINE__),_exit(1)
244 static void _redisAssert(char *estr
, char *file
, int line
);
245 static void _redisPanic(char *msg
, char *file
, int line
);
247 /*================================= Data types ============================== */
249 /* A redis object, that is a type able to hold a string / list / set */
251 /* The actual Redis Object */
252 typedef struct redisObject
{
254 unsigned storage
:2; /* REDIS_VM_MEMORY or REDIS_VM_SWAPPING */
256 unsigned lru
:22; /* lru time (relative to server.lruclock) */
259 /* VM fields, this are only allocated if VM is active, otherwise the
260 * object allocation function will just allocate
261 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
262 * Redis without VM active will not have any overhead. */
265 /* The VM pointer structure - identifies an object in the swap file.
267 * This object is stored in place of the value
268 * object in the main key->value hash table representing a database.
269 * Note that the first fields (type, storage) are the same as the redisObject
270 * structure so that vmPointer strucuters can be accessed even when casted
271 * as redisObject structures.
273 * This is useful as we don't know if a value object is or not on disk, but we
274 * are always able to read obj->storage to check this. For vmPointer
275 * structures "type" is set to REDIS_VMPOINTER (even if without this field
276 * is still possible to check the kind of object from the value of 'storage').*/
277 typedef struct vmPointer
{
279 unsigned storage
:2; /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
281 unsigned int vtype
; /* type of the object stored in the swap file */
282 off_t page
; /* the page at witch the object is stored on disk */
283 off_t usedpages
; /* number of pages used on disk */
286 /* Macro used to initalize a Redis object allocated on the stack.
287 * Note that this macro is taken near the structure definition to make sure
288 * we'll update it when the structure is changed, to avoid bugs like
289 * bug #85 introduced exactly in this way. */
290 #define initStaticStringObject(_var,_ptr) do { \
292 _var.type = REDIS_STRING; \
293 _var.encoding = REDIS_ENCODING_RAW; \
295 _var.storage = REDIS_VM_MEMORY; \
298 typedef struct redisDb
{
299 dict
*dict
; /* The keyspace for this DB */
300 dict
*expires
; /* Timeout of keys with a timeout set */
301 dict
*blocking_keys
; /* Keys with clients waiting for data (BLPOP) */
302 dict
*io_keys
; /* Keys with clients waiting for VM I/O */
303 dict
*watched_keys
; /* WATCHED keys for MULTI/EXEC CAS */
307 /* Client MULTI/EXEC state */
308 typedef struct multiCmd
{
311 struct redisCommand
*cmd
;
314 typedef struct multiState
{
315 multiCmd
*commands
; /* Array of MULTI commands */
316 int count
; /* Total number of MULTI commands */
319 /* With multiplexing we need to take per-clinet state.
320 * Clients are taken in a liked list. */
321 typedef struct redisClient
{
326 robj
**argv
, **mbargv
;
328 int bulklen
; /* bulk read len. -1 if not in bulk read mode */
329 int multibulk
; /* multi bulk command format active */
332 time_t lastinteraction
; /* time of the last interaction, used for timeout */
333 int flags
; /* REDIS_SLAVE | REDIS_MONITOR | REDIS_MULTI ... */
334 int slaveseldb
; /* slave selected db, if this client is a slave */
335 int authenticated
; /* when requirepass is non-NULL */
336 int replstate
; /* replication state if this is a slave */
337 int repldbfd
; /* replication DB file descriptor */
338 long repldboff
; /* replication DB file offset */
339 off_t repldbsize
; /* replication DB file size */
340 multiState mstate
; /* MULTI/EXEC state */
341 robj
**blocking_keys
; /* The key we are waiting to terminate a blocking
342 * operation such as BLPOP. Otherwise NULL. */
343 int blocking_keys_num
; /* Number of blocking keys */
344 time_t blockingto
; /* Blocking operation timeout. If UNIX current time
345 * is >= blockingto then the operation timed out. */
346 list
*io_keys
; /* Keys this client is waiting to be loaded from the
347 * swap file in order to continue. */
348 list
*watched_keys
; /* Keys WATCHED for MULTI/EXEC CAS */
349 dict
*pubsub_channels
; /* channels a client is interested in (SUBSCRIBE) */
350 list
*pubsub_patterns
; /* patterns a client is interested in (SUBSCRIBE) */
358 /* Global server state structure */
363 long long dirty
; /* changes to DB from the last save */
365 list
*slaves
, *monitors
;
366 char neterr
[ANET_ERR_LEN
];
368 int cronloops
; /* number of times the cron function run */
369 list
*objfreelist
; /* A list of freed objects to avoid malloc() */
370 time_t lastsave
; /* Unix time of last save succeeede */
371 /* Fields used only for stats */
372 time_t stat_starttime
; /* server start time */
373 long long stat_numcommands
; /* number of processed commands */
374 long long stat_numconnections
; /* number of connections received */
375 long long stat_expiredkeys
; /* number of expired keys */
384 int no_appendfsync_on_rewrite
;
390 pid_t bgsavechildpid
;
391 pid_t bgrewritechildpid
;
392 sds bgrewritebuf
; /* buffer taken by parent during oppend only rewrite */
393 sds aofbuf
; /* AOF buffer, written before entering the event loop */
394 struct saveparam
*saveparams
;
399 char *appendfilename
;
403 /* Replication related */
408 redisClient
*master
; /* client that is master for this slave */
410 unsigned int maxclients
;
411 unsigned long long maxmemory
;
412 unsigned int blpop_blocked_clients
;
413 unsigned int vm_blocked_clients
;
414 /* Sort parameters - qsort_r() is only available under BSD so we
415 * have to take this state global, in order to pass it to sortCompare() */
419 /* Virtual memory configuration */
424 unsigned long long vm_max_memory
;
426 size_t hash_max_zipmap_entries
;
427 size_t hash_max_zipmap_value
;
428 /* Virtual memory state */
431 off_t vm_next_page
; /* Next probably empty page */
432 off_t vm_near_pages
; /* Number of pages allocated sequentially */
433 unsigned char *vm_bitmap
; /* Bitmap of free/used pages */
434 time_t unixtime
; /* Unix time sampled every second. */
435 /* Virtual memory I/O threads stuff */
436 /* An I/O thread process an element taken from the io_jobs queue and
437 * put the result of the operation in the io_done list. While the
438 * job is being processed, it's put on io_processing queue. */
439 list
*io_newjobs
; /* List of VM I/O jobs yet to be processed */
440 list
*io_processing
; /* List of VM I/O jobs being processed */
441 list
*io_processed
; /* List of VM I/O jobs already processed */
442 list
*io_ready_clients
; /* Clients ready to be unblocked. All keys loaded */
443 pthread_mutex_t io_mutex
; /* lock to access io_jobs/io_done/io_thread_job */
444 pthread_mutex_t obj_freelist_mutex
; /* safe redis objects creation/free */
445 pthread_mutex_t io_swapfile_mutex
; /* So we can lseek + write */
446 pthread_attr_t io_threads_attr
; /* attributes for threads creation */
447 int io_active_threads
; /* Number of running I/O threads */
448 int vm_max_threads
; /* Max number of I/O threads running at the same time */
449 /* Our main thread is blocked on the event loop, locking for sockets ready
450 * to be read or written, so when a threaded I/O operation is ready to be
451 * processed by the main thread, the I/O thread will use a unix pipe to
452 * awake the main thread. The followings are the two pipe FDs. */
453 int io_ready_pipe_read
;
454 int io_ready_pipe_write
;
455 /* Virtual memory stats */
456 unsigned long long vm_stats_used_pages
;
457 unsigned long long vm_stats_swapped_objects
;
458 unsigned long long vm_stats_swapouts
;
459 unsigned long long vm_stats_swapins
;
461 dict
*pubsub_channels
; /* Map channels to list of subscribed clients */
462 list
*pubsub_patterns
; /* A list of pubsub_patterns */
465 unsigned lruclock
:22; /* clock incrementing every minute, for LRU */
466 unsigned lruclock_padding
:10;
469 typedef struct pubsubPattern
{
474 typedef void redisCommandProc(redisClient
*c
);
475 typedef void redisVmPreloadProc(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
);
476 struct redisCommand
{
478 redisCommandProc
*proc
;
481 /* Use a function to determine which keys need to be loaded
482 * in the background prior to executing this command. Takes precedence
483 * over vm_firstkey and others, ignored when NULL */
484 redisVmPreloadProc
*vm_preload_proc
;
485 /* What keys should be loaded in background when calling this command? */
486 int vm_firstkey
; /* The first argument that's a key (0 = no keys) */
487 int vm_lastkey
; /* THe last argument that's a key */
488 int vm_keystep
; /* The step between first and last key */
491 struct redisFunctionSym
{
493 unsigned long pointer
;
496 typedef struct _redisSortObject
{
504 typedef struct _redisSortOperation
{
507 } redisSortOperation
;
509 /* ZSETs use a specialized version of Skiplists */
511 typedef struct zskiplistNode
{
512 struct zskiplistNode
**forward
;
513 struct zskiplistNode
*backward
;
519 typedef struct zskiplist
{
520 struct zskiplistNode
*header
, *tail
;
521 unsigned long length
;
525 typedef struct zset
{
530 /* Our shared "common" objects */
532 #define REDIS_SHARED_INTEGERS 10000
533 struct sharedObjectsStruct
{
534 robj
*crlf
, *ok
, *err
, *emptybulk
, *czero
, *cone
, *pong
, *space
,
535 *colon
, *nullbulk
, *nullmultibulk
, *queued
,
536 *emptymultibulk
, *wrongtypeerr
, *nokeyerr
, *syntaxerr
, *sameobjecterr
,
537 *outofrangeerr
, *plus
,
538 *select0
, *select1
, *select2
, *select3
, *select4
,
539 *select5
, *select6
, *select7
, *select8
, *select9
,
540 *messagebulk
, *pmessagebulk
, *subscribebulk
, *unsubscribebulk
, *mbulk3
,
541 *mbulk4
, *psubscribebulk
, *punsubscribebulk
,
542 *integers
[REDIS_SHARED_INTEGERS
];
545 /* Global vars that are actally used as constants. The following double
546 * values are used for double on-disk serialization, and are initialized
547 * at runtime to avoid strange compiler optimizations. */
549 static double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
;
551 /* VM threaded I/O request message */
552 #define REDIS_IOJOB_LOAD 0 /* Load from disk to memory */
553 #define REDIS_IOJOB_PREPARE_SWAP 1 /* Compute needed pages */
554 #define REDIS_IOJOB_DO_SWAP 2 /* Swap from memory to disk */
555 typedef struct iojob
{
556 int type
; /* Request type, REDIS_IOJOB_* */
557 redisDb
*db
;/* Redis database */
558 robj
*key
; /* This I/O request is about swapping this key */
559 robj
*id
; /* Unique identifier of this job:
560 this is the object to swap for REDIS_IOREQ_*_SWAP, or the
561 vmpointer objct for REDIS_IOREQ_LOAD. */
562 robj
*val
; /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
563 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
564 off_t page
; /* Swap page where to read/write the object */
565 off_t pages
; /* Swap pages needed to save object. PREPARE_SWAP return val */
566 int canceled
; /* True if this command was canceled by blocking side of VM */
567 pthread_t thread
; /* ID of the thread processing this entry */
570 /*================================ Prototypes =============================== */
572 static void freeStringObject(robj
*o
);
573 static void freeListObject(robj
*o
);
574 static void freeSetObject(robj
*o
);
575 static void decrRefCount(void *o
);
576 static robj
*createObject(int type
, void *ptr
);
577 static void freeClient(redisClient
*c
);
578 static int rdbLoad(char *filename
);
579 static void addReply(redisClient
*c
, robj
*obj
);
580 static void addReplySds(redisClient
*c
, sds s
);
581 static void incrRefCount(robj
*o
);
582 static int rdbSaveBackground(char *filename
);
583 static robj
*createStringObject(char *ptr
, size_t len
);
584 static robj
*dupStringObject(robj
*o
);
585 static void replicationFeedSlaves(list
*slaves
, int dictid
, robj
**argv
, int argc
);
586 static void replicationFeedMonitors(list
*monitors
, int dictid
, robj
**argv
, int argc
);
587 static void flushAppendOnlyFile(void);
588 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
589 static int syncWithMaster(void);
590 static robj
*tryObjectEncoding(robj
*o
);
591 static robj
*getDecodedObject(robj
*o
);
592 static int removeExpire(redisDb
*db
, robj
*key
);
593 static int expireIfNeeded(redisDb
*db
, robj
*key
);
594 static int deleteIfVolatile(redisDb
*db
, robj
*key
);
595 static int deleteIfSwapped(redisDb
*db
, robj
*key
);
596 static int deleteKey(redisDb
*db
, robj
*key
);
597 static time_t getExpire(redisDb
*db
, robj
*key
);
598 static int setExpire(redisDb
*db
, robj
*key
, time_t when
);
599 static void updateSlavesWaitingBgsave(int bgsaveerr
);
600 static void freeMemoryIfNeeded(void);
601 static int processCommand(redisClient
*c
);
602 static void setupSigSegvAction(void);
603 static void rdbRemoveTempFile(pid_t childpid
);
604 static void aofRemoveTempFile(pid_t childpid
);
605 static size_t stringObjectLen(robj
*o
);
606 static void processInputBuffer(redisClient
*c
);
607 static zskiplist
*zslCreate(void);
608 static void zslFree(zskiplist
*zsl
);
609 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
);
610 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
611 static void initClientMultiState(redisClient
*c
);
612 static void freeClientMultiState(redisClient
*c
);
613 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
);
614 static void unblockClientWaitingData(redisClient
*c
);
615 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
);
616 static void vmInit(void);
617 static void vmMarkPagesFree(off_t page
, off_t count
);
618 static robj
*vmLoadObject(robj
*o
);
619 static robj
*vmPreviewObject(robj
*o
);
620 static int vmSwapOneObjectBlocking(void);
621 static int vmSwapOneObjectThreaded(void);
622 static int vmCanSwapOut(void);
623 static int tryFreeOneObjectFromFreelist(void);
624 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
625 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
626 static void vmCancelThreadedIOJob(robj
*o
);
627 static void lockThreadedIO(void);
628 static void unlockThreadedIO(void);
629 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
);
630 static void freeIOJob(iojob
*j
);
631 static void queueIOJob(iojob
*j
);
632 static int vmWriteObjectOnSwap(robj
*o
, off_t page
);
633 static robj
*vmReadObjectFromSwap(off_t page
, int type
);
634 static void waitEmptyIOJobsQueue(void);
635 static void vmReopenSwapFile(void);
636 static int vmFreePage(off_t page
);
637 static void zunionInterBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
);
638 static void execBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
);
639 static int blockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
);
640 static int dontWaitForSwappedKey(redisClient
*c
, robj
*key
);
641 static void handleClientsBlockedOnSwappedKey(redisDb
*db
, robj
*key
);
642 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
643 static struct redisCommand
*lookupCommand(char *name
);
644 static void call(redisClient
*c
, struct redisCommand
*cmd
);
645 static void resetClient(redisClient
*c
);
646 static void convertToRealHash(robj
*o
);
647 static int pubsubUnsubscribeAllChannels(redisClient
*c
, int notify
);
648 static int pubsubUnsubscribeAllPatterns(redisClient
*c
, int notify
);
649 static void freePubsubPattern(void *p
);
650 static int listMatchPubsubPattern(void *a
, void *b
);
651 static int compareStringObjects(robj
*a
, robj
*b
);
652 static int equalStringObjects(robj
*a
, robj
*b
);
654 static int rewriteAppendOnlyFileBackground(void);
655 static vmpointer
*vmSwapObjectBlocking(robj
*val
);
656 static int prepareForShutdown();
657 static void touchWatchedKey(redisDb
*db
, robj
*key
);
658 static void touchWatchedKeysOnFlush(int dbid
);
659 static void unwatchAllKeys(redisClient
*c
);
661 static void authCommand(redisClient
*c
);
662 static void pingCommand(redisClient
*c
);
663 static void echoCommand(redisClient
*c
);
664 static void setCommand(redisClient
*c
);
665 static void setnxCommand(redisClient
*c
);
666 static void setexCommand(redisClient
*c
);
667 static void getCommand(redisClient
*c
);
668 static void delCommand(redisClient
*c
);
669 static void existsCommand(redisClient
*c
);
670 static void incrCommand(redisClient
*c
);
671 static void decrCommand(redisClient
*c
);
672 static void incrbyCommand(redisClient
*c
);
673 static void decrbyCommand(redisClient
*c
);
674 static void selectCommand(redisClient
*c
);
675 static void randomkeyCommand(redisClient
*c
);
676 static void keysCommand(redisClient
*c
);
677 static void dbsizeCommand(redisClient
*c
);
678 static void lastsaveCommand(redisClient
*c
);
679 static void saveCommand(redisClient
*c
);
680 static void bgsaveCommand(redisClient
*c
);
681 static void bgrewriteaofCommand(redisClient
*c
);
682 static void shutdownCommand(redisClient
*c
);
683 static void moveCommand(redisClient
*c
);
684 static void renameCommand(redisClient
*c
);
685 static void renamenxCommand(redisClient
*c
);
686 static void lpushCommand(redisClient
*c
);
687 static void rpushCommand(redisClient
*c
);
688 static void lpopCommand(redisClient
*c
);
689 static void rpopCommand(redisClient
*c
);
690 static void llenCommand(redisClient
*c
);
691 static void lindexCommand(redisClient
*c
);
692 static void lrangeCommand(redisClient
*c
);
693 static void ltrimCommand(redisClient
*c
);
694 static void typeCommand(redisClient
*c
);
695 static void lsetCommand(redisClient
*c
);
696 static void saddCommand(redisClient
*c
);
697 static void sremCommand(redisClient
*c
);
698 static void smoveCommand(redisClient
*c
);
699 static void sismemberCommand(redisClient
*c
);
700 static void scardCommand(redisClient
*c
);
701 static void spopCommand(redisClient
*c
);
702 static void srandmemberCommand(redisClient
*c
);
703 static void sinterCommand(redisClient
*c
);
704 static void sinterstoreCommand(redisClient
*c
);
705 static void sunionCommand(redisClient
*c
);
706 static void sunionstoreCommand(redisClient
*c
);
707 static void sdiffCommand(redisClient
*c
);
708 static void sdiffstoreCommand(redisClient
*c
);
709 static void syncCommand(redisClient
*c
);
710 static void flushdbCommand(redisClient
*c
);
711 static void flushallCommand(redisClient
*c
);
712 static void sortCommand(redisClient
*c
);
713 static void lremCommand(redisClient
*c
);
714 static void rpoplpushcommand(redisClient
*c
);
715 static void infoCommand(redisClient
*c
);
716 static void mgetCommand(redisClient
*c
);
717 static void monitorCommand(redisClient
*c
);
718 static void expireCommand(redisClient
*c
);
719 static void expireatCommand(redisClient
*c
);
720 static void getsetCommand(redisClient
*c
);
721 static void ttlCommand(redisClient
*c
);
722 static void slaveofCommand(redisClient
*c
);
723 static void debugCommand(redisClient
*c
);
724 static void msetCommand(redisClient
*c
);
725 static void msetnxCommand(redisClient
*c
);
726 static void zaddCommand(redisClient
*c
);
727 static void zincrbyCommand(redisClient
*c
);
728 static void zrangeCommand(redisClient
*c
);
729 static void zrangebyscoreCommand(redisClient
*c
);
730 static void zcountCommand(redisClient
*c
);
731 static void zrevrangeCommand(redisClient
*c
);
732 static void zcardCommand(redisClient
*c
);
733 static void zremCommand(redisClient
*c
);
734 static void zscoreCommand(redisClient
*c
);
735 static void zremrangebyscoreCommand(redisClient
*c
);
736 static void multiCommand(redisClient
*c
);
737 static void execCommand(redisClient
*c
);
738 static void discardCommand(redisClient
*c
);
739 static void blpopCommand(redisClient
*c
);
740 static void brpopCommand(redisClient
*c
);
741 static void appendCommand(redisClient
*c
);
742 static void substrCommand(redisClient
*c
);
743 static void zrankCommand(redisClient
*c
);
744 static void zrevrankCommand(redisClient
*c
);
745 static void hsetCommand(redisClient
*c
);
746 static void hsetnxCommand(redisClient
*c
);
747 static void hgetCommand(redisClient
*c
);
748 static void hmsetCommand(redisClient
*c
);
749 static void hmgetCommand(redisClient
*c
);
750 static void hdelCommand(redisClient
*c
);
751 static void hlenCommand(redisClient
*c
);
752 static void zremrangebyrankCommand(redisClient
*c
);
753 static void zunionstoreCommand(redisClient
*c
);
754 static void zinterstoreCommand(redisClient
*c
);
755 static void hkeysCommand(redisClient
*c
);
756 static void hvalsCommand(redisClient
*c
);
757 static void hgetallCommand(redisClient
*c
);
758 static void hexistsCommand(redisClient
*c
);
759 static void configCommand(redisClient
*c
);
760 static void hincrbyCommand(redisClient
*c
);
761 static void subscribeCommand(redisClient
*c
);
762 static void unsubscribeCommand(redisClient
*c
);
763 static void psubscribeCommand(redisClient
*c
);
764 static void punsubscribeCommand(redisClient
*c
);
765 static void publishCommand(redisClient
*c
);
766 static void watchCommand(redisClient
*c
);
767 static void unwatchCommand(redisClient
*c
);
769 /*================================= Globals ================================= */
772 static struct redisServer server
; /* server global state */
773 static struct redisCommand
*commandTable
;
774 static struct redisCommand readonlyCommandTable
[] = {
775 {"get",getCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
776 {"set",setCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,0,0,0},
777 {"setnx",setnxCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,0,0,0},
778 {"setex",setexCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,0,0,0},
779 {"append",appendCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
780 {"substr",substrCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
781 {"del",delCommand
,-2,REDIS_CMD_INLINE
,NULL
,0,0,0},
782 {"exists",existsCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
783 {"incr",incrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
784 {"decr",decrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
785 {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
,NULL
,1,-1,1},
786 {"rpush",rpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
787 {"lpush",lpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
788 {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
789 {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
790 {"brpop",brpopCommand
,-3,REDIS_CMD_INLINE
,NULL
,1,1,1},
791 {"blpop",blpopCommand
,-3,REDIS_CMD_INLINE
,NULL
,1,1,1},
792 {"llen",llenCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
793 {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
,NULL
,1,1,1},
794 {"lset",lsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
795 {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
796 {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
797 {"lrem",lremCommand
,4,REDIS_CMD_BULK
,NULL
,1,1,1},
798 {"rpoplpush",rpoplpushcommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,2,1},
799 {"sadd",saddCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
800 {"srem",sremCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
801 {"smove",smoveCommand
,4,REDIS_CMD_BULK
,NULL
,1,2,1},
802 {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
803 {"scard",scardCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
804 {"spop",spopCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
805 {"srandmember",srandmemberCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
806 {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
807 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
808 {"sunion",sunionCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
809 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
810 {"sdiff",sdiffCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
811 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
812 {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
813 {"zadd",zaddCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
814 {"zincrby",zincrbyCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
815 {"zrem",zremCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
816 {"zremrangebyscore",zremrangebyscoreCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
817 {"zremrangebyrank",zremrangebyrankCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
818 {"zunionstore",zunionstoreCommand
,-4,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,zunionInterBlockClientOnSwappedKeys
,0,0,0},
819 {"zinterstore",zinterstoreCommand
,-4,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,zunionInterBlockClientOnSwappedKeys
,0,0,0},
820 {"zrange",zrangeCommand
,-4,REDIS_CMD_INLINE
,NULL
,1,1,1},
821 {"zrangebyscore",zrangebyscoreCommand
,-4,REDIS_CMD_INLINE
,NULL
,1,1,1},
822 {"zcount",zcountCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
823 {"zrevrange",zrevrangeCommand
,-4,REDIS_CMD_INLINE
,NULL
,1,1,1},
824 {"zcard",zcardCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
825 {"zscore",zscoreCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
826 {"zrank",zrankCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
827 {"zrevrank",zrevrankCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
828 {"hset",hsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
829 {"hsetnx",hsetnxCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
830 {"hget",hgetCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
831 {"hmset",hmsetCommand
,-4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
832 {"hmget",hmgetCommand
,-3,REDIS_CMD_BULK
,NULL
,1,1,1},
833 {"hincrby",hincrbyCommand
,4,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
834 {"hdel",hdelCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
835 {"hlen",hlenCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
836 {"hkeys",hkeysCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
837 {"hvals",hvalsCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
838 {"hgetall",hgetallCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
839 {"hexists",hexistsCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
840 {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
841 {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
842 {"getset",getsetCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
843 {"mset",msetCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,-1,2},
844 {"msetnx",msetnxCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,-1,2},
845 {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
846 {"select",selectCommand
,2,REDIS_CMD_INLINE
,NULL
,0,0,0},
847 {"move",moveCommand
,3,REDIS_CMD_INLINE
,NULL
,1,1,1},
848 {"rename",renameCommand
,3,REDIS_CMD_INLINE
,NULL
,1,1,1},
849 {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
,NULL
,1,1,1},
850 {"expire",expireCommand
,3,REDIS_CMD_INLINE
,NULL
,0,0,0},
851 {"expireat",expireatCommand
,3,REDIS_CMD_INLINE
,NULL
,0,0,0},
852 {"keys",keysCommand
,2,REDIS_CMD_INLINE
,NULL
,0,0,0},
853 {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
854 {"auth",authCommand
,2,REDIS_CMD_INLINE
,NULL
,0,0,0},
855 {"ping",pingCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
856 {"echo",echoCommand
,2,REDIS_CMD_BULK
,NULL
,0,0,0},
857 {"save",saveCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
858 {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
859 {"bgrewriteaof",bgrewriteaofCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
860 {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
861 {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
862 {"type",typeCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
863 {"multi",multiCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
864 {"exec",execCommand
,1,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,execBlockClientOnSwappedKeys
,0,0,0},
865 {"discard",discardCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
866 {"sync",syncCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
867 {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
868 {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
869 {"sort",sortCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
870 {"info",infoCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
871 {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
872 {"ttl",ttlCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
873 {"slaveof",slaveofCommand
,3,REDIS_CMD_INLINE
,NULL
,0,0,0},
874 {"debug",debugCommand
,-2,REDIS_CMD_INLINE
,NULL
,0,0,0},
875 {"config",configCommand
,-2,REDIS_CMD_BULK
,NULL
,0,0,0},
876 {"subscribe",subscribeCommand
,-2,REDIS_CMD_INLINE
,NULL
,0,0,0},
877 {"unsubscribe",unsubscribeCommand
,-1,REDIS_CMD_INLINE
,NULL
,0,0,0},
878 {"psubscribe",psubscribeCommand
,-2,REDIS_CMD_INLINE
,NULL
,0,0,0},
879 {"punsubscribe",punsubscribeCommand
,-1,REDIS_CMD_INLINE
,NULL
,0,0,0},
880 {"publish",publishCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_FORCE_REPLICATION
,NULL
,0,0,0},
881 {"watch",watchCommand
,-2,REDIS_CMD_INLINE
,NULL
,0,0,0},
882 {"unwatch",unwatchCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0}
885 /*============================ Utility functions ============================ */
887 /* Glob-style pattern matching. */
888 static int stringmatchlen(const char *pattern
, int patternLen
,
889 const char *string
, int stringLen
, int nocase
)
894 while (pattern
[1] == '*') {
899 return 1; /* match */
901 if (stringmatchlen(pattern
+1, patternLen
-1,
902 string
, stringLen
, nocase
))
903 return 1; /* match */
907 return 0; /* no match */
911 return 0; /* no match */
921 not = pattern
[0] == '^';
928 if (pattern
[0] == '\\') {
931 if (pattern
[0] == string
[0])
933 } else if (pattern
[0] == ']') {
935 } else if (patternLen
== 0) {
939 } else if (pattern
[1] == '-' && patternLen
>= 3) {
940 int start
= pattern
[0];
941 int end
= pattern
[2];
949 start
= tolower(start
);
955 if (c
>= start
&& c
<= end
)
959 if (pattern
[0] == string
[0])
962 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
972 return 0; /* no match */
978 if (patternLen
>= 2) {
985 if (pattern
[0] != string
[0])
986 return 0; /* no match */
988 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
989 return 0; /* no match */
997 if (stringLen
== 0) {
998 while(*pattern
== '*') {
1005 if (patternLen
== 0 && stringLen
== 0)
1010 static int stringmatch(const char *pattern
, const char *string
, int nocase
) {
1011 return stringmatchlen(pattern
,strlen(pattern
),string
,strlen(string
),nocase
);
1014 /* Convert a string representing an amount of memory into the number of
1015 * bytes, so for instance memtoll("1Gi") will return 1073741824 that is
1018 * On parsing error, if *err is not NULL, it's set to 1, otherwise it's
1020 static long long memtoll(const char *p
, int *err
) {
1023 long mul
; /* unit multiplier */
1025 unsigned int digits
;
1028 /* Search the first non digit character. */
1031 while(*u
&& isdigit(*u
)) u
++;
1032 if (*u
== '\0' || !strcasecmp(u
,"b")) {
1034 } else if (!strcasecmp(u
,"k")) {
1036 } else if (!strcasecmp(u
,"kb")) {
1038 } else if (!strcasecmp(u
,"m")) {
1040 } else if (!strcasecmp(u
,"mb")) {
1042 } else if (!strcasecmp(u
,"g")) {
1043 mul
= 1000L*1000*1000;
1044 } else if (!strcasecmp(u
,"gb")) {
1045 mul
= 1024L*1024*1024;
1051 if (digits
>= sizeof(buf
)) {
1055 memcpy(buf
,p
,digits
);
1057 val
= strtoll(buf
,NULL
,10);
1061 /* Convert a long long into a string. Returns the number of
1062 * characters needed to represent the number, that can be shorter if passed
1063 * buffer length is not enough to store the whole number. */
1064 static int ll2string(char *s
, size_t len
, long long value
) {
1066 unsigned long long v
;
1069 if (len
== 0) return 0;
1070 v
= (value
< 0) ? -value
: value
;
1071 p
= buf
+31; /* point to the last character */
1076 if (value
< 0) *p
-- = '-';
1079 if (l
+1 > len
) l
= len
-1; /* Make sure it fits, including the nul term */
1085 static void redisLog(int level
, const char *fmt
, ...) {
1089 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
1093 if (level
>= server
.verbosity
) {
1099 strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
));
1100 fprintf(fp
,"[%d] %s %c ",(int)getpid(),buf
,c
[level
]);
1101 vfprintf(fp
, fmt
, ap
);
1107 if (server
.logfile
) fclose(fp
);
1110 /*====================== Hash table type implementation ==================== */
1112 /* This is an hash table type that uses the SDS dynamic strings libary as
1113 * keys and radis objects as values (objects can hold SDS strings,
1116 static void dictVanillaFree(void *privdata
, void *val
)
1118 DICT_NOTUSED(privdata
);
1122 static void dictListDestructor(void *privdata
, void *val
)
1124 DICT_NOTUSED(privdata
);
1125 listRelease((list
*)val
);
1128 static int sdsDictKeyCompare(void *privdata
, const void *key1
,
1132 DICT_NOTUSED(privdata
);
1134 l1
= sdslen((sds
)key1
);
1135 l2
= sdslen((sds
)key2
);
1136 if (l1
!= l2
) return 0;
1137 return memcmp(key1
, key2
, l1
) == 0;
1140 static void dictRedisObjectDestructor(void *privdata
, void *val
)
1142 DICT_NOTUSED(privdata
);
1144 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
1148 static int dictObjKeyCompare(void *privdata
, const void *key1
,
1151 const robj
*o1
= key1
, *o2
= key2
;
1152 return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
1155 static unsigned int dictObjHash(const void *key
) {
1156 const robj
*o
= key
;
1157 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
1160 static int dictEncObjKeyCompare(void *privdata
, const void *key1
,
1163 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
1166 if (o1
->encoding
== REDIS_ENCODING_INT
&&
1167 o2
->encoding
== REDIS_ENCODING_INT
)
1168 return o1
->ptr
== o2
->ptr
;
1170 o1
= getDecodedObject(o1
);
1171 o2
= getDecodedObject(o2
);
1172 cmp
= sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
1178 static unsigned int dictEncObjHash(const void *key
) {
1179 robj
*o
= (robj
*) key
;
1181 if (o
->encoding
== REDIS_ENCODING_RAW
) {
1182 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
1184 if (o
->encoding
== REDIS_ENCODING_INT
) {
1188 len
= ll2string(buf
,32,(long)o
->ptr
);
1189 return dictGenHashFunction((unsigned char*)buf
, len
);
1193 o
= getDecodedObject(o
);
1194 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
1201 /* Sets type and expires */
1202 static dictType setDictType
= {
1203 dictEncObjHash
, /* hash function */
1206 dictEncObjKeyCompare
, /* key compare */
1207 dictRedisObjectDestructor
, /* key destructor */
1208 NULL
/* val destructor */
1211 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
1212 static dictType zsetDictType
= {
1213 dictEncObjHash
, /* hash function */
1216 dictEncObjKeyCompare
, /* key compare */
1217 dictRedisObjectDestructor
, /* key destructor */
1218 dictVanillaFree
/* val destructor of malloc(sizeof(double)) */
1222 static dictType dbDictType
= {
1223 dictObjHash
, /* hash function */
1226 dictObjKeyCompare
, /* key compare */
1227 dictRedisObjectDestructor
, /* key destructor */
1228 dictRedisObjectDestructor
/* val destructor */
1232 static dictType keyptrDictType
= {
1233 dictObjHash
, /* hash function */
1236 dictObjKeyCompare
, /* key compare */
1237 dictRedisObjectDestructor
, /* key destructor */
1238 NULL
/* val destructor */
1241 /* Hash type hash table (note that small hashes are represented with zimpaps) */
1242 static dictType hashDictType
= {
1243 dictEncObjHash
, /* hash function */
1246 dictEncObjKeyCompare
, /* key compare */
1247 dictRedisObjectDestructor
, /* key destructor */
1248 dictRedisObjectDestructor
/* val destructor */
1251 /* Keylist hash table type has unencoded redis objects as keys and
1252 * lists as values. It's used for blocking operations (BLPOP) and to
1253 * map swapped keys to a list of clients waiting for this keys to be loaded. */
1254 static dictType keylistDictType
= {
1255 dictObjHash
, /* hash function */
1258 dictObjKeyCompare
, /* key compare */
1259 dictRedisObjectDestructor
, /* key destructor */
1260 dictListDestructor
/* val destructor */
1263 static void version();
1265 /* ========================= Random utility functions ======================= */
1267 /* Redis generally does not try to recover from out of memory conditions
1268 * when allocating objects or strings, it is not clear if it will be possible
1269 * to report this condition to the client since the networking layer itself
1270 * is based on heap allocation for send buffers, so we simply abort.
1271 * At least the code will be simpler to read... */
1272 static void oom(const char *msg
) {
1273 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
1278 /* ====================== Redis server networking stuff ===================== */
1279 static void closeTimedoutClients(void) {
1282 time_t now
= time(NULL
);
1285 listRewind(server
.clients
,&li
);
1286 while ((ln
= listNext(&li
)) != NULL
) {
1287 c
= listNodeValue(ln
);
1288 if (server
.maxidletime
&&
1289 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
1290 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
1291 dictSize(c
->pubsub_channels
) == 0 && /* no timeout for pubsub */
1292 listLength(c
->pubsub_patterns
) == 0 &&
1293 (now
- c
->lastinteraction
> server
.maxidletime
))
1295 redisLog(REDIS_VERBOSE
,"Closing idle client");
1297 } else if (c
->flags
& REDIS_BLOCKED
) {
1298 if (c
->blockingto
!= 0 && c
->blockingto
< now
) {
1299 addReply(c
,shared
.nullmultibulk
);
1300 unblockClientWaitingData(c
);
1306 static int htNeedsResize(dict
*dict
) {
1307 long long size
, used
;
1309 size
= dictSlots(dict
);
1310 used
= dictSize(dict
);
1311 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
1312 (used
*100/size
< REDIS_HT_MINFILL
));
1315 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
1316 * we resize the hash table to save memory */
1317 static void tryResizeHashTables(void) {
1320 for (j
= 0; j
< server
.dbnum
; j
++) {
1321 if (htNeedsResize(server
.db
[j
].dict
))
1322 dictResize(server
.db
[j
].dict
);
1323 if (htNeedsResize(server
.db
[j
].expires
))
1324 dictResize(server
.db
[j
].expires
);
1328 /* Our hash table implementation performs rehashing incrementally while
1329 * we write/read from the hash table. Still if the server is idle, the hash
1330 * table will use two tables for a long time. So we try to use 1 millisecond
1331 * of CPU time at every serverCron() loop in order to rehash some key. */
1332 static void incrementallyRehash(void) {
1335 for (j
= 0; j
< server
.dbnum
; j
++) {
1336 if (dictIsRehashing(server
.db
[j
].dict
)) {
1337 dictRehashMilliseconds(server
.db
[j
].dict
,1);
1338 break; /* already used our millisecond for this loop... */
1343 /* A background saving child (BGSAVE) terminated its work. Handle this. */
1344 void backgroundSaveDoneHandler(int statloc
) {
1345 int exitcode
= WEXITSTATUS(statloc
);
1346 int bysignal
= WIFSIGNALED(statloc
);
1348 if (!bysignal
&& exitcode
== 0) {
1349 redisLog(REDIS_NOTICE
,
1350 "Background saving terminated with success");
1352 server
.lastsave
= time(NULL
);
1353 } else if (!bysignal
&& exitcode
!= 0) {
1354 redisLog(REDIS_WARNING
, "Background saving error");
1356 redisLog(REDIS_WARNING
,
1357 "Background saving terminated by signal %d", WTERMSIG(statloc
));
1358 rdbRemoveTempFile(server
.bgsavechildpid
);
1360 server
.bgsavechildpid
= -1;
1361 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1362 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1363 updateSlavesWaitingBgsave(exitcode
== 0 ? REDIS_OK
: REDIS_ERR
);
1366 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1368 void backgroundRewriteDoneHandler(int statloc
) {
1369 int exitcode
= WEXITSTATUS(statloc
);
1370 int bysignal
= WIFSIGNALED(statloc
);
1372 if (!bysignal
&& exitcode
== 0) {
1376 redisLog(REDIS_NOTICE
,
1377 "Background append only file rewriting terminated with success");
1378 /* Now it's time to flush the differences accumulated by the parent */
1379 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) server
.bgrewritechildpid
);
1380 fd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
1382 redisLog(REDIS_WARNING
, "Not able to open the temp append only file produced by the child: %s", strerror(errno
));
1385 /* Flush our data... */
1386 if (write(fd
,server
.bgrewritebuf
,sdslen(server
.bgrewritebuf
)) !=
1387 (signed) sdslen(server
.bgrewritebuf
)) {
1388 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
));
1392 redisLog(REDIS_NOTICE
,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server
.bgrewritebuf
));
1393 /* Now our work is to rename the temp file into the stable file. And
1394 * switch the file descriptor used by the server for append only. */
1395 if (rename(tmpfile
,server
.appendfilename
) == -1) {
1396 redisLog(REDIS_WARNING
,"Can't rename the temp append only file into the stable one: %s", strerror(errno
));
1400 /* Mission completed... almost */
1401 redisLog(REDIS_NOTICE
,"Append only file successfully rewritten.");
1402 if (server
.appendfd
!= -1) {
1403 /* If append only is actually enabled... */
1404 close(server
.appendfd
);
1405 server
.appendfd
= fd
;
1406 if (server
.appendfsync
!= APPENDFSYNC_NO
) aof_fsync(fd
);
1407 server
.appendseldb
= -1; /* Make sure it will issue SELECT */
1408 redisLog(REDIS_NOTICE
,"The new append only file was selected for future appends.");
1410 /* If append only is disabled we just generate a dump in this
1411 * format. Why not? */
1414 } else if (!bysignal
&& exitcode
!= 0) {
1415 redisLog(REDIS_WARNING
, "Background append only file rewriting error");
1417 redisLog(REDIS_WARNING
,
1418 "Background append only file rewriting terminated by signal %d",
1422 sdsfree(server
.bgrewritebuf
);
1423 server
.bgrewritebuf
= sdsempty();
1424 aofRemoveTempFile(server
.bgrewritechildpid
);
1425 server
.bgrewritechildpid
= -1;
1428 /* This function is called once a background process of some kind terminates,
1429 * as we want to avoid resizing the hash tables when there is a child in order
1430 * to play well with copy-on-write (otherwise when a resize happens lots of
1431 * memory pages are copied). The goal of this function is to update the ability
1432 * for dict.c to resize the hash tables accordingly to the fact we have o not
1433 * running childs. */
1434 static void updateDictResizePolicy(void) {
1435 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1)
1438 dictDisableResize();
1441 static int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
1442 int j
, loops
= server
.cronloops
++;
1443 REDIS_NOTUSED(eventLoop
);
1445 REDIS_NOTUSED(clientData
);
1447 /* We take a cached value of the unix time in the global state because
1448 * with virtual memory and aging there is to store the current time
1449 * in objects at every object access, and accuracy is not needed.
1450 * To access a global var is faster than calling time(NULL) */
1451 server
.unixtime
= time(NULL
);
1452 /* We have just 21 bits per object for LRU information.
1453 * So we use an (eventually wrapping) LRU clock with minutes resolution.
1455 * When we need to select what object to swap, we compute the minimum
1456 * time distance between the current lruclock and the object last access
1457 * lruclock info. Even if clocks will wrap on overflow, there is
1458 * the interesting property that we are sure that at least
1459 * ABS(A-B) minutes passed between current time and timestamp B.
1461 * This is not precise but we don't need at all precision, but just
1462 * something statistically reasonable.
1464 server
.lruclock
= (time(NULL
)/60)&((1<<21)-1);
1466 /* We received a SIGTERM, shutting down here in a safe way, as it is
1467 * not ok doing so inside the signal handler. */
1468 if (server
.shutdown_asap
) {
1469 if (prepareForShutdown() == REDIS_OK
) exit(0);
1470 redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
1473 /* Show some info about non-empty databases */
1474 for (j
= 0; j
< server
.dbnum
; j
++) {
1475 long long size
, used
, vkeys
;
1477 size
= dictSlots(server
.db
[j
].dict
);
1478 used
= dictSize(server
.db
[j
].dict
);
1479 vkeys
= dictSize(server
.db
[j
].expires
);
1480 if (!(loops
% 50) && (used
|| vkeys
)) {
1481 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
1482 /* dictPrintStats(server.dict); */
1486 /* We don't want to resize the hash tables while a bacground saving
1487 * is in progress: the saving child is created using fork() that is
1488 * implemented with a copy-on-write semantic in most modern systems, so
1489 * if we resize the HT while there is the saving child at work actually
1490 * a lot of memory movements in the parent will cause a lot of pages
1492 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1) {
1493 if (!(loops
% 10)) tryResizeHashTables();
1494 if (server
.activerehashing
) incrementallyRehash();
1497 /* Show information about connected clients */
1498 if (!(loops
% 50)) {
1499 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use",
1500 listLength(server
.clients
)-listLength(server
.slaves
),
1501 listLength(server
.slaves
),
1502 zmalloc_used_memory());
1505 /* Close connections of timedout clients */
1506 if ((server
.maxidletime
&& !(loops
% 100)) || server
.blpop_blocked_clients
)
1507 closeTimedoutClients();
1509 /* Check if a background saving or AOF rewrite in progress terminated */
1510 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
1514 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
1515 if (pid
== server
.bgsavechildpid
) {
1516 backgroundSaveDoneHandler(statloc
);
1518 backgroundRewriteDoneHandler(statloc
);
1520 updateDictResizePolicy();
1523 /* If there is not a background saving in progress check if
1524 * we have to save now */
1525 time_t now
= time(NULL
);
1526 for (j
= 0; j
< server
.saveparamslen
; j
++) {
1527 struct saveparam
*sp
= server
.saveparams
+j
;
1529 if (server
.dirty
>= sp
->changes
&&
1530 now
-server
.lastsave
> sp
->seconds
) {
1531 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
1532 sp
->changes
, sp
->seconds
);
1533 rdbSaveBackground(server
.dbfilename
);
1539 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1540 * will use few CPU cycles if there are few expiring keys, otherwise
1541 * it will get more aggressive to avoid that too much memory is used by
1542 * keys that can be removed from the keyspace. */
1543 for (j
= 0; j
< server
.dbnum
; j
++) {
1545 redisDb
*db
= server
.db
+j
;
1547 /* Continue to expire if at the end of the cycle more than 25%
1548 * of the keys were expired. */
1550 long num
= dictSize(db
->expires
);
1551 time_t now
= time(NULL
);
1554 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
1555 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
1560 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
1561 t
= (time_t) dictGetEntryVal(de
);
1563 deleteKey(db
,dictGetEntryKey(de
));
1565 server
.stat_expiredkeys
++;
1568 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
1571 /* Swap a few keys on disk if we are over the memory limit and VM
1572 * is enbled. Try to free objects from the free list first. */
1573 if (vmCanSwapOut()) {
1574 while (server
.vm_enabled
&& zmalloc_used_memory() >
1575 server
.vm_max_memory
)
1579 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
1580 retval
= (server
.vm_max_threads
== 0) ?
1581 vmSwapOneObjectBlocking() :
1582 vmSwapOneObjectThreaded();
1583 if (retval
== REDIS_ERR
&& !(loops
% 300) &&
1584 zmalloc_used_memory() >
1585 (server
.vm_max_memory
+server
.vm_max_memory
/10))
1587 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
1589 /* Note that when using threade I/O we free just one object,
1590 * because anyway when the I/O thread in charge to swap this
1591 * object out will finish, the handler of completed jobs
1592 * will try to swap more objects if we are still out of memory. */
1593 if (retval
== REDIS_ERR
|| server
.vm_max_threads
> 0) break;
1597 /* Check if we should connect to a MASTER */
1598 if (server
.replstate
== REDIS_REPL_CONNECT
&& !(loops
% 10)) {
1599 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
1600 if (syncWithMaster() == REDIS_OK
) {
1601 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
1602 if (server
.appendonly
) rewriteAppendOnlyFileBackground();
1608 /* This function gets called every time Redis is entering the
1609 * main loop of the event driven library, that is, before to sleep
1610 * for ready file descriptors. */
1611 static void beforeSleep(struct aeEventLoop
*eventLoop
) {
1612 REDIS_NOTUSED(eventLoop
);
1614 /* Awake clients that got all the swapped keys they requested */
1615 if (server
.vm_enabled
&& listLength(server
.io_ready_clients
)) {
1619 listRewind(server
.io_ready_clients
,&li
);
1620 while((ln
= listNext(&li
))) {
1621 redisClient
*c
= ln
->value
;
1622 struct redisCommand
*cmd
;
1624 /* Resume the client. */
1625 listDelNode(server
.io_ready_clients
,ln
);
1626 c
->flags
&= (~REDIS_IO_WAIT
);
1627 server
.vm_blocked_clients
--;
1628 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
1629 readQueryFromClient
, c
);
1630 cmd
= lookupCommand(c
->argv
[0]->ptr
);
1631 assert(cmd
!= NULL
);
1634 /* There may be more data to process in the input buffer. */
1635 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
1636 processInputBuffer(c
);
1639 /* Write the AOF buffer on disk */
1640 flushAppendOnlyFile();
1643 static void createSharedObjects(void) {
1646 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
1647 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
1648 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
1649 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
1650 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
1651 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
1652 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
1653 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
1654 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
1655 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
1656 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
1657 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
1658 "-ERR Operation against a key holding the wrong kind of value\r\n"));
1659 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
1660 "-ERR no such key\r\n"));
1661 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
1662 "-ERR syntax error\r\n"));
1663 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
1664 "-ERR source and destination objects are the same\r\n"));
1665 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
1666 "-ERR index out of range\r\n"));
1667 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
1668 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
1669 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
1670 shared
.select0
= createStringObject("select 0\r\n",10);
1671 shared
.select1
= createStringObject("select 1\r\n",10);
1672 shared
.select2
= createStringObject("select 2\r\n",10);
1673 shared
.select3
= createStringObject("select 3\r\n",10);
1674 shared
.select4
= createStringObject("select 4\r\n",10);
1675 shared
.select5
= createStringObject("select 5\r\n",10);
1676 shared
.select6
= createStringObject("select 6\r\n",10);
1677 shared
.select7
= createStringObject("select 7\r\n",10);
1678 shared
.select8
= createStringObject("select 8\r\n",10);
1679 shared
.select9
= createStringObject("select 9\r\n",10);
1680 shared
.messagebulk
= createStringObject("$7\r\nmessage\r\n",13);
1681 shared
.pmessagebulk
= createStringObject("$8\r\npmessage\r\n",14);
1682 shared
.subscribebulk
= createStringObject("$9\r\nsubscribe\r\n",15);
1683 shared
.unsubscribebulk
= createStringObject("$11\r\nunsubscribe\r\n",18);
1684 shared
.psubscribebulk
= createStringObject("$10\r\npsubscribe\r\n",17);
1685 shared
.punsubscribebulk
= createStringObject("$12\r\npunsubscribe\r\n",19);
1686 shared
.mbulk3
= createStringObject("*3\r\n",4);
1687 shared
.mbulk4
= createStringObject("*4\r\n",4);
1688 for (j
= 0; j
< REDIS_SHARED_INTEGERS
; j
++) {
1689 shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
);
1690 shared
.integers
[j
]->encoding
= REDIS_ENCODING_INT
;
1694 static void appendServerSaveParams(time_t seconds
, int changes
) {
1695 server
.saveparams
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1));
1696 server
.saveparams
[server
.saveparamslen
].seconds
= seconds
;
1697 server
.saveparams
[server
.saveparamslen
].changes
= changes
;
1698 server
.saveparamslen
++;
1701 static void resetServerSaveParams() {
1702 zfree(server
.saveparams
);
1703 server
.saveparams
= NULL
;
1704 server
.saveparamslen
= 0;
1707 static void initServerConfig() {
1708 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
1709 server
.port
= REDIS_SERVERPORT
;
1710 server
.verbosity
= REDIS_VERBOSE
;
1711 server
.maxidletime
= REDIS_MAXIDLETIME
;
1712 server
.saveparams
= NULL
;
1713 server
.logfile
= NULL
; /* NULL = log on standard output */
1714 server
.bindaddr
= NULL
;
1715 server
.glueoutputbuf
= 1;
1716 server
.daemonize
= 0;
1717 server
.appendonly
= 0;
1718 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
1719 server
.no_appendfsync_on_rewrite
= 0;
1720 server
.lastfsync
= time(NULL
);
1721 server
.appendfd
= -1;
1722 server
.appendseldb
= -1; /* Make sure the first time will not match */
1723 server
.pidfile
= zstrdup("/var/run/redis.pid");
1724 server
.dbfilename
= zstrdup("dump.rdb");
1725 server
.appendfilename
= zstrdup("appendonly.aof");
1726 server
.requirepass
= NULL
;
1727 server
.rdbcompression
= 1;
1728 server
.activerehashing
= 1;
1729 server
.maxclients
= 0;
1730 server
.blpop_blocked_clients
= 0;
1731 server
.maxmemory
= 0;
1732 server
.vm_enabled
= 0;
1733 server
.vm_swap_file
= zstrdup("/tmp/redis-%p.vm");
1734 server
.vm_page_size
= 256; /* 256 bytes per page */
1735 server
.vm_pages
= 1024*1024*100; /* 104 millions of pages */
1736 server
.vm_max_memory
= 1024LL*1024*1024*1; /* 1 GB of RAM */
1737 server
.vm_max_threads
= 4;
1738 server
.vm_blocked_clients
= 0;
1739 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
1740 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
1741 server
.shutdown_asap
= 0;
1743 resetServerSaveParams();
1745 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1746 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1747 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1748 /* Replication related */
1750 server
.masterauth
= NULL
;
1751 server
.masterhost
= NULL
;
1752 server
.masterport
= 6379;
1753 server
.master
= NULL
;
1754 server
.replstate
= REDIS_REPL_NONE
;
1756 /* Double constants initialization */
1758 R_PosInf
= 1.0/R_Zero
;
1759 R_NegInf
= -1.0/R_Zero
;
1760 R_Nan
= R_Zero
/R_Zero
;
1763 static void initServer() {
1766 signal(SIGHUP
, SIG_IGN
);
1767 signal(SIGPIPE
, SIG_IGN
);
1768 setupSigSegvAction();
1770 server
.devnull
= fopen("/dev/null","w");
1771 if (server
.devnull
== NULL
) {
1772 redisLog(REDIS_WARNING
, "Can't open /dev/null: %s", server
.neterr
);
1775 server
.clients
= listCreate();
1776 server
.slaves
= listCreate();
1777 server
.monitors
= listCreate();
1778 server
.objfreelist
= listCreate();
1779 createSharedObjects();
1780 server
.el
= aeCreateEventLoop();
1781 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
1782 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
1783 if (server
.fd
== -1) {
1784 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
1787 for (j
= 0; j
< server
.dbnum
; j
++) {
1788 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
1789 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
1790 server
.db
[j
].blocking_keys
= dictCreate(&keylistDictType
,NULL
);
1791 server
.db
[j
].watched_keys
= dictCreate(&keylistDictType
,NULL
);
1792 if (server
.vm_enabled
)
1793 server
.db
[j
].io_keys
= dictCreate(&keylistDictType
,NULL
);
1794 server
.db
[j
].id
= j
;
1796 server
.pubsub_channels
= dictCreate(&keylistDictType
,NULL
);
1797 server
.pubsub_patterns
= listCreate();
1798 listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
);
1799 listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
);
1800 server
.cronloops
= 0;
1801 server
.bgsavechildpid
= -1;
1802 server
.bgrewritechildpid
= -1;
1803 server
.bgrewritebuf
= sdsempty();
1804 server
.aofbuf
= sdsempty();
1805 server
.lastsave
= time(NULL
);
1807 server
.stat_numcommands
= 0;
1808 server
.stat_numconnections
= 0;
1809 server
.stat_expiredkeys
= 0;
1810 server
.stat_starttime
= time(NULL
);
1811 server
.unixtime
= time(NULL
);
1812 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
1813 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
1814 acceptHandler
, NULL
) == AE_ERR
) oom("creating file event");
1816 if (server
.appendonly
) {
1817 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
1818 if (server
.appendfd
== -1) {
1819 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
1825 if (server
.vm_enabled
) vmInit();
1828 /* Empty the whole database */
1829 static long long emptyDb() {
1831 long long removed
= 0;
1833 for (j
= 0; j
< server
.dbnum
; j
++) {
1834 removed
+= dictSize(server
.db
[j
].dict
);
1835 dictEmpty(server
.db
[j
].dict
);
1836 dictEmpty(server
.db
[j
].expires
);
1841 static int yesnotoi(char *s
) {
1842 if (!strcasecmp(s
,"yes")) return 1;
1843 else if (!strcasecmp(s
,"no")) return 0;
1847 /* I agree, this is a very rudimental way to load a configuration...
1848 will improve later if the config gets more complex */
1849 static void loadServerConfig(char *filename
) {
1851 char buf
[REDIS_CONFIGLINE_MAX
+1], *err
= NULL
;
1855 if (filename
[0] == '-' && filename
[1] == '\0')
1858 if ((fp
= fopen(filename
,"r")) == NULL
) {
1859 redisLog(REDIS_WARNING
, "Fatal error, can't open config file '%s'", filename
);
1864 while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) {
1870 line
= sdstrim(line
," \t\r\n");
1872 /* Skip comments and blank lines*/
1873 if (line
[0] == '#' || line
[0] == '\0') {
1878 /* Split into arguments */
1879 argv
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
);
1880 sdstolower(argv
[0]);
1882 /* Execute config directives */
1883 if (!strcasecmp(argv
[0],"timeout") && argc
== 2) {
1884 server
.maxidletime
= atoi(argv
[1]);
1885 if (server
.maxidletime
< 0) {
1886 err
= "Invalid timeout value"; goto loaderr
;
1888 } else if (!strcasecmp(argv
[0],"port") && argc
== 2) {
1889 server
.port
= atoi(argv
[1]);
1890 if (server
.port
< 1 || server
.port
> 65535) {
1891 err
= "Invalid port"; goto loaderr
;
1893 } else if (!strcasecmp(argv
[0],"bind") && argc
== 2) {
1894 server
.bindaddr
= zstrdup(argv
[1]);
1895 } else if (!strcasecmp(argv
[0],"save") && argc
== 3) {
1896 int seconds
= atoi(argv
[1]);
1897 int changes
= atoi(argv
[2]);
1898 if (seconds
< 1 || changes
< 0) {
1899 err
= "Invalid save parameters"; goto loaderr
;
1901 appendServerSaveParams(seconds
,changes
);
1902 } else if (!strcasecmp(argv
[0],"dir") && argc
== 2) {
1903 if (chdir(argv
[1]) == -1) {
1904 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s",
1905 argv
[1], strerror(errno
));
1908 } else if (!strcasecmp(argv
[0],"loglevel") && argc
== 2) {
1909 if (!strcasecmp(argv
[1],"debug")) server
.verbosity
= REDIS_DEBUG
;
1910 else if (!strcasecmp(argv
[1],"verbose")) server
.verbosity
= REDIS_VERBOSE
;
1911 else if (!strcasecmp(argv
[1],"notice")) server
.verbosity
= REDIS_NOTICE
;
1912 else if (!strcasecmp(argv
[1],"warning")) server
.verbosity
= REDIS_WARNING
;
1914 err
= "Invalid log level. Must be one of debug, notice, warning";
1917 } else if (!strcasecmp(argv
[0],"logfile") && argc
== 2) {
1920 server
.logfile
= zstrdup(argv
[1]);
1921 if (!strcasecmp(server
.logfile
,"stdout")) {
1922 zfree(server
.logfile
);
1923 server
.logfile
= NULL
;
1925 if (server
.logfile
) {
1926 /* Test if we are able to open the file. The server will not
1927 * be able to abort just for this problem later... */
1928 logfp
= fopen(server
.logfile
,"a");
1929 if (logfp
== NULL
) {
1930 err
= sdscatprintf(sdsempty(),
1931 "Can't open the log file: %s", strerror(errno
));
1936 } else if (!strcasecmp(argv
[0],"databases") && argc
== 2) {
1937 server
.dbnum
= atoi(argv
[1]);
1938 if (server
.dbnum
< 1) {
1939 err
= "Invalid number of databases"; goto loaderr
;
1941 } else if (!strcasecmp(argv
[0],"include") && argc
== 2) {
1942 loadServerConfig(argv
[1]);
1943 } else if (!strcasecmp(argv
[0],"maxclients") && argc
== 2) {
1944 server
.maxclients
= atoi(argv
[1]);
1945 } else if (!strcasecmp(argv
[0],"maxmemory") && argc
== 2) {
1946 server
.maxmemory
= memtoll(argv
[1],NULL
);
1947 } else if (!strcasecmp(argv
[0],"slaveof") && argc
== 3) {
1948 server
.masterhost
= sdsnew(argv
[1]);
1949 server
.masterport
= atoi(argv
[2]);
1950 server
.replstate
= REDIS_REPL_CONNECT
;
1951 } else if (!strcasecmp(argv
[0],"masterauth") && argc
== 2) {
1952 server
.masterauth
= zstrdup(argv
[1]);
1953 } else if (!strcasecmp(argv
[0],"glueoutputbuf") && argc
== 2) {
1954 if ((server
.glueoutputbuf
= yesnotoi(argv
[1])) == -1) {
1955 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1957 } else if (!strcasecmp(argv
[0],"rdbcompression") && argc
== 2) {
1958 if ((server
.rdbcompression
= yesnotoi(argv
[1])) == -1) {
1959 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1961 } else if (!strcasecmp(argv
[0],"activerehashing") && argc
== 2) {
1962 if ((server
.activerehashing
= yesnotoi(argv
[1])) == -1) {
1963 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1965 } else if (!strcasecmp(argv
[0],"daemonize") && argc
== 2) {
1966 if ((server
.daemonize
= yesnotoi(argv
[1])) == -1) {
1967 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1969 } else if (!strcasecmp(argv
[0],"appendonly") && argc
== 2) {
1970 if ((server
.appendonly
= yesnotoi(argv
[1])) == -1) {
1971 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1973 } else if (!strcasecmp(argv
[0],"appendfilename") && argc
== 2) {
1974 zfree(server
.appendfilename
);
1975 server
.appendfilename
= zstrdup(argv
[1]);
1976 } else if (!strcasecmp(argv
[0],"no-appendfsync-on-rewrite")
1978 if ((server
.no_appendfsync_on_rewrite
= yesnotoi(argv
[1])) == -1) {
1979 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1981 } else if (!strcasecmp(argv
[0],"appendfsync") && argc
== 2) {
1982 if (!strcasecmp(argv
[1],"no")) {
1983 server
.appendfsync
= APPENDFSYNC_NO
;
1984 } else if (!strcasecmp(argv
[1],"always")) {
1985 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1986 } else if (!strcasecmp(argv
[1],"everysec")) {
1987 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
1989 err
= "argument must be 'no', 'always' or 'everysec'";
1992 } else if (!strcasecmp(argv
[0],"requirepass") && argc
== 2) {
1993 server
.requirepass
= zstrdup(argv
[1]);
1994 } else if (!strcasecmp(argv
[0],"pidfile") && argc
== 2) {
1995 zfree(server
.pidfile
);
1996 server
.pidfile
= zstrdup(argv
[1]);
1997 } else if (!strcasecmp(argv
[0],"dbfilename") && argc
== 2) {
1998 zfree(server
.dbfilename
);
1999 server
.dbfilename
= zstrdup(argv
[1]);
2000 } else if (!strcasecmp(argv
[0],"vm-enabled") && argc
== 2) {
2001 if ((server
.vm_enabled
= yesnotoi(argv
[1])) == -1) {
2002 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
2004 } else if (!strcasecmp(argv
[0],"vm-swap-file") && argc
== 2) {
2005 zfree(server
.vm_swap_file
);
2006 server
.vm_swap_file
= zstrdup(argv
[1]);
2007 } else if (!strcasecmp(argv
[0],"vm-max-memory") && argc
== 2) {
2008 server
.vm_max_memory
= memtoll(argv
[1],NULL
);
2009 } else if (!strcasecmp(argv
[0],"vm-page-size") && argc
== 2) {
2010 server
.vm_page_size
= memtoll(argv
[1], NULL
);
2011 } else if (!strcasecmp(argv
[0],"vm-pages") && argc
== 2) {
2012 server
.vm_pages
= memtoll(argv
[1], NULL
);
2013 } else if (!strcasecmp(argv
[0],"vm-max-threads") && argc
== 2) {
2014 server
.vm_max_threads
= strtoll(argv
[1], NULL
, 10);
2015 } else if (!strcasecmp(argv
[0],"hash-max-zipmap-entries") && argc
== 2){
2016 server
.hash_max_zipmap_entries
= memtoll(argv
[1], NULL
);
2017 } else if (!strcasecmp(argv
[0],"hash-max-zipmap-value") && argc
== 2){
2018 server
.hash_max_zipmap_value
= memtoll(argv
[1], NULL
);
2020 err
= "Bad directive or wrong number of arguments"; goto loaderr
;
2022 for (j
= 0; j
< argc
; j
++)
2027 if (fp
!= stdin
) fclose(fp
);
2031 fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n");
2032 fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
);
2033 fprintf(stderr
, ">>> '%s'\n", line
);
2034 fprintf(stderr
, "%s\n", err
);
2038 static void freeClientArgv(redisClient
*c
) {
2041 for (j
= 0; j
< c
->argc
; j
++)
2042 decrRefCount(c
->argv
[j
]);
2043 for (j
= 0; j
< c
->mbargc
; j
++)
2044 decrRefCount(c
->mbargv
[j
]);
2049 static void freeClient(redisClient
*c
) {
2052 /* Note that if the client we are freeing is blocked into a blocking
2053 * call, we have to set querybuf to NULL *before* to call
2054 * unblockClientWaitingData() to avoid processInputBuffer() will get
2055 * called. Also it is important to remove the file events after
2056 * this, because this call adds the READABLE event. */
2057 sdsfree(c
->querybuf
);
2059 if (c
->flags
& REDIS_BLOCKED
)
2060 unblockClientWaitingData(c
);
2062 /* UNWATCH all the keys */
2064 listRelease(c
->watched_keys
);
2065 /* Unsubscribe from all the pubsub channels */
2066 pubsubUnsubscribeAllChannels(c
,0);
2067 pubsubUnsubscribeAllPatterns(c
,0);
2068 dictRelease(c
->pubsub_channels
);
2069 listRelease(c
->pubsub_patterns
);
2070 /* Obvious cleanup */
2071 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
2072 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
2073 listRelease(c
->reply
);
2076 /* Remove from the list of clients */
2077 ln
= listSearchKey(server
.clients
,c
);
2078 redisAssert(ln
!= NULL
);
2079 listDelNode(server
.clients
,ln
);
2080 /* Remove from the list of clients that are now ready to be restarted
2081 * after waiting for swapped keys */
2082 if (c
->flags
& REDIS_IO_WAIT
&& listLength(c
->io_keys
) == 0) {
2083 ln
= listSearchKey(server
.io_ready_clients
,c
);
2085 listDelNode(server
.io_ready_clients
,ln
);
2086 server
.vm_blocked_clients
--;
2089 /* Remove from the list of clients waiting for swapped keys */
2090 while (server
.vm_enabled
&& listLength(c
->io_keys
)) {
2091 ln
= listFirst(c
->io_keys
);
2092 dontWaitForSwappedKey(c
,ln
->value
);
2094 listRelease(c
->io_keys
);
2095 /* Master/slave cleanup */
2096 if (c
->flags
& REDIS_SLAVE
) {
2097 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
2099 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
2100 ln
= listSearchKey(l
,c
);
2101 redisAssert(ln
!= NULL
);
2104 if (c
->flags
& REDIS_MASTER
) {
2105 server
.master
= NULL
;
2106 server
.replstate
= REDIS_REPL_CONNECT
;
2108 /* Release memory */
2111 freeClientMultiState(c
);
2115 #define GLUEREPLY_UP_TO (1024)
2116 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
2118 char buf
[GLUEREPLY_UP_TO
];
2123 listRewind(c
->reply
,&li
);
2124 while((ln
= listNext(&li
))) {
2128 objlen
= sdslen(o
->ptr
);
2129 if (copylen
+ objlen
<= GLUEREPLY_UP_TO
) {
2130 memcpy(buf
+copylen
,o
->ptr
,objlen
);
2132 listDelNode(c
->reply
,ln
);
2134 if (copylen
== 0) return;
2138 /* Now the output buffer is empty, add the new single element */
2139 o
= createObject(REDIS_STRING
,sdsnewlen(buf
,copylen
));
2140 listAddNodeHead(c
->reply
,o
);
2143 static void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2144 redisClient
*c
= privdata
;
2145 int nwritten
= 0, totwritten
= 0, objlen
;
2148 REDIS_NOTUSED(mask
);
2150 /* Use writev() if we have enough buffers to send */
2151 if (!server
.glueoutputbuf
&&
2152 listLength(c
->reply
) > REDIS_WRITEV_THRESHOLD
&&
2153 !(c
->flags
& REDIS_MASTER
))
2155 sendReplyToClientWritev(el
, fd
, privdata
, mask
);
2159 while(listLength(c
->reply
)) {
2160 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
2161 glueReplyBuffersIfNeeded(c
);
2163 o
= listNodeValue(listFirst(c
->reply
));
2164 objlen
= sdslen(o
->ptr
);
2167 listDelNode(c
->reply
,listFirst(c
->reply
));
2171 if (c
->flags
& REDIS_MASTER
) {
2172 /* Don't reply to a master */
2173 nwritten
= objlen
- c
->sentlen
;
2175 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen
- c
->sentlen
);
2176 if (nwritten
<= 0) break;
2178 c
->sentlen
+= nwritten
;
2179 totwritten
+= nwritten
;
2180 /* If we fully sent the object on head go to the next one */
2181 if (c
->sentlen
== objlen
) {
2182 listDelNode(c
->reply
,listFirst(c
->reply
));
2185 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
2186 * bytes, in a single threaded server it's a good idea to serve
2187 * other clients as well, even if a very large request comes from
2188 * super fast link that is always able to accept data (in real world
2189 * scenario think about 'KEYS *' against the loopback interfae) */
2190 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
) break;
2192 if (nwritten
== -1) {
2193 if (errno
== EAGAIN
) {
2196 redisLog(REDIS_VERBOSE
,
2197 "Error writing to client: %s", strerror(errno
));
2202 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
2203 if (listLength(c
->reply
) == 0) {
2205 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
2209 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
)
2211 redisClient
*c
= privdata
;
2212 int nwritten
= 0, totwritten
= 0, objlen
, willwrite
;
2214 struct iovec iov
[REDIS_WRITEV_IOVEC_COUNT
];
2215 int offset
, ion
= 0;
2217 REDIS_NOTUSED(mask
);
2220 while (listLength(c
->reply
)) {
2221 offset
= c
->sentlen
;
2225 /* fill-in the iov[] array */
2226 for(node
= listFirst(c
->reply
); node
; node
= listNextNode(node
)) {
2227 o
= listNodeValue(node
);
2228 objlen
= sdslen(o
->ptr
);
2230 if (totwritten
+ objlen
- offset
> REDIS_MAX_WRITE_PER_EVENT
)
2233 if(ion
== REDIS_WRITEV_IOVEC_COUNT
)
2234 break; /* no more iovecs */
2236 iov
[ion
].iov_base
= ((char*)o
->ptr
) + offset
;
2237 iov
[ion
].iov_len
= objlen
- offset
;
2238 willwrite
+= objlen
- offset
;
2239 offset
= 0; /* just for the first item */
2246 /* write all collected blocks at once */
2247 if((nwritten
= writev(fd
, iov
, ion
)) < 0) {
2248 if (errno
!= EAGAIN
) {
2249 redisLog(REDIS_VERBOSE
,
2250 "Error writing to client: %s", strerror(errno
));
2257 totwritten
+= nwritten
;
2258 offset
= c
->sentlen
;
2260 /* remove written robjs from c->reply */
2261 while (nwritten
&& listLength(c
->reply
)) {
2262 o
= listNodeValue(listFirst(c
->reply
));
2263 objlen
= sdslen(o
->ptr
);
2265 if(nwritten
>= objlen
- offset
) {
2266 listDelNode(c
->reply
, listFirst(c
->reply
));
2267 nwritten
-= objlen
- offset
;
2271 c
->sentlen
+= nwritten
;
2279 c
->lastinteraction
= time(NULL
);
2281 if (listLength(c
->reply
) == 0) {
2283 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
2287 static int qsortRedisCommands(const void *r1
, const void *r2
) {
2289 ((struct redisCommand
*)r1
)->name
,
2290 ((struct redisCommand
*)r2
)->name
);
2293 static void sortCommandTable() {
2294 /* Copy and sort the read-only version of the command table */
2295 commandTable
= (struct redisCommand
*)malloc(sizeof(readonlyCommandTable
));
2296 memcpy(commandTable
,readonlyCommandTable
,sizeof(readonlyCommandTable
));
2298 sizeof(readonlyCommandTable
)/sizeof(struct redisCommand
),
2299 sizeof(struct redisCommand
),qsortRedisCommands
);
2302 static struct redisCommand
*lookupCommand(char *name
) {
2303 struct redisCommand tmp
= {name
,NULL
,0,0,NULL
,0,0,0};
2307 sizeof(readonlyCommandTable
)/sizeof(struct redisCommand
),
2308 sizeof(struct redisCommand
),
2309 qsortRedisCommands
);
2312 /* resetClient prepare the client to process the next command */
2313 static void resetClient(redisClient
*c
) {
2319 /* Call() is the core of Redis execution of a command */
2320 static void call(redisClient
*c
, struct redisCommand
*cmd
) {
2323 dirty
= server
.dirty
;
2325 dirty
= server
.dirty
-dirty
;
2327 if (server
.appendonly
&& dirty
)
2328 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
2329 if ((dirty
|| cmd
->flags
& REDIS_CMD_FORCE_REPLICATION
) &&
2330 listLength(server
.slaves
))
2331 replicationFeedSlaves(server
.slaves
,c
->db
->id
,c
->argv
,c
->argc
);
2332 if (listLength(server
.monitors
))
2333 replicationFeedMonitors(server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
);
2334 server
.stat_numcommands
++;
2337 /* If this function gets called we already read a whole
2338 * command, argments are in the client argv/argc fields.
2339 * processCommand() execute the command or prepare the
2340 * server for a bulk read from the client.
2342 * If 1 is returned the client is still alive and valid and
2343 * and other operations can be performed by the caller. Otherwise
2344 * if 0 is returned the client was destroied (i.e. after QUIT). */
2345 static int processCommand(redisClient
*c
) {
2346 struct redisCommand
*cmd
;
2348 /* Free some memory if needed (maxmemory setting) */
2349 if (server
.maxmemory
) freeMemoryIfNeeded();
2351 /* Handle the multi bulk command type. This is an alternative protocol
2352 * supported by Redis in order to receive commands that are composed of
2353 * multiple binary-safe "bulk" arguments. The latency of processing is
2354 * a bit higher but this allows things like multi-sets, so if this
2355 * protocol is used only for MSET and similar commands this is a big win. */
2356 if (c
->multibulk
== 0 && c
->argc
== 1 && ((char*)(c
->argv
[0]->ptr
))[0] == '*') {
2357 c
->multibulk
= atoi(((char*)c
->argv
[0]->ptr
)+1);
2358 if (c
->multibulk
<= 0) {
2362 decrRefCount(c
->argv
[c
->argc
-1]);
2366 } else if (c
->multibulk
) {
2367 if (c
->bulklen
== -1) {
2368 if (((char*)c
->argv
[0]->ptr
)[0] != '$') {
2369 addReplySds(c
,sdsnew("-ERR multi bulk protocol error\r\n"));
2373 int bulklen
= atoi(((char*)c
->argv
[0]->ptr
)+1);
2374 decrRefCount(c
->argv
[0]);
2375 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
2377 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
2382 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
2386 c
->mbargv
= zrealloc(c
->mbargv
,(sizeof(robj
*))*(c
->mbargc
+1));
2387 c
->mbargv
[c
->mbargc
] = c
->argv
[0];
2391 if (c
->multibulk
== 0) {
2395 /* Here we need to swap the multi-bulk argc/argv with the
2396 * normal argc/argv of the client structure. */
2398 c
->argv
= c
->mbargv
;
2399 c
->mbargv
= auxargv
;
2402 c
->argc
= c
->mbargc
;
2403 c
->mbargc
= auxargc
;
2405 /* We need to set bulklen to something different than -1
2406 * in order for the code below to process the command without
2407 * to try to read the last argument of a bulk command as
2408 * a special argument. */
2410 /* continue below and process the command */
2417 /* -- end of multi bulk commands processing -- */
2419 /* The QUIT command is handled as a special case. Normal command
2420 * procs are unable to close the client connection safely */
2421 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
2426 /* Now lookup the command and check ASAP about trivial error conditions
2427 * such wrong arity, bad command name and so forth. */
2428 cmd
= lookupCommand(c
->argv
[0]->ptr
);
2431 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
2432 (char*)c
->argv
[0]->ptr
));
2435 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
2436 (c
->argc
< -cmd
->arity
)) {
2438 sdscatprintf(sdsempty(),
2439 "-ERR wrong number of arguments for '%s' command\r\n",
2443 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
2444 /* This is a bulk command, we have to read the last argument yet. */
2445 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
2447 decrRefCount(c
->argv
[c
->argc
-1]);
2448 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
2450 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
2455 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
2456 /* It is possible that the bulk read is already in the
2457 * buffer. Check this condition and handle it accordingly.
2458 * This is just a fast path, alternative to call processInputBuffer().
2459 * It's a good idea since the code is small and this condition
2460 * happens most of the times. */
2461 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
2462 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2464 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2466 /* Otherwise return... there is to read the last argument
2467 * from the socket. */
2471 /* Let's try to encode the bulk object to save space. */
2472 if (cmd
->flags
& REDIS_CMD_BULK
)
2473 c
->argv
[c
->argc
-1] = tryObjectEncoding(c
->argv
[c
->argc
-1]);
2475 /* Check if the user is authenticated */
2476 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
2477 addReplySds(c
,sdsnew("-ERR operation not permitted\r\n"));
2482 /* Handle the maxmemory directive */
2483 if (server
.maxmemory
&& (cmd
->flags
& REDIS_CMD_DENYOOM
) &&
2484 zmalloc_used_memory() > server
.maxmemory
)
2486 addReplySds(c
,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
2491 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
2492 if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0)
2494 cmd
->proc
!= subscribeCommand
&& cmd
->proc
!= unsubscribeCommand
&&
2495 cmd
->proc
!= psubscribeCommand
&& cmd
->proc
!= punsubscribeCommand
) {
2496 addReplySds(c
,sdsnew("-ERR only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context\r\n"));
2501 /* Exec the command */
2502 if (c
->flags
& REDIS_MULTI
&&
2503 cmd
->proc
!= execCommand
&& cmd
->proc
!= discardCommand
&&
2504 cmd
->proc
!= multiCommand
&& cmd
->proc
!= watchCommand
)
2506 queueMultiCommand(c
,cmd
);
2507 addReply(c
,shared
.queued
);
2509 if (server
.vm_enabled
&& server
.vm_max_threads
> 0 &&
2510 blockClientOnSwappedKeys(c
,cmd
)) return 1;
2514 /* Prepare the client for the next command */
2519 static void replicationFeedSlaves(list
*slaves
, int dictid
, robj
**argv
, int argc
) {
2524 /* We need 1+(ARGS*3) objects since commands are using the new protocol
2525 * and we one 1 object for the first "*<count>\r\n" multibulk count, then
2526 * for every additional object we have "$<count>\r\n" + object + "\r\n". */
2527 robj
*static_outv
[REDIS_STATIC_ARGS
*3+1];
2530 if (argc
<= REDIS_STATIC_ARGS
) {
2533 outv
= zmalloc(sizeof(robj
*)*(argc
*3+1));
2536 lenobj
= createObject(REDIS_STRING
,
2537 sdscatprintf(sdsempty(), "*%d\r\n", argc
));
2538 lenobj
->refcount
= 0;
2539 outv
[outc
++] = lenobj
;
2540 for (j
= 0; j
< argc
; j
++) {
2541 lenobj
= createObject(REDIS_STRING
,
2542 sdscatprintf(sdsempty(),"$%lu\r\n",
2543 (unsigned long) stringObjectLen(argv
[j
])));
2544 lenobj
->refcount
= 0;
2545 outv
[outc
++] = lenobj
;
2546 outv
[outc
++] = argv
[j
];
2547 outv
[outc
++] = shared
.crlf
;
2550 /* Increment all the refcounts at start and decrement at end in order to
2551 * be sure to free objects if there is no slave in a replication state
2552 * able to be feed with commands */
2553 for (j
= 0; j
< outc
; j
++) incrRefCount(outv
[j
]);
2554 listRewind(slaves
,&li
);
2555 while((ln
= listNext(&li
))) {
2556 redisClient
*slave
= ln
->value
;
2558 /* Don't feed slaves that are still waiting for BGSAVE to start */
2559 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) continue;
2561 /* Feed all the other slaves, MONITORs and so on */
2562 if (slave
->slaveseldb
!= dictid
) {
2566 case 0: selectcmd
= shared
.select0
; break;
2567 case 1: selectcmd
= shared
.select1
; break;
2568 case 2: selectcmd
= shared
.select2
; break;
2569 case 3: selectcmd
= shared
.select3
; break;
2570 case 4: selectcmd
= shared
.select4
; break;
2571 case 5: selectcmd
= shared
.select5
; break;
2572 case 6: selectcmd
= shared
.select6
; break;
2573 case 7: selectcmd
= shared
.select7
; break;
2574 case 8: selectcmd
= shared
.select8
; break;
2575 case 9: selectcmd
= shared
.select9
; break;
2577 selectcmd
= createObject(REDIS_STRING
,
2578 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
2579 selectcmd
->refcount
= 0;
2582 addReply(slave
,selectcmd
);
2583 slave
->slaveseldb
= dictid
;
2585 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
2587 for (j
= 0; j
< outc
; j
++) decrRefCount(outv
[j
]);
2588 if (outv
!= static_outv
) zfree(outv
);
2591 static sds
sdscatrepr(sds s
, char *p
, size_t len
) {
2592 s
= sdscatlen(s
,"\"",1);
2597 s
= sdscatprintf(s
,"\\%c",*p
);
2599 case '\n': s
= sdscatlen(s
,"\\n",1); break;
2600 case '\r': s
= sdscatlen(s
,"\\r",1); break;
2601 case '\t': s
= sdscatlen(s
,"\\t",1); break;
2602 case '\a': s
= sdscatlen(s
,"\\a",1); break;
2603 case '\b': s
= sdscatlen(s
,"\\b",1); break;
2606 s
= sdscatprintf(s
,"%c",*p
);
2608 s
= sdscatprintf(s
,"\\x%02x",(unsigned char)*p
);
2613 return sdscatlen(s
,"\"",1);
2616 static void replicationFeedMonitors(list
*monitors
, int dictid
, robj
**argv
, int argc
) {
2620 sds cmdrepr
= sdsnew("+");
2624 gettimeofday(&tv
,NULL
);
2625 cmdrepr
= sdscatprintf(cmdrepr
,"%ld.%ld ",(long)tv
.tv_sec
,(long)tv
.tv_usec
);
2626 if (dictid
!= 0) cmdrepr
= sdscatprintf(cmdrepr
,"(db %d) ", dictid
);
2628 for (j
= 0; j
< argc
; j
++) {
2629 if (argv
[j
]->encoding
== REDIS_ENCODING_INT
) {
2630 cmdrepr
= sdscatprintf(cmdrepr
, "%ld", (long)argv
[j
]->ptr
);
2632 cmdrepr
= sdscatrepr(cmdrepr
,(char*)argv
[j
]->ptr
,
2633 sdslen(argv
[j
]->ptr
));
2636 cmdrepr
= sdscatlen(cmdrepr
," ",1);
2638 cmdrepr
= sdscatlen(cmdrepr
,"\r\n",2);
2639 cmdobj
= createObject(REDIS_STRING
,cmdrepr
);
2641 listRewind(monitors
,&li
);
2642 while((ln
= listNext(&li
))) {
2643 redisClient
*monitor
= ln
->value
;
2644 addReply(monitor
,cmdobj
);
2646 decrRefCount(cmdobj
);
2649 static void processInputBuffer(redisClient
*c
) {
2651 /* Before to process the input buffer, make sure the client is not
2652 * waitig for a blocking operation such as BLPOP. Note that the first
2653 * iteration the client is never blocked, otherwise the processInputBuffer
2654 * would not be called at all, but after the execution of the first commands
2655 * in the input buffer the client may be blocked, and the "goto again"
2656 * will try to reiterate. The following line will make it return asap. */
2657 if (c
->flags
& REDIS_BLOCKED
|| c
->flags
& REDIS_IO_WAIT
) return;
2658 if (c
->bulklen
== -1) {
2659 /* Read the first line of the query */
2660 char *p
= strchr(c
->querybuf
,'\n');
2667 query
= c
->querybuf
;
2668 c
->querybuf
= sdsempty();
2669 querylen
= 1+(p
-(query
));
2670 if (sdslen(query
) > querylen
) {
2671 /* leave data after the first line of the query in the buffer */
2672 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
2674 *p
= '\0'; /* remove "\n" */
2675 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
2676 sdsupdatelen(query
);
2678 /* Now we can split the query in arguments */
2679 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
2682 if (c
->argv
) zfree(c
->argv
);
2683 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
2685 for (j
= 0; j
< argc
; j
++) {
2686 if (sdslen(argv
[j
])) {
2687 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
2695 /* Execute the command. If the client is still valid
2696 * after processCommand() return and there is something
2697 * on the query buffer try to process the next command. */
2698 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2700 /* Nothing to process, argc == 0. Just process the query
2701 * buffer if it's not empty or return to the caller */
2702 if (sdslen(c
->querybuf
)) goto again
;
2705 } else if (sdslen(c
->querybuf
) >= REDIS_REQUEST_MAX_SIZE
) {
2706 redisLog(REDIS_VERBOSE
, "Client protocol error");
2711 /* Bulk read handling. Note that if we are at this point
2712 the client already sent a command terminated with a newline,
2713 we are reading the bulk data that is actually the last
2714 argument of the command. */
2715 int qbl
= sdslen(c
->querybuf
);
2717 if (c
->bulklen
<= qbl
) {
2718 /* Copy everything but the final CRLF as final argument */
2719 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2721 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2722 /* Process the command. If the client is still valid after
2723 * the processing and there is more data in the buffer
2724 * try to parse it. */
2725 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2731 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2732 redisClient
*c
= (redisClient
*) privdata
;
2733 char buf
[REDIS_IOBUF_LEN
];
2736 REDIS_NOTUSED(mask
);
2738 nread
= read(fd
, buf
, REDIS_IOBUF_LEN
);
2740 if (errno
== EAGAIN
) {
2743 redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
));
2747 } else if (nread
== 0) {
2748 redisLog(REDIS_VERBOSE
, "Client closed connection");
2753 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
2754 c
->lastinteraction
= time(NULL
);
2758 processInputBuffer(c
);
2761 static int selectDb(redisClient
*c
, int id
) {
2762 if (id
< 0 || id
>= server
.dbnum
)
2764 c
->db
= &server
.db
[id
];
2768 static void *dupClientReplyValue(void *o
) {
2769 incrRefCount((robj
*)o
);
2773 static int listMatchObjects(void *a
, void *b
) {
2774 return equalStringObjects(a
,b
);
2777 static redisClient
*createClient(int fd
) {
2778 redisClient
*c
= zmalloc(sizeof(*c
));
2780 anetNonBlock(NULL
,fd
);
2781 anetTcpNoDelay(NULL
,fd
);
2782 if (!c
) return NULL
;
2785 c
->querybuf
= sdsempty();
2794 c
->lastinteraction
= time(NULL
);
2795 c
->authenticated
= 0;
2796 c
->replstate
= REDIS_REPL_NONE
;
2797 c
->reply
= listCreate();
2798 listSetFreeMethod(c
->reply
,decrRefCount
);
2799 listSetDupMethod(c
->reply
,dupClientReplyValue
);
2800 c
->blocking_keys
= NULL
;
2801 c
->blocking_keys_num
= 0;
2802 c
->io_keys
= listCreate();
2803 c
->watched_keys
= listCreate();
2804 listSetFreeMethod(c
->io_keys
,decrRefCount
);
2805 c
->pubsub_channels
= dictCreate(&setDictType
,NULL
);
2806 c
->pubsub_patterns
= listCreate();
2807 listSetFreeMethod(c
->pubsub_patterns
,decrRefCount
);
2808 listSetMatchMethod(c
->pubsub_patterns
,listMatchObjects
);
2809 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
2810 readQueryFromClient
, c
) == AE_ERR
) {
2814 listAddNodeTail(server
.clients
,c
);
2815 initClientMultiState(c
);
2819 static void addReply(redisClient
*c
, robj
*obj
) {
2820 if (listLength(c
->reply
) == 0 &&
2821 (c
->replstate
== REDIS_REPL_NONE
||
2822 c
->replstate
== REDIS_REPL_ONLINE
) &&
2823 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
2824 sendReplyToClient
, c
) == AE_ERR
) return;
2826 if (server
.vm_enabled
&& obj
->storage
!= REDIS_VM_MEMORY
) {
2827 obj
= dupStringObject(obj
);
2828 obj
->refcount
= 0; /* getDecodedObject() will increment the refcount */
2830 listAddNodeTail(c
->reply
,getDecodedObject(obj
));
2833 static void addReplySds(redisClient
*c
, sds s
) {
2834 robj
*o
= createObject(REDIS_STRING
,s
);
2839 static void addReplyDouble(redisClient
*c
, double d
) {
2842 snprintf(buf
,sizeof(buf
),"%.17g",d
);
2843 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
2844 (unsigned long) strlen(buf
),buf
));
2847 static void addReplyLongLong(redisClient
*c
, long long ll
) {
2852 addReply(c
,shared
.czero
);
2854 } else if (ll
== 1) {
2855 addReply(c
,shared
.cone
);
2859 len
= ll2string(buf
+1,sizeof(buf
)-1,ll
);
2862 addReplySds(c
,sdsnewlen(buf
,len
+3));
2865 static void addReplyUlong(redisClient
*c
, unsigned long ul
) {
2870 addReply(c
,shared
.czero
);
2872 } else if (ul
== 1) {
2873 addReply(c
,shared
.cone
);
2876 len
= snprintf(buf
,sizeof(buf
),":%lu\r\n",ul
);
2877 addReplySds(c
,sdsnewlen(buf
,len
));
2880 static void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
2884 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
2885 len
= sdslen(obj
->ptr
);
2887 long n
= (long)obj
->ptr
;
2889 /* Compute how many bytes will take this integer as a radix 10 string */
2895 while((n
= n
/10) != 0) {
2900 intlen
= ll2string(buf
+1,sizeof(buf
)-1,(long long)len
);
2901 buf
[intlen
+1] = '\r';
2902 buf
[intlen
+2] = '\n';
2903 addReplySds(c
,sdsnewlen(buf
,intlen
+3));
2906 static void addReplyBulk(redisClient
*c
, robj
*obj
) {
2907 addReplyBulkLen(c
,obj
);
2909 addReply(c
,shared
.crlf
);
2912 /* In the CONFIG command we need to add vanilla C string as bulk replies */
2913 static void addReplyBulkCString(redisClient
*c
, char *s
) {
2915 addReply(c
,shared
.nullbulk
);
2917 robj
*o
= createStringObject(s
,strlen(s
));
2923 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2928 REDIS_NOTUSED(mask
);
2929 REDIS_NOTUSED(privdata
);
2931 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
2932 if (cfd
== AE_ERR
) {
2933 redisLog(REDIS_VERBOSE
,"Accepting client connection: %s", server
.neterr
);
2936 redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
);
2937 if ((c
= createClient(cfd
)) == NULL
) {
2938 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
2939 close(cfd
); /* May be already closed, just ingore errors */
2942 /* If maxclient directive is set and this is one client more... close the
2943 * connection. Note that we create the client instead to check before
2944 * for this condition, since now the socket is already set in nonblocking
2945 * mode and we can send an error for free using the Kernel I/O */
2946 if (server
.maxclients
&& listLength(server
.clients
) > server
.maxclients
) {
2947 char *err
= "-ERR max number of clients reached\r\n";
2949 /* That's a best effort error message, don't check write errors */
2950 if (write(c
->fd
,err
,strlen(err
)) == -1) {
2951 /* Nothing to do, Just to avoid the warning... */
2956 server
.stat_numconnections
++;
2959 /* ======================= Redis objects implementation ===================== */
2961 static robj
*createObject(int type
, void *ptr
) {
2964 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
2965 if (listLength(server
.objfreelist
)) {
2966 listNode
*head
= listFirst(server
.objfreelist
);
2967 o
= listNodeValue(head
);
2968 listDelNode(server
.objfreelist
,head
);
2969 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2971 if (server
.vm_enabled
)
2972 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2973 o
= zmalloc(sizeof(*o
));
2976 o
->encoding
= REDIS_ENCODING_RAW
;
2979 if (server
.vm_enabled
) {
2980 /* Note that this code may run in the context of an I/O thread
2981 * and accessing server.lruclock in theory is an error
2982 * (no locks). But in practice this is safe, and even if we read
2983 * garbage Redis will not fail. */
2984 o
->lru
= server
.lruclock
;
2985 o
->storage
= REDIS_VM_MEMORY
;
2990 static robj
*createStringObject(char *ptr
, size_t len
) {
2991 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
2994 static robj
*createStringObjectFromLongLong(long long value
) {
2996 if (value
>= 0 && value
< REDIS_SHARED_INTEGERS
) {
2997 incrRefCount(shared
.integers
[value
]);
2998 o
= shared
.integers
[value
];
3000 if (value
>= LONG_MIN
&& value
<= LONG_MAX
) {
3001 o
= createObject(REDIS_STRING
, NULL
);
3002 o
->encoding
= REDIS_ENCODING_INT
;
3003 o
->ptr
= (void*)((long)value
);
3005 o
= createObject(REDIS_STRING
,sdsfromlonglong(value
));
3011 static robj
*dupStringObject(robj
*o
) {
3012 assert(o
->encoding
== REDIS_ENCODING_RAW
);
3013 return createStringObject(o
->ptr
,sdslen(o
->ptr
));
3016 static robj
*createListObject(void) {
3017 list
*l
= listCreate();
3019 listSetFreeMethod(l
,decrRefCount
);
3020 return createObject(REDIS_LIST
,l
);
3023 static robj
*createSetObject(void) {
3024 dict
*d
= dictCreate(&setDictType
,NULL
);
3025 return createObject(REDIS_SET
,d
);
3028 static robj
*createHashObject(void) {
3029 /* All the Hashes start as zipmaps. Will be automatically converted
3030 * into hash tables if there are enough elements or big elements
3032 unsigned char *zm
= zipmapNew();
3033 robj
*o
= createObject(REDIS_HASH
,zm
);
3034 o
->encoding
= REDIS_ENCODING_ZIPMAP
;
3038 static robj
*createZsetObject(void) {
3039 zset
*zs
= zmalloc(sizeof(*zs
));
3041 zs
->dict
= dictCreate(&zsetDictType
,NULL
);
3042 zs
->zsl
= zslCreate();
3043 return createObject(REDIS_ZSET
,zs
);
3046 static void freeStringObject(robj
*o
) {
3047 if (o
->encoding
== REDIS_ENCODING_RAW
) {
3052 static void freeListObject(robj
*o
) {
3053 listRelease((list
*) o
->ptr
);
3056 static void freeSetObject(robj
*o
) {
3057 dictRelease((dict
*) o
->ptr
);
3060 static void freeZsetObject(robj
*o
) {
3063 dictRelease(zs
->dict
);
3068 static void freeHashObject(robj
*o
) {
3069 switch (o
->encoding
) {
3070 case REDIS_ENCODING_HT
:
3071 dictRelease((dict
*) o
->ptr
);
3073 case REDIS_ENCODING_ZIPMAP
:
3077 redisPanic("Unknown hash encoding type");
3082 static void incrRefCount(robj
*o
) {
3086 static void decrRefCount(void *obj
) {
3089 /* Object is a swapped out value, or in the process of being loaded. */
3090 if (server
.vm_enabled
&&
3091 (o
->storage
== REDIS_VM_SWAPPED
|| o
->storage
== REDIS_VM_LOADING
))
3093 vmpointer
*vp
= obj
;
3094 if (o
->storage
== REDIS_VM_LOADING
) vmCancelThreadedIOJob(o
);
3095 vmMarkPagesFree(vp
->page
,vp
->usedpages
);
3096 server
.vm_stats_swapped_objects
--;
3101 if (o
->refcount
<= 0) redisPanic("decrRefCount against refcount <= 0");
3102 /* Object is in memory, or in the process of being swapped out.
3104 * If the object is being swapped out, abort the operation on
3105 * decrRefCount even if the refcount does not drop to 0: the object
3106 * is referenced at least two times, as value of the key AND as
3107 * job->val in the iojob. So if we don't invalidate the iojob, when it is
3108 * done but the relevant key was removed in the meantime, the
3109 * complete jobs handler will not find the key about the job and the
3110 * assert will fail. */
3111 if (server
.vm_enabled
&& o
->storage
== REDIS_VM_SWAPPING
)
3112 vmCancelThreadedIOJob(o
);
3113 if (--(o
->refcount
) == 0) {
3115 case REDIS_STRING
: freeStringObject(o
); break;
3116 case REDIS_LIST
: freeListObject(o
); break;
3117 case REDIS_SET
: freeSetObject(o
); break;
3118 case REDIS_ZSET
: freeZsetObject(o
); break;
3119 case REDIS_HASH
: freeHashObject(o
); break;
3120 default: redisPanic("Unknown object type"); break;
3122 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
3123 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
3124 !listAddNodeHead(server
.objfreelist
,o
))
3126 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
3130 static int checkType(redisClient
*c
, robj
*o
, int type
) {
3131 if (o
->type
!= type
) {
3132 addReply(c
,shared
.wrongtypeerr
);
3138 /* Check if the nul-terminated string 's' can be represented by a long
3139 * (that is, is a number that fits into long without any other space or
3140 * character before or after the digits).
3142 * If so, the function returns REDIS_OK and *longval is set to the value
3143 * of the number. Otherwise REDIS_ERR is returned */
3144 static int isStringRepresentableAsLong(sds s
, long *longval
) {
3145 char buf
[32], *endptr
;
3149 value
= strtol(s
, &endptr
, 10);
3150 if (endptr
[0] != '\0') return REDIS_ERR
;
3151 slen
= ll2string(buf
,32,value
);
3153 /* If the number converted back into a string is not identical
3154 * then it's not possible to encode the string as integer */
3155 if (sdslen(s
) != (unsigned)slen
|| memcmp(buf
,s
,slen
)) return REDIS_ERR
;
3156 if (longval
) *longval
= value
;
3160 /* Try to encode a string object in order to save space */
3161 static robj
*tryObjectEncoding(robj
*o
) {
3165 if (o
->encoding
!= REDIS_ENCODING_RAW
)
3166 return o
; /* Already encoded */
3168 /* It's not safe to encode shared objects: shared objects can be shared
3169 * everywhere in the "object space" of Redis. Encoded objects can only
3170 * appear as "values" (and not, for instance, as keys) */
3171 if (o
->refcount
> 1) return o
;
3173 /* Currently we try to encode only strings */
3174 redisAssert(o
->type
== REDIS_STRING
);
3176 /* Check if we can represent this string as a long integer */
3177 if (isStringRepresentableAsLong(s
,&value
) == REDIS_ERR
) return o
;
3179 /* Ok, this object can be encoded */
3180 if (value
>= 0 && value
< REDIS_SHARED_INTEGERS
) {
3182 incrRefCount(shared
.integers
[value
]);
3183 return shared
.integers
[value
];
3185 o
->encoding
= REDIS_ENCODING_INT
;
3187 o
->ptr
= (void*) value
;
3192 /* Get a decoded version of an encoded object (returned as a new object).
3193 * If the object is already raw-encoded just increment the ref count. */
3194 static robj
*getDecodedObject(robj
*o
) {
3197 if (o
->encoding
== REDIS_ENCODING_RAW
) {
3201 if (o
->type
== REDIS_STRING
&& o
->encoding
== REDIS_ENCODING_INT
) {
3204 ll2string(buf
,32,(long)o
->ptr
);
3205 dec
= createStringObject(buf
,strlen(buf
));
3208 redisPanic("Unknown encoding type");
3212 /* Compare two string objects via strcmp() or alike.
3213 * Note that the objects may be integer-encoded. In such a case we
3214 * use ll2string() to get a string representation of the numbers on the stack
3215 * and compare the strings, it's much faster than calling getDecodedObject().
3217 * Important note: if objects are not integer encoded, but binary-safe strings,
3218 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
3220 static int compareStringObjects(robj
*a
, robj
*b
) {
3221 redisAssert(a
->type
== REDIS_STRING
&& b
->type
== REDIS_STRING
);
3222 char bufa
[128], bufb
[128], *astr
, *bstr
;
3225 if (a
== b
) return 0;
3226 if (a
->encoding
!= REDIS_ENCODING_RAW
) {
3227 ll2string(bufa
,sizeof(bufa
),(long) a
->ptr
);
3233 if (b
->encoding
!= REDIS_ENCODING_RAW
) {
3234 ll2string(bufb
,sizeof(bufb
),(long) b
->ptr
);
3240 return bothsds
? sdscmp(astr
,bstr
) : strcmp(astr
,bstr
);
3243 /* Equal string objects return 1 if the two objects are the same from the
3244 * point of view of a string comparison, otherwise 0 is returned. Note that
3245 * this function is faster then checking for (compareStringObject(a,b) == 0)
3246 * because it can perform some more optimization. */
3247 static int equalStringObjects(robj
*a
, robj
*b
) {
3248 if (a
->encoding
!= REDIS_ENCODING_RAW
&& b
->encoding
!= REDIS_ENCODING_RAW
){
3249 return a
->ptr
== b
->ptr
;
3251 return compareStringObjects(a
,b
) == 0;
3255 static size_t stringObjectLen(robj
*o
) {
3256 redisAssert(o
->type
== REDIS_STRING
);
3257 if (o
->encoding
== REDIS_ENCODING_RAW
) {
3258 return sdslen(o
->ptr
);
3262 return ll2string(buf
,32,(long)o
->ptr
);
3266 static int getDoubleFromObject(robj
*o
, double *target
) {
3273 redisAssert(o
->type
== REDIS_STRING
);
3274 if (o
->encoding
== REDIS_ENCODING_RAW
) {
3275 value
= strtod(o
->ptr
, &eptr
);
3276 if (eptr
[0] != '\0') return REDIS_ERR
;
3277 } else if (o
->encoding
== REDIS_ENCODING_INT
) {
3278 value
= (long)o
->ptr
;
3280 redisPanic("Unknown string encoding");
3288 static int getDoubleFromObjectOrReply(redisClient
*c
, robj
*o
, double *target
, const char *msg
) {
3290 if (getDoubleFromObject(o
, &value
) != REDIS_OK
) {
3292 addReplySds(c
, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg
));
3294 addReplySds(c
, sdsnew("-ERR value is not a double\r\n"));
3303 static int getLongLongFromObject(robj
*o
, long long *target
) {
3310 redisAssert(o
->type
== REDIS_STRING
);
3311 if (o
->encoding
== REDIS_ENCODING_RAW
) {
3312 value
= strtoll(o
->ptr
, &eptr
, 10);
3313 if (eptr
[0] != '\0') return REDIS_ERR
;
3314 } else if (o
->encoding
== REDIS_ENCODING_INT
) {
3315 value
= (long)o
->ptr
;
3317 redisPanic("Unknown string encoding");
3325 static int getLongLongFromObjectOrReply(redisClient
*c
, robj
*o
, long long *target
, const char *msg
) {
3327 if (getLongLongFromObject(o
, &value
) != REDIS_OK
) {
3329 addReplySds(c
, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg
));
3331 addReplySds(c
, sdsnew("-ERR value is not an integer\r\n"));
3340 static int getLongFromObjectOrReply(redisClient
*c
, robj
*o
, long *target
, const char *msg
) {
3343 if (getLongLongFromObjectOrReply(c
, o
, &value
, msg
) != REDIS_OK
) return REDIS_ERR
;
3344 if (value
< LONG_MIN
|| value
> LONG_MAX
) {
3346 addReplySds(c
, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg
));
3348 addReplySds(c
, sdsnew("-ERR value is out of range\r\n"));
3357 /* =========================== Keyspace access API ========================== */
3359 static robj
*lookupKey(redisDb
*db
, robj
*key
) {
3360 dictEntry
*de
= dictFind(db
->dict
,key
);
3362 robj
*key
= dictGetEntryKey(de
);
3363 robj
*val
= dictGetEntryVal(de
);
3365 if (server
.vm_enabled
) {
3366 if (val
->storage
== REDIS_VM_MEMORY
||
3367 val
->storage
== REDIS_VM_SWAPPING
)
3369 /* If we were swapping the object out, cancel the operation */
3370 if (val
->storage
== REDIS_VM_SWAPPING
)
3371 vmCancelThreadedIOJob(val
);
3372 /* Update the access time of the key for the aging algorithm. */
3373 val
->lru
= server
.lruclock
;
3375 int notify
= (val
->storage
== REDIS_VM_LOADING
);
3377 /* Our value was swapped on disk. Bring it at home. */
3378 redisAssert(val
->type
== REDIS_VMPOINTER
);
3379 val
= vmLoadObject(val
);
3380 dictGetEntryVal(de
) = val
;
3382 /* Clients blocked by the VM subsystem may be waiting for
3384 if (notify
) handleClientsBlockedOnSwappedKey(db
,key
);
3393 static robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
3394 expireIfNeeded(db
,key
);
3395 return lookupKey(db
,key
);
3398 static robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
3399 deleteIfVolatile(db
,key
);
3400 touchWatchedKey(db
,key
);
3401 return lookupKey(db
,key
);
3404 static robj
*lookupKeyReadOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
3405 robj
*o
= lookupKeyRead(c
->db
, key
);
3406 if (!o
) addReply(c
,reply
);
3410 static robj
*lookupKeyWriteOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
3411 robj
*o
= lookupKeyWrite(c
->db
, key
);
3412 if (!o
) addReply(c
,reply
);
3416 static int deleteKey(redisDb
*db
, robj
*key
) {
3419 /* We need to protect key from destruction: after the first dictDelete()
3420 * it may happen that 'key' is no longer valid if we don't increment
3421 * it's count. This may happen when we get the object reference directly
3422 * from the hash table with dictRandomKey() or dict iterators */
3424 if (dictSize(db
->expires
)) dictDelete(db
->expires
,key
);
3425 retval
= dictDelete(db
->dict
,key
);
3428 return retval
== DICT_OK
;
3431 /*============================ RDB saving/loading =========================== */
3433 static int rdbSaveType(FILE *fp
, unsigned char type
) {
3434 if (fwrite(&type
,1,1,fp
) == 0) return -1;
3438 static int rdbSaveTime(FILE *fp
, time_t t
) {
3439 int32_t t32
= (int32_t) t
;
3440 if (fwrite(&t32
,4,1,fp
) == 0) return -1;
3444 /* check rdbLoadLen() comments for more info */
3445 static int rdbSaveLen(FILE *fp
, uint32_t len
) {
3446 unsigned char buf
[2];
3449 /* Save a 6 bit len */
3450 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
3451 if (fwrite(buf
,1,1,fp
) == 0) return -1;
3452 } else if (len
< (1<<14)) {
3453 /* Save a 14 bit len */
3454 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
3456 if (fwrite(buf
,2,1,fp
) == 0) return -1;
3458 /* Save a 32 bit len */
3459 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
3460 if (fwrite(buf
,1,1,fp
) == 0) return -1;
3462 if (fwrite(&len
,4,1,fp
) == 0) return -1;
3467 /* Encode 'value' as an integer if possible (if integer will fit the
3468 * supported range). If the function sucessful encoded the integer
3469 * then the (up to 5 bytes) encoded representation is written in the
3470 * string pointed by 'enc' and the length is returned. Otherwise
3472 static int rdbEncodeInteger(long long value
, unsigned char *enc
) {
3473 /* Finally check if it fits in our ranges */
3474 if (value
>= -(1<<7) && value
<= (1<<7)-1) {
3475 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT8
;
3476 enc
[1] = value
&0xFF;
3478 } else if (value
>= -(1<<15) && value
<= (1<<15)-1) {
3479 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
;
3480 enc
[1] = value
&0xFF;
3481 enc
[2] = (value
>>8)&0xFF;
3483 } else if (value
>= -((long long)1<<31) && value
<= ((long long)1<<31)-1) {
3484 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT32
;
3485 enc
[1] = value
&0xFF;
3486 enc
[2] = (value
>>8)&0xFF;
3487 enc
[3] = (value
>>16)&0xFF;
3488 enc
[4] = (value
>>24)&0xFF;
3495 /* String objects in the form "2391" "-100" without any space and with a
3496 * range of values that can fit in an 8, 16 or 32 bit signed value can be
3497 * encoded as integers to save space */
3498 static int rdbTryIntegerEncoding(char *s
, size_t len
, unsigned char *enc
) {
3500 char *endptr
, buf
[32];
3502 /* Check if it's possible to encode this value as a number */
3503 value
= strtoll(s
, &endptr
, 10);
3504 if (endptr
[0] != '\0') return 0;
3505 ll2string(buf
,32,value
);
3507 /* If the number converted back into a string is not identical
3508 * then it's not possible to encode the string as integer */
3509 if (strlen(buf
) != len
|| memcmp(buf
,s
,len
)) return 0;
3511 return rdbEncodeInteger(value
,enc
);
3514 static int rdbSaveLzfStringObject(FILE *fp
, unsigned char *s
, size_t len
) {
3515 size_t comprlen
, outlen
;
3519 /* We require at least four bytes compression for this to be worth it */
3520 if (len
<= 4) return 0;
3522 if ((out
= zmalloc(outlen
+1)) == NULL
) return 0;
3523 comprlen
= lzf_compress(s
, len
, out
, outlen
);
3524 if (comprlen
== 0) {
3528 /* Data compressed! Let's save it on disk */
3529 byte
= (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_LZF
;
3530 if (fwrite(&byte
,1,1,fp
) == 0) goto writeerr
;
3531 if (rdbSaveLen(fp
,comprlen
) == -1) goto writeerr
;
3532 if (rdbSaveLen(fp
,len
) == -1) goto writeerr
;
3533 if (fwrite(out
,comprlen
,1,fp
) == 0) goto writeerr
;
3542 /* Save a string objet as [len][data] on disk. If the object is a string
3543 * representation of an integer value we try to safe it in a special form */
3544 static int rdbSaveRawString(FILE *fp
, unsigned char *s
, size_t len
) {
3547 /* Try integer encoding */
3549 unsigned char buf
[5];
3550 if ((enclen
= rdbTryIntegerEncoding((char*)s
,len
,buf
)) > 0) {
3551 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
3556 /* Try LZF compression - under 20 bytes it's unable to compress even
3557 * aaaaaaaaaaaaaaaaaa so skip it */
3558 if (server
.rdbcompression
&& len
> 20) {
3561 retval
= rdbSaveLzfStringObject(fp
,s
,len
);
3562 if (retval
== -1) return -1;
3563 if (retval
> 0) return 0;
3564 /* retval == 0 means data can't be compressed, save the old way */
3567 /* Store verbatim */
3568 if (rdbSaveLen(fp
,len
) == -1) return -1;
3569 if (len
&& fwrite(s
,len
,1,fp
) == 0) return -1;
3573 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
3574 static int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
3577 /* Avoid to decode the object, then encode it again, if the
3578 * object is alrady integer encoded. */
3579 if (obj
->encoding
== REDIS_ENCODING_INT
) {
3580 long val
= (long) obj
->ptr
;
3581 unsigned char buf
[5];
3584 if ((enclen
= rdbEncodeInteger(val
,buf
)) > 0) {
3585 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
3588 /* otherwise... fall throught and continue with the usual
3592 /* Avoid incr/decr ref count business when possible.
3593 * This plays well with copy-on-write given that we are probably
3594 * in a child process (BGSAVE). Also this makes sure key objects
3595 * of swapped objects are not incRefCount-ed (an assert does not allow
3596 * this in order to avoid bugs) */
3597 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
3598 obj
= getDecodedObject(obj
);
3599 retval
= rdbSaveRawString(fp
,obj
->ptr
,sdslen(obj
->ptr
));
3602 retval
= rdbSaveRawString(fp
,obj
->ptr
,sdslen(obj
->ptr
));
3607 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
3608 * 8 bit integer specifing the length of the representation.
3609 * This 8 bit integer has special values in order to specify the following
3615 static int rdbSaveDoubleValue(FILE *fp
, double val
) {
3616 unsigned char buf
[128];
3622 } else if (!isfinite(val
)) {
3624 buf
[0] = (val
< 0) ? 255 : 254;
3626 #if (DBL_MANT_DIG >= 52) && (LLONG_MAX == 0x7fffffffffffffffLL)
3627 /* Check if the float is in a safe range to be casted into a
3628 * long long. We are assuming that long long is 64 bit here.
3629 * Also we are assuming that there are no implementations around where
3630 * double has precision < 52 bit.
3632 * Under this assumptions we test if a double is inside an interval
3633 * where casting to long long is safe. Then using two castings we
3634 * make sure the decimal part is zero. If all this is true we use
3635 * integer printing function that is much faster. */
3636 double min
= -4503599627370495; /* (2^52)-1 */
3637 double max
= 4503599627370496; /* -(2^52) */
3638 if (val
> min
&& val
< max
&& val
== ((double)((long long)val
)))
3639 ll2string((char*)buf
+1,sizeof(buf
),(long long)val
);
3642 snprintf((char*)buf
+1,sizeof(buf
)-1,"%.17g",val
);
3643 buf
[0] = strlen((char*)buf
+1);
3646 if (fwrite(buf
,len
,1,fp
) == 0) return -1;
3650 /* Save a Redis object. */
3651 static int rdbSaveObject(FILE *fp
, robj
*o
) {
3652 if (o
->type
== REDIS_STRING
) {
3653 /* Save a string value */
3654 if (rdbSaveStringObject(fp
,o
) == -1) return -1;
3655 } else if (o
->type
== REDIS_LIST
) {
3656 /* Save a list value */
3657 list
*list
= o
->ptr
;
3661 if (rdbSaveLen(fp
,listLength(list
)) == -1) return -1;
3662 listRewind(list
,&li
);
3663 while((ln
= listNext(&li
))) {
3664 robj
*eleobj
= listNodeValue(ln
);
3666 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
3668 } else if (o
->type
== REDIS_SET
) {
3669 /* Save a set value */
3671 dictIterator
*di
= dictGetIterator(set
);
3674 if (rdbSaveLen(fp
,dictSize(set
)) == -1) return -1;
3675 while((de
= dictNext(di
)) != NULL
) {
3676 robj
*eleobj
= dictGetEntryKey(de
);
3678 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
3680 dictReleaseIterator(di
);
3681 } else if (o
->type
== REDIS_ZSET
) {
3682 /* Save a set value */
3684 dictIterator
*di
= dictGetIterator(zs
->dict
);
3687 if (rdbSaveLen(fp
,dictSize(zs
->dict
)) == -1) return -1;
3688 while((de
= dictNext(di
)) != NULL
) {
3689 robj
*eleobj
= dictGetEntryKey(de
);
3690 double *score
= dictGetEntryVal(de
);
3692 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
3693 if (rdbSaveDoubleValue(fp
,*score
) == -1) return -1;
3695 dictReleaseIterator(di
);
3696 } else if (o
->type
== REDIS_HASH
) {
3697 /* Save a hash value */
3698 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
3699 unsigned char *p
= zipmapRewind(o
->ptr
);
3700 unsigned int count
= zipmapLen(o
->ptr
);
3701 unsigned char *key
, *val
;
3702 unsigned int klen
, vlen
;
3704 if (rdbSaveLen(fp
,count
) == -1) return -1;
3705 while((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) != NULL
) {
3706 if (rdbSaveRawString(fp
,key
,klen
) == -1) return -1;
3707 if (rdbSaveRawString(fp
,val
,vlen
) == -1) return -1;
3710 dictIterator
*di
= dictGetIterator(o
->ptr
);
3713 if (rdbSaveLen(fp
,dictSize((dict
*)o
->ptr
)) == -1) return -1;
3714 while((de
= dictNext(di
)) != NULL
) {
3715 robj
*key
= dictGetEntryKey(de
);
3716 robj
*val
= dictGetEntryVal(de
);
3718 if (rdbSaveStringObject(fp
,key
) == -1) return -1;
3719 if (rdbSaveStringObject(fp
,val
) == -1) return -1;
3721 dictReleaseIterator(di
);
3724 redisPanic("Unknown object type");
3729 /* Return the length the object will have on disk if saved with
3730 * the rdbSaveObject() function. Currently we use a trick to get
3731 * this length with very little changes to the code. In the future
3732 * we could switch to a faster solution. */
3733 static off_t
rdbSavedObjectLen(robj
*o
, FILE *fp
) {
3734 if (fp
== NULL
) fp
= server
.devnull
;
3736 assert(rdbSaveObject(fp
,o
) != 1);
3740 /* Return the number of pages required to save this object in the swap file */
3741 static off_t
rdbSavedObjectPages(robj
*o
, FILE *fp
) {
3742 off_t bytes
= rdbSavedObjectLen(o
,fp
);
3744 return (bytes
+(server
.vm_page_size
-1))/server
.vm_page_size
;
3747 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
3748 static int rdbSave(char *filename
) {
3749 dictIterator
*di
= NULL
;
3754 time_t now
= time(NULL
);
3756 /* Wait for I/O therads to terminate, just in case this is a
3757 * foreground-saving, to avoid seeking the swap file descriptor at the
3759 if (server
.vm_enabled
)
3760 waitEmptyIOJobsQueue();
3762 snprintf(tmpfile
,256,"temp-%d.rdb", (int) getpid());
3763 fp
= fopen(tmpfile
,"w");
3765 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
3768 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
3769 for (j
= 0; j
< server
.dbnum
; j
++) {
3770 redisDb
*db
= server
.db
+j
;
3772 if (dictSize(d
) == 0) continue;
3773 di
= dictGetIterator(d
);
3779 /* Write the SELECT DB opcode */
3780 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
3781 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
3783 /* Iterate this DB writing every entry */
3784 while((de
= dictNext(di
)) != NULL
) {
3785 robj
*key
= dictGetEntryKey(de
);
3786 robj
*o
= dictGetEntryVal(de
);
3787 time_t expiretime
= getExpire(db
,key
);
3789 /* Save the expire time */
3790 if (expiretime
!= -1) {
3791 /* If this key is already expired skip it */
3792 if (expiretime
< now
) continue;
3793 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
;
3794 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
;
3796 /* Save the key and associated value. This requires special
3797 * handling if the value is swapped out. */
3798 if (!server
.vm_enabled
|| o
->storage
== REDIS_VM_MEMORY
||
3799 o
->storage
== REDIS_VM_SWAPPING
) {
3800 /* Save type, key, value */
3801 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
3802 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3803 if (rdbSaveObject(fp
,o
) == -1) goto werr
;
3805 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
3807 /* Get a preview of the object in memory */
3808 po
= vmPreviewObject(o
);
3809 /* Save type, key, value */
3810 if (rdbSaveType(fp
,po
->type
) == -1) goto werr
;
3811 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3812 if (rdbSaveObject(fp
,po
) == -1) goto werr
;
3813 /* Remove the loaded object from memory */
3817 dictReleaseIterator(di
);
3820 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
3822 /* Make sure data will not remain on the OS's output buffers */
3827 /* Use RENAME to make sure the DB file is changed atomically only
3828 * if the generate DB file is ok. */
3829 if (rename(tmpfile
,filename
) == -1) {
3830 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destination: %s", strerror(errno
));
3834 redisLog(REDIS_NOTICE
,"DB saved on disk");
3836 server
.lastsave
= time(NULL
);
3842 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
3843 if (di
) dictReleaseIterator(di
);
3847 static int rdbSaveBackground(char *filename
) {
3850 if (server
.bgsavechildpid
!= -1) return REDIS_ERR
;
3851 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
3852 if ((childpid
= fork()) == 0) {
3854 if (server
.vm_enabled
) vmReopenSwapFile();
3856 if (rdbSave(filename
) == REDIS_OK
) {
3863 if (childpid
== -1) {
3864 redisLog(REDIS_WARNING
,"Can't save in background: fork: %s",
3868 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
3869 server
.bgsavechildpid
= childpid
;
3870 updateDictResizePolicy();
3873 return REDIS_OK
; /* unreached */
3876 static void rdbRemoveTempFile(pid_t childpid
) {
3879 snprintf(tmpfile
,256,"temp-%d.rdb", (int) childpid
);
3883 static int rdbLoadType(FILE *fp
) {
3885 if (fread(&type
,1,1,fp
) == 0) return -1;
3889 static time_t rdbLoadTime(FILE *fp
) {
3891 if (fread(&t32
,4,1,fp
) == 0) return -1;
3892 return (time_t) t32
;
3895 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
3896 * of this file for a description of how this are stored on disk.
3898 * isencoded is set to 1 if the readed length is not actually a length but
3899 * an "encoding type", check the above comments for more info */
3900 static uint32_t rdbLoadLen(FILE *fp
, int *isencoded
) {
3901 unsigned char buf
[2];
3905 if (isencoded
) *isencoded
= 0;
3906 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3907 type
= (buf
[0]&0xC0)>>6;
3908 if (type
== REDIS_RDB_6BITLEN
) {
3909 /* Read a 6 bit len */
3911 } else if (type
== REDIS_RDB_ENCVAL
) {
3912 /* Read a 6 bit len encoding type */
3913 if (isencoded
) *isencoded
= 1;
3915 } else if (type
== REDIS_RDB_14BITLEN
) {
3916 /* Read a 14 bit len */
3917 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3918 return ((buf
[0]&0x3F)<<8)|buf
[1];
3920 /* Read a 32 bit len */
3921 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
3926 /* Load an integer-encoded object from file 'fp', with the specified
3927 * encoding type 'enctype'. If encode is true the function may return
3928 * an integer-encoded object as reply, otherwise the returned object
3929 * will always be encoded as a raw string. */
3930 static robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
, int encode
) {
3931 unsigned char enc
[4];
3934 if (enctype
== REDIS_RDB_ENC_INT8
) {
3935 if (fread(enc
,1,1,fp
) == 0) return NULL
;
3936 val
= (signed char)enc
[0];
3937 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
3939 if (fread(enc
,2,1,fp
) == 0) return NULL
;
3940 v
= enc
[0]|(enc
[1]<<8);
3942 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
3944 if (fread(enc
,4,1,fp
) == 0) return NULL
;
3945 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
3948 val
= 0; /* anti-warning */
3949 redisPanic("Unknown RDB integer encoding type");
3952 return createStringObjectFromLongLong(val
);
3954 return createObject(REDIS_STRING
,sdsfromlonglong(val
));
3957 static robj
*rdbLoadLzfStringObject(FILE*fp
) {
3958 unsigned int len
, clen
;
3959 unsigned char *c
= NULL
;
3962 if ((clen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3963 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3964 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
3965 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
3966 if (fread(c
,clen
,1,fp
) == 0) goto err
;
3967 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
3969 return createObject(REDIS_STRING
,val
);
3976 static robj
*rdbGenericLoadStringObject(FILE*fp
, int encode
) {
3981 len
= rdbLoadLen(fp
,&isencoded
);
3984 case REDIS_RDB_ENC_INT8
:
3985 case REDIS_RDB_ENC_INT16
:
3986 case REDIS_RDB_ENC_INT32
:
3987 return rdbLoadIntegerObject(fp
,len
,encode
);
3988 case REDIS_RDB_ENC_LZF
:
3989 return rdbLoadLzfStringObject(fp
);
3991 redisPanic("Unknown RDB encoding type");
3995 if (len
== REDIS_RDB_LENERR
) return NULL
;
3996 val
= sdsnewlen(NULL
,len
);
3997 if (len
&& fread(val
,len
,1,fp
) == 0) {
4001 return createObject(REDIS_STRING
,val
);
4004 static robj
*rdbLoadStringObject(FILE *fp
) {
4005 return rdbGenericLoadStringObject(fp
,0);
4008 static robj
*rdbLoadEncodedStringObject(FILE *fp
) {
4009 return rdbGenericLoadStringObject(fp
,1);
4012 /* For information about double serialization check rdbSaveDoubleValue() */
4013 static int rdbLoadDoubleValue(FILE *fp
, double *val
) {
4017 if (fread(&len
,1,1,fp
) == 0) return -1;
4019 case 255: *val
= R_NegInf
; return 0;
4020 case 254: *val
= R_PosInf
; return 0;
4021 case 253: *val
= R_Nan
; return 0;
4023 if (fread(buf
,len
,1,fp
) == 0) return -1;
4025 sscanf(buf
, "%lg", val
);
4030 /* Load a Redis object of the specified type from the specified file.
4031 * On success a newly allocated object is returned, otherwise NULL. */
4032 static robj
*rdbLoadObject(int type
, FILE *fp
) {
4035 redisLog(REDIS_DEBUG
,"LOADING OBJECT %d (at %d)\n",type
,ftell(fp
));
4036 if (type
== REDIS_STRING
) {
4037 /* Read string value */
4038 if ((o
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
4039 o
= tryObjectEncoding(o
);
4040 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
4041 /* Read list/set value */
4044 if ((listlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
4045 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
4046 /* It's faster to expand the dict to the right size asap in order
4047 * to avoid rehashing */
4048 if (type
== REDIS_SET
&& listlen
> DICT_HT_INITIAL_SIZE
)
4049 dictExpand(o
->ptr
,listlen
);
4050 /* Load every single element of the list/set */
4054 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
4055 ele
= tryObjectEncoding(ele
);
4056 if (type
== REDIS_LIST
) {
4057 listAddNodeTail((list
*)o
->ptr
,ele
);
4059 dictAdd((dict
*)o
->ptr
,ele
,NULL
);
4062 } else if (type
== REDIS_ZSET
) {
4063 /* Read list/set value */
4067 if ((zsetlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
4068 o
= createZsetObject();
4070 /* Load every single element of the list/set */
4073 double *score
= zmalloc(sizeof(double));
4075 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
4076 ele
= tryObjectEncoding(ele
);
4077 if (rdbLoadDoubleValue(fp
,score
) == -1) return NULL
;
4078 dictAdd(zs
->dict
,ele
,score
);
4079 zslInsert(zs
->zsl
,*score
,ele
);
4080 incrRefCount(ele
); /* added to skiplist */
4082 } else if (type
== REDIS_HASH
) {
4085 if ((hashlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
4086 o
= createHashObject();
4087 /* Too many entries? Use an hash table. */
4088 if (hashlen
> server
.hash_max_zipmap_entries
)
4089 convertToRealHash(o
);
4090 /* Load every key/value, then set it into the zipmap or hash
4091 * table, as needed. */
4095 if ((key
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
4096 if ((val
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
4097 /* If we are using a zipmap and there are too big values
4098 * the object is converted to real hash table encoding. */
4099 if (o
->encoding
!= REDIS_ENCODING_HT
&&
4100 (sdslen(key
->ptr
) > server
.hash_max_zipmap_value
||
4101 sdslen(val
->ptr
) > server
.hash_max_zipmap_value
))
4103 convertToRealHash(o
);
4106 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
4107 unsigned char *zm
= o
->ptr
;
4109 zm
= zipmapSet(zm
,key
->ptr
,sdslen(key
->ptr
),
4110 val
->ptr
,sdslen(val
->ptr
),NULL
);
4115 key
= tryObjectEncoding(key
);
4116 val
= tryObjectEncoding(val
);
4117 dictAdd((dict
*)o
->ptr
,key
,val
);
4121 redisPanic("Unknown object type");
4126 static int rdbLoad(char *filename
) {
4129 int type
, retval
, rdbver
;
4130 int swap_all_values
= 0;
4131 dict
*d
= server
.db
[0].dict
;
4132 redisDb
*db
= server
.db
+0;
4134 time_t expiretime
, now
= time(NULL
);
4136 fp
= fopen(filename
,"r");
4137 if (!fp
) return REDIS_ERR
;
4138 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
4140 if (memcmp(buf
,"REDIS",5) != 0) {
4142 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
4145 rdbver
= atoi(buf
+5);
4148 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
4157 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
4158 if (type
== REDIS_EXPIRETIME
) {
4159 if ((expiretime
= rdbLoadTime(fp
)) == -1) goto eoferr
;
4160 /* We read the time so we need to read the object type again */
4161 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
4163 if (type
== REDIS_EOF
) break;
4164 /* Handle SELECT DB opcode as a special case */
4165 if (type
== REDIS_SELECTDB
) {
4166 if ((dbid
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
)
4168 if (dbid
>= (unsigned)server
.dbnum
) {
4169 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
4172 db
= server
.db
+dbid
;
4177 if ((key
= rdbLoadStringObject(fp
)) == NULL
) goto eoferr
;
4179 if ((val
= rdbLoadObject(type
,fp
)) == NULL
) goto eoferr
;
4180 /* Check if the key already expired */
4181 if (expiretime
!= -1 && expiretime
< now
) {
4186 /* Add the new object in the hash table */
4187 retval
= dictAdd(d
,key
,val
);
4188 if (retval
== DICT_ERR
) {
4189 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key
->ptr
);
4192 /* Set the expire time if needed */
4193 if (expiretime
!= -1) setExpire(db
,key
,expiretime
);
4195 /* Handle swapping while loading big datasets when VM is on */
4197 /* If we detecter we are hopeless about fitting something in memory
4198 * we just swap every new key on disk. Directly...
4199 * Note that's important to check for this condition before resorting
4200 * to random sampling, otherwise we may try to swap already
4202 if (swap_all_values
) {
4203 dictEntry
*de
= dictFind(d
,key
);
4205 /* de may be NULL since the key already expired */
4208 key
= dictGetEntryKey(de
);
4209 val
= dictGetEntryVal(de
);
4211 if (val
->refcount
== 1 &&
4212 (vp
= vmSwapObjectBlocking(val
)) != NULL
)
4213 dictGetEntryVal(de
) = vp
;
4218 /* Flush data on disk once 32 MB of additional RAM are used... */
4220 if ((zmalloc_used_memory() - server
.vm_max_memory
) > 1024*1024*32)
4223 /* If we have still some hope of having some value fitting memory
4224 * then we try random sampling. */
4225 if (!swap_all_values
&& server
.vm_enabled
&& force_swapout
) {
4226 while (zmalloc_used_memory() > server
.vm_max_memory
) {
4227 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
4229 if (zmalloc_used_memory() > server
.vm_max_memory
)
4230 swap_all_values
= 1; /* We are already using too much mem */
4236 eoferr
: /* unexpected end of file is handled here with a fatal exit */
4237 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
4239 return REDIS_ERR
; /* Just to avoid warning */
4242 /*================================== Shutdown =============================== */
4243 static int prepareForShutdown() {
4244 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
4245 /* Kill the saving child if there is a background saving in progress.
4246 We want to avoid race conditions, for instance our saving child may
4247 overwrite the synchronous saving did by SHUTDOWN. */
4248 if (server
.bgsavechildpid
!= -1) {
4249 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
4250 kill(server
.bgsavechildpid
,SIGKILL
);
4251 rdbRemoveTempFile(server
.bgsavechildpid
);
4253 if (server
.appendonly
) {
4254 /* Append only file: fsync() the AOF and exit */
4255 aof_fsync(server
.appendfd
);
4256 if (server
.vm_enabled
) unlink(server
.vm_swap_file
);
4258 /* Snapshotting. Perform a SYNC SAVE and exit */
4259 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
4260 if (server
.daemonize
)
4261 unlink(server
.pidfile
);
4262 redisLog(REDIS_WARNING
,"%zu bytes used at exit",zmalloc_used_memory());
4264 /* Ooops.. error saving! The best we can do is to continue
4265 * operating. Note that if there was a background saving process,
4266 * in the next cron() Redis will be notified that the background
4267 * saving aborted, handling special stuff like slaves pending for
4268 * synchronization... */
4269 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
4273 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
4277 /*================================== Commands =============================== */
4279 static void authCommand(redisClient
*c
) {
4280 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
4281 c
->authenticated
= 1;
4282 addReply(c
,shared
.ok
);
4284 c
->authenticated
= 0;
4285 addReplySds(c
,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
4289 static void pingCommand(redisClient
*c
) {
4290 addReply(c
,shared
.pong
);
4293 static void echoCommand(redisClient
*c
) {
4294 addReplyBulk(c
,c
->argv
[1]);
4297 /*=================================== Strings =============================== */
4299 static void setGenericCommand(redisClient
*c
, int nx
, robj
*key
, robj
*val
, robj
*expire
) {
4301 long seconds
= 0; /* initialized to avoid an harmness warning */
4304 if (getLongFromObjectOrReply(c
, expire
, &seconds
, NULL
) != REDIS_OK
)
4307 addReplySds(c
,sdsnew("-ERR invalid expire time in SETEX\r\n"));
4312 touchWatchedKey(c
->db
,key
);
4313 if (nx
) deleteIfVolatile(c
->db
,key
);
4314 retval
= dictAdd(c
->db
->dict
,key
,val
);
4315 if (retval
== DICT_ERR
) {
4317 /* If the key is about a swapped value, we want a new key object
4318 * to overwrite the old. So we delete the old key in the database.
4319 * This will also make sure that swap pages about the old object
4320 * will be marked as free. */
4321 if (server
.vm_enabled
&& deleteIfSwapped(c
->db
,key
))
4323 dictReplace(c
->db
->dict
,key
,val
);
4326 addReply(c
,shared
.czero
);
4334 removeExpire(c
->db
,key
);
4335 if (expire
) setExpire(c
->db
,key
,time(NULL
)+seconds
);
4336 addReply(c
, nx
? shared
.cone
: shared
.ok
);
4339 static void setCommand(redisClient
*c
) {
4340 setGenericCommand(c
,0,c
->argv
[1],c
->argv
[2],NULL
);
4343 static void setnxCommand(redisClient
*c
) {
4344 setGenericCommand(c
,1,c
->argv
[1],c
->argv
[2],NULL
);
4347 static void setexCommand(redisClient
*c
) {
4348 setGenericCommand(c
,0,c
->argv
[1],c
->argv
[3],c
->argv
[2]);
4351 static int getGenericCommand(redisClient
*c
) {
4354 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
)
4357 if (o
->type
!= REDIS_STRING
) {
4358 addReply(c
,shared
.wrongtypeerr
);
4366 static void getCommand(redisClient
*c
) {
4367 getGenericCommand(c
);
4370 static void getsetCommand(redisClient
*c
) {
4371 if (getGenericCommand(c
) == REDIS_ERR
) return;
4372 if (dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]) == DICT_ERR
) {
4373 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
4375 incrRefCount(c
->argv
[1]);
4377 incrRefCount(c
->argv
[2]);
4379 removeExpire(c
->db
,c
->argv
[1]);
4382 static void mgetCommand(redisClient
*c
) {
4385 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
4386 for (j
= 1; j
< c
->argc
; j
++) {
4387 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[j
]);
4389 addReply(c
,shared
.nullbulk
);
4391 if (o
->type
!= REDIS_STRING
) {
4392 addReply(c
,shared
.nullbulk
);
4400 static void msetGenericCommand(redisClient
*c
, int nx
) {
4401 int j
, busykeys
= 0;
4403 if ((c
->argc
% 2) == 0) {
4404 addReplySds(c
,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
4407 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
4408 * set nothing at all if at least one already key exists. */
4410 for (j
= 1; j
< c
->argc
; j
+= 2) {
4411 if (lookupKeyWrite(c
->db
,c
->argv
[j
]) != NULL
) {
4417 addReply(c
, shared
.czero
);
4421 for (j
= 1; j
< c
->argc
; j
+= 2) {
4424 c
->argv
[j
+1] = tryObjectEncoding(c
->argv
[j
+1]);
4425 retval
= dictAdd(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
4426 if (retval
== DICT_ERR
) {
4427 dictReplace(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
4428 incrRefCount(c
->argv
[j
+1]);
4430 incrRefCount(c
->argv
[j
]);
4431 incrRefCount(c
->argv
[j
+1]);
4433 removeExpire(c
->db
,c
->argv
[j
]);
4435 server
.dirty
+= (c
->argc
-1)/2;
4436 addReply(c
, nx
? shared
.cone
: shared
.ok
);
4439 static void msetCommand(redisClient
*c
) {
4440 msetGenericCommand(c
,0);
4443 static void msetnxCommand(redisClient
*c
) {
4444 msetGenericCommand(c
,1);
4447 static void incrDecrCommand(redisClient
*c
, long long incr
) {
4452 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4453 if (o
!= NULL
&& checkType(c
,o
,REDIS_STRING
)) return;
4454 if (getLongLongFromObjectOrReply(c
,o
,&value
,NULL
) != REDIS_OK
) return;
4457 o
= createStringObjectFromLongLong(value
);
4458 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],o
);
4459 if (retval
== DICT_ERR
) {
4460 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
4461 removeExpire(c
->db
,c
->argv
[1]);
4463 incrRefCount(c
->argv
[1]);
4466 addReply(c
,shared
.colon
);
4468 addReply(c
,shared
.crlf
);
4471 static void incrCommand(redisClient
*c
) {
4472 incrDecrCommand(c
,1);
4475 static void decrCommand(redisClient
*c
) {
4476 incrDecrCommand(c
,-1);
4479 static void incrbyCommand(redisClient
*c
) {
4482 if (getLongLongFromObjectOrReply(c
, c
->argv
[2], &incr
, NULL
) != REDIS_OK
) return;
4483 incrDecrCommand(c
,incr
);
4486 static void decrbyCommand(redisClient
*c
) {
4489 if (getLongLongFromObjectOrReply(c
, c
->argv
[2], &incr
, NULL
) != REDIS_OK
) return;
4490 incrDecrCommand(c
,-incr
);
4493 static void appendCommand(redisClient
*c
) {
4498 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4500 /* Create the key */
4501 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
4502 incrRefCount(c
->argv
[1]);
4503 incrRefCount(c
->argv
[2]);
4504 totlen
= stringObjectLen(c
->argv
[2]);
4508 de
= dictFind(c
->db
->dict
,c
->argv
[1]);
4511 o
= dictGetEntryVal(de
);
4512 if (o
->type
!= REDIS_STRING
) {
4513 addReply(c
,shared
.wrongtypeerr
);
4516 /* If the object is specially encoded or shared we have to make
4518 if (o
->refcount
!= 1 || o
->encoding
!= REDIS_ENCODING_RAW
) {
4519 robj
*decoded
= getDecodedObject(o
);
4521 o
= createStringObject(decoded
->ptr
, sdslen(decoded
->ptr
));
4522 decrRefCount(decoded
);
4523 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
4526 if (c
->argv
[2]->encoding
== REDIS_ENCODING_RAW
) {
4527 o
->ptr
= sdscatlen(o
->ptr
,
4528 c
->argv
[2]->ptr
, sdslen(c
->argv
[2]->ptr
));
4530 o
->ptr
= sdscatprintf(o
->ptr
, "%ld",
4531 (unsigned long) c
->argv
[2]->ptr
);
4533 totlen
= sdslen(o
->ptr
);
4536 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",(unsigned long)totlen
));
4539 static void substrCommand(redisClient
*c
) {
4541 long start
= atoi(c
->argv
[2]->ptr
);
4542 long end
= atoi(c
->argv
[3]->ptr
);
4543 size_t rangelen
, strlen
;
4546 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
4547 checkType(c
,o
,REDIS_STRING
)) return;
4549 o
= getDecodedObject(o
);
4550 strlen
= sdslen(o
->ptr
);
4552 /* convert negative indexes */
4553 if (start
< 0) start
= strlen
+start
;
4554 if (end
< 0) end
= strlen
+end
;
4555 if (start
< 0) start
= 0;
4556 if (end
< 0) end
= 0;
4558 /* indexes sanity checks */
4559 if (start
> end
|| (size_t)start
>= strlen
) {
4560 /* Out of range start or start > end result in null reply */
4561 addReply(c
,shared
.nullbulk
);
4565 if ((size_t)end
>= strlen
) end
= strlen
-1;
4566 rangelen
= (end
-start
)+1;
4568 /* Return the result */
4569 addReplySds(c
,sdscatprintf(sdsempty(),"$%zu\r\n",rangelen
));
4570 range
= sdsnewlen((char*)o
->ptr
+start
,rangelen
);
4571 addReplySds(c
,range
);
4572 addReply(c
,shared
.crlf
);
4576 /* ========================= Type agnostic commands ========================= */
4578 static void delCommand(redisClient
*c
) {
4581 for (j
= 1; j
< c
->argc
; j
++) {
4582 if (deleteKey(c
->db
,c
->argv
[j
])) {
4583 touchWatchedKey(c
->db
,c
->argv
[j
]);
4588 addReplyLongLong(c
,deleted
);
4591 static void existsCommand(redisClient
*c
) {
4592 expireIfNeeded(c
->db
,c
->argv
[1]);
4593 if (dictFind(c
->db
->dict
,c
->argv
[1])) {
4594 addReply(c
, shared
.cone
);
4596 addReply(c
, shared
.czero
);
4600 static void selectCommand(redisClient
*c
) {
4601 int id
= atoi(c
->argv
[1]->ptr
);
4603 if (selectDb(c
,id
) == REDIS_ERR
) {
4604 addReplySds(c
,sdsnew("-ERR invalid DB index\r\n"));
4606 addReply(c
,shared
.ok
);
4610 static void randomkeyCommand(redisClient
*c
) {
4615 de
= dictGetRandomKey(c
->db
->dict
);
4616 if (!de
|| expireIfNeeded(c
->db
,dictGetEntryKey(de
)) == 0) break;
4620 addReply(c
,shared
.nullbulk
);
4624 key
= dictGetEntryKey(de
);
4625 if (server
.vm_enabled
) {
4626 key
= dupStringObject(key
);
4627 addReplyBulk(c
,key
);
4630 addReplyBulk(c
,key
);
4634 static void keysCommand(redisClient
*c
) {
4637 sds pattern
= c
->argv
[1]->ptr
;
4638 int plen
= sdslen(pattern
);
4639 unsigned long numkeys
= 0;
4640 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
4642 di
= dictGetIterator(c
->db
->dict
);
4644 decrRefCount(lenobj
);
4645 while((de
= dictNext(di
)) != NULL
) {
4646 robj
*keyobj
= dictGetEntryKey(de
);
4648 sds key
= keyobj
->ptr
;
4649 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
4650 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
4651 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
4652 addReplyBulk(c
,keyobj
);
4657 dictReleaseIterator(di
);
4658 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",numkeys
);
4661 static void dbsizeCommand(redisClient
*c
) {
4663 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c
->db
->dict
)));
4666 static void lastsaveCommand(redisClient
*c
) {
4668 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
4671 static void typeCommand(redisClient
*c
) {
4675 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4680 case REDIS_STRING
: type
= "+string"; break;
4681 case REDIS_LIST
: type
= "+list"; break;
4682 case REDIS_SET
: type
= "+set"; break;
4683 case REDIS_ZSET
: type
= "+zset"; break;
4684 case REDIS_HASH
: type
= "+hash"; break;
4685 default: type
= "+unknown"; break;
4688 addReplySds(c
,sdsnew(type
));
4689 addReply(c
,shared
.crlf
);
4692 static void saveCommand(redisClient
*c
) {
4693 if (server
.bgsavechildpid
!= -1) {
4694 addReplySds(c
,sdsnew("-ERR background save in progress\r\n"));
4697 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
4698 addReply(c
,shared
.ok
);
4700 addReply(c
,shared
.err
);
4704 static void bgsaveCommand(redisClient
*c
) {
4705 if (server
.bgsavechildpid
!= -1) {
4706 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
4709 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
4710 char *status
= "+Background saving started\r\n";
4711 addReplySds(c
,sdsnew(status
));
4713 addReply(c
,shared
.err
);
4717 static void shutdownCommand(redisClient
*c
) {
4718 if (prepareForShutdown() == REDIS_OK
)
4720 addReplySds(c
, sdsnew("-ERR Errors trying to SHUTDOWN. Check logs.\r\n"));
4723 static void renameGenericCommand(redisClient
*c
, int nx
) {
4726 /* To use the same key as src and dst is probably an error */
4727 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
4728 addReply(c
,shared
.sameobjecterr
);
4732 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
)
4736 deleteIfVolatile(c
->db
,c
->argv
[2]);
4737 if (dictAdd(c
->db
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
4740 addReply(c
,shared
.czero
);
4743 dictReplace(c
->db
->dict
,c
->argv
[2],o
);
4745 incrRefCount(c
->argv
[2]);
4747 deleteKey(c
->db
,c
->argv
[1]);
4748 touchWatchedKey(c
->db
,c
->argv
[2]);
4750 addReply(c
,nx
? shared
.cone
: shared
.ok
);
4753 static void renameCommand(redisClient
*c
) {
4754 renameGenericCommand(c
,0);
4757 static void renamenxCommand(redisClient
*c
) {
4758 renameGenericCommand(c
,1);
4761 static void moveCommand(redisClient
*c
) {
4766 /* Obtain source and target DB pointers */
4769 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
4770 addReply(c
,shared
.outofrangeerr
);
4774 selectDb(c
,srcid
); /* Back to the source DB */
4776 /* If the user is moving using as target the same
4777 * DB as the source DB it is probably an error. */
4779 addReply(c
,shared
.sameobjecterr
);
4783 /* Check if the element exists and get a reference */
4784 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4786 addReply(c
,shared
.czero
);
4790 /* Try to add the element to the target DB */
4791 deleteIfVolatile(dst
,c
->argv
[1]);
4792 if (dictAdd(dst
->dict
,c
->argv
[1],o
) == DICT_ERR
) {
4793 addReply(c
,shared
.czero
);
4796 incrRefCount(c
->argv
[1]);
4799 /* OK! key moved, free the entry in the source DB */
4800 deleteKey(src
,c
->argv
[1]);
4802 addReply(c
,shared
.cone
);
4805 /* =================================== Lists ================================ */
4806 static void pushGenericCommand(redisClient
*c
, int where
) {
4810 lobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4812 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
4813 addReply(c
,shared
.cone
);
4816 lobj
= createListObject();
4818 if (where
== REDIS_HEAD
) {
4819 listAddNodeHead(list
,c
->argv
[2]);
4821 listAddNodeTail(list
,c
->argv
[2]);
4823 dictAdd(c
->db
->dict
,c
->argv
[1],lobj
);
4824 incrRefCount(c
->argv
[1]);
4825 incrRefCount(c
->argv
[2]);
4827 if (lobj
->type
!= REDIS_LIST
) {
4828 addReply(c
,shared
.wrongtypeerr
);
4831 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
4832 addReply(c
,shared
.cone
);
4836 if (where
== REDIS_HEAD
) {
4837 listAddNodeHead(list
,c
->argv
[2]);
4839 listAddNodeTail(list
,c
->argv
[2]);
4841 incrRefCount(c
->argv
[2]);
4844 addReplyLongLong(c
,listLength(list
));
4847 static void lpushCommand(redisClient
*c
) {
4848 pushGenericCommand(c
,REDIS_HEAD
);
4851 static void rpushCommand(redisClient
*c
) {
4852 pushGenericCommand(c
,REDIS_TAIL
);
4855 static void llenCommand(redisClient
*c
) {
4859 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
4860 checkType(c
,o
,REDIS_LIST
)) return;
4863 addReplyUlong(c
,listLength(l
));
4866 static void lindexCommand(redisClient
*c
) {
4868 int index
= atoi(c
->argv
[2]->ptr
);
4872 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
4873 checkType(c
,o
,REDIS_LIST
)) return;
4876 ln
= listIndex(list
, index
);
4878 addReply(c
,shared
.nullbulk
);
4880 robj
*ele
= listNodeValue(ln
);
4881 addReplyBulk(c
,ele
);
4885 static void lsetCommand(redisClient
*c
) {
4887 int index
= atoi(c
->argv
[2]->ptr
);
4891 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
||
4892 checkType(c
,o
,REDIS_LIST
)) return;
4895 ln
= listIndex(list
, index
);
4897 addReply(c
,shared
.outofrangeerr
);
4899 robj
*ele
= listNodeValue(ln
);
4902 listNodeValue(ln
) = c
->argv
[3];
4903 incrRefCount(c
->argv
[3]);
4904 addReply(c
,shared
.ok
);
4909 static void popGenericCommand(redisClient
*c
, int where
) {
4914 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
4915 checkType(c
,o
,REDIS_LIST
)) return;
4918 if (where
== REDIS_HEAD
)
4919 ln
= listFirst(list
);
4921 ln
= listLast(list
);
4924 addReply(c
,shared
.nullbulk
);
4926 robj
*ele
= listNodeValue(ln
);
4927 addReplyBulk(c
,ele
);
4928 listDelNode(list
,ln
);
4929 if (listLength(list
) == 0) deleteKey(c
->db
,c
->argv
[1]);
4934 static void lpopCommand(redisClient
*c
) {
4935 popGenericCommand(c
,REDIS_HEAD
);
4938 static void rpopCommand(redisClient
*c
) {
4939 popGenericCommand(c
,REDIS_TAIL
);
4942 static void lrangeCommand(redisClient
*c
) {
4944 int start
= atoi(c
->argv
[2]->ptr
);
4945 int end
= atoi(c
->argv
[3]->ptr
);
4952 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.emptymultibulk
)) == NULL
4953 || checkType(c
,o
,REDIS_LIST
)) return;
4955 llen
= listLength(list
);
4957 /* convert negative indexes */
4958 if (start
< 0) start
= llen
+start
;
4959 if (end
< 0) end
= llen
+end
;
4960 if (start
< 0) start
= 0;
4961 if (end
< 0) end
= 0;
4963 /* indexes sanity checks */
4964 if (start
> end
|| start
>= llen
) {
4965 /* Out of range start or start > end result in empty list */
4966 addReply(c
,shared
.emptymultibulk
);
4969 if (end
>= llen
) end
= llen
-1;
4970 rangelen
= (end
-start
)+1;
4972 /* Return the result in form of a multi-bulk reply */
4973 ln
= listIndex(list
, start
);
4974 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
4975 for (j
= 0; j
< rangelen
; j
++) {
4976 ele
= listNodeValue(ln
);
4977 addReplyBulk(c
,ele
);
4982 static void ltrimCommand(redisClient
*c
) {
4984 int start
= atoi(c
->argv
[2]->ptr
);
4985 int end
= atoi(c
->argv
[3]->ptr
);
4987 int j
, ltrim
, rtrim
;
4991 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.ok
)) == NULL
||
4992 checkType(c
,o
,REDIS_LIST
)) return;
4994 llen
= listLength(list
);
4996 /* convert negative indexes */
4997 if (start
< 0) start
= llen
+start
;
4998 if (end
< 0) end
= llen
+end
;
4999 if (start
< 0) start
= 0;
5000 if (end
< 0) end
= 0;
5002 /* indexes sanity checks */
5003 if (start
> end
|| start
>= llen
) {
5004 /* Out of range start or start > end result in empty list */
5008 if (end
>= llen
) end
= llen
-1;
5013 /* Remove list elements to perform the trim */
5014 for (j
= 0; j
< ltrim
; j
++) {
5015 ln
= listFirst(list
);
5016 listDelNode(list
,ln
);
5018 for (j
= 0; j
< rtrim
; j
++) {
5019 ln
= listLast(list
);
5020 listDelNode(list
,ln
);
5022 if (listLength(list
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5024 addReply(c
,shared
.ok
);
5027 static void lremCommand(redisClient
*c
) {
5030 listNode
*ln
, *next
;
5031 int toremove
= atoi(c
->argv
[2]->ptr
);
5035 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5036 checkType(c
,o
,REDIS_LIST
)) return;
5040 toremove
= -toremove
;
5043 ln
= fromtail
? list
->tail
: list
->head
;
5045 robj
*ele
= listNodeValue(ln
);
5047 next
= fromtail
? ln
->prev
: ln
->next
;
5048 if (equalStringObjects(ele
,c
->argv
[3])) {
5049 listDelNode(list
,ln
);
5052 if (toremove
&& removed
== toremove
) break;
5056 if (listLength(list
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5057 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
5060 /* This is the semantic of this command:
5061 * RPOPLPUSH srclist dstlist:
5062 * IF LLEN(srclist) > 0
5063 * element = RPOP srclist
5064 * LPUSH dstlist element
5071 * The idea is to be able to get an element from a list in a reliable way
5072 * since the element is not just returned but pushed against another list
5073 * as well. This command was originally proposed by Ezra Zygmuntowicz.
5075 static void rpoplpushcommand(redisClient
*c
) {
5080 if ((sobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
5081 checkType(c
,sobj
,REDIS_LIST
)) return;
5082 srclist
= sobj
->ptr
;
5083 ln
= listLast(srclist
);
5086 addReply(c
,shared
.nullbulk
);
5088 robj
*dobj
= lookupKeyWrite(c
->db
,c
->argv
[2]);
5089 robj
*ele
= listNodeValue(ln
);
5092 if (dobj
&& dobj
->type
!= REDIS_LIST
) {
5093 addReply(c
,shared
.wrongtypeerr
);
5097 /* Add the element to the target list (unless it's directly
5098 * passed to some BLPOP-ing client */
5099 if (!handleClientsWaitingListPush(c
,c
->argv
[2],ele
)) {
5101 /* Create the list if the key does not exist */
5102 dobj
= createListObject();
5103 dictAdd(c
->db
->dict
,c
->argv
[2],dobj
);
5104 incrRefCount(c
->argv
[2]);
5106 dstlist
= dobj
->ptr
;
5107 listAddNodeHead(dstlist
,ele
);
5111 /* Send the element to the client as reply as well */
5112 addReplyBulk(c
,ele
);
5114 /* Finally remove the element from the source list */
5115 listDelNode(srclist
,ln
);
5116 if (listLength(srclist
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5121 /* ==================================== Sets ================================ */
5123 static void saddCommand(redisClient
*c
) {
5126 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
5128 set
= createSetObject();
5129 dictAdd(c
->db
->dict
,c
->argv
[1],set
);
5130 incrRefCount(c
->argv
[1]);
5132 if (set
->type
!= REDIS_SET
) {
5133 addReply(c
,shared
.wrongtypeerr
);
5137 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
5138 incrRefCount(c
->argv
[2]);
5140 addReply(c
,shared
.cone
);
5142 addReply(c
,shared
.czero
);
5146 static void sremCommand(redisClient
*c
) {
5149 if ((set
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5150 checkType(c
,set
,REDIS_SET
)) return;
5152 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
5154 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
5155 if (dictSize((dict
*)set
->ptr
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5156 addReply(c
,shared
.cone
);
5158 addReply(c
,shared
.czero
);
5162 static void smoveCommand(redisClient
*c
) {
5163 robj
*srcset
, *dstset
;
5165 srcset
= lookupKeyWrite(c
->db
,c
->argv
[1]);
5166 dstset
= lookupKeyWrite(c
->db
,c
->argv
[2]);
5168 /* If the source key does not exist return 0, if it's of the wrong type
5170 if (srcset
== NULL
|| srcset
->type
!= REDIS_SET
) {
5171 addReply(c
, srcset
? shared
.wrongtypeerr
: shared
.czero
);
5174 /* Error if the destination key is not a set as well */
5175 if (dstset
&& dstset
->type
!= REDIS_SET
) {
5176 addReply(c
,shared
.wrongtypeerr
);
5179 /* Remove the element from the source set */
5180 if (dictDelete(srcset
->ptr
,c
->argv
[3]) == DICT_ERR
) {
5181 /* Key not found in the src set! return zero */
5182 addReply(c
,shared
.czero
);
5185 if (dictSize((dict
*)srcset
->ptr
) == 0 && srcset
!= dstset
)
5186 deleteKey(c
->db
,c
->argv
[1]);
5188 /* Add the element to the destination set */
5190 dstset
= createSetObject();
5191 dictAdd(c
->db
->dict
,c
->argv
[2],dstset
);
5192 incrRefCount(c
->argv
[2]);
5194 if (dictAdd(dstset
->ptr
,c
->argv
[3],NULL
) == DICT_OK
)
5195 incrRefCount(c
->argv
[3]);
5196 addReply(c
,shared
.cone
);
5199 static void sismemberCommand(redisClient
*c
) {
5202 if ((set
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5203 checkType(c
,set
,REDIS_SET
)) return;
5205 if (dictFind(set
->ptr
,c
->argv
[2]))
5206 addReply(c
,shared
.cone
);
5208 addReply(c
,shared
.czero
);
5211 static void scardCommand(redisClient
*c
) {
5215 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5216 checkType(c
,o
,REDIS_SET
)) return;
5219 addReplyUlong(c
,dictSize(s
));
5222 static void spopCommand(redisClient
*c
) {
5226 if ((set
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
5227 checkType(c
,set
,REDIS_SET
)) return;
5229 de
= dictGetRandomKey(set
->ptr
);
5231 addReply(c
,shared
.nullbulk
);
5233 robj
*ele
= dictGetEntryKey(de
);
5235 addReplyBulk(c
,ele
);
5236 dictDelete(set
->ptr
,ele
);
5237 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
5238 if (dictSize((dict
*)set
->ptr
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5243 static void srandmemberCommand(redisClient
*c
) {
5247 if ((set
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
5248 checkType(c
,set
,REDIS_SET
)) return;
5250 de
= dictGetRandomKey(set
->ptr
);
5252 addReply(c
,shared
.nullbulk
);
5254 robj
*ele
= dictGetEntryKey(de
);
5256 addReplyBulk(c
,ele
);
5260 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
5261 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
5263 return dictSize(*d1
)-dictSize(*d2
);
5266 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, unsigned long setsnum
, robj
*dstkey
) {
5267 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
5270 robj
*lenobj
= NULL
, *dstset
= NULL
;
5271 unsigned long j
, cardinality
= 0;
5273 for (j
= 0; j
< setsnum
; j
++) {
5277 lookupKeyWrite(c
->db
,setskeys
[j
]) :
5278 lookupKeyRead(c
->db
,setskeys
[j
]);
5282 if (deleteKey(c
->db
,dstkey
))
5284 addReply(c
,shared
.czero
);
5286 addReply(c
,shared
.emptymultibulk
);
5290 if (setobj
->type
!= REDIS_SET
) {
5292 addReply(c
,shared
.wrongtypeerr
);
5295 dv
[j
] = setobj
->ptr
;
5297 /* Sort sets from the smallest to largest, this will improve our
5298 * algorithm's performace */
5299 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
5301 /* The first thing we should output is the total number of elements...
5302 * since this is a multi-bulk write, but at this stage we don't know
5303 * the intersection set size, so we use a trick, append an empty object
5304 * to the output list and save the pointer to later modify it with the
5307 lenobj
= createObject(REDIS_STRING
,NULL
);
5309 decrRefCount(lenobj
);
5311 /* If we have a target key where to store the resulting set
5312 * create this key with an empty set inside */
5313 dstset
= createSetObject();
5316 /* Iterate all the elements of the first (smallest) set, and test
5317 * the element against all the other sets, if at least one set does
5318 * not include the element it is discarded */
5319 di
= dictGetIterator(dv
[0]);
5321 while((de
= dictNext(di
)) != NULL
) {
5324 for (j
= 1; j
< setsnum
; j
++)
5325 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
5327 continue; /* at least one set does not contain the member */
5328 ele
= dictGetEntryKey(de
);
5330 addReplyBulk(c
,ele
);
5333 dictAdd(dstset
->ptr
,ele
,NULL
);
5337 dictReleaseIterator(di
);
5340 /* Store the resulting set into the target, if the intersection
5341 * is not an empty set. */
5342 deleteKey(c
->db
,dstkey
);
5343 if (dictSize((dict
*)dstset
->ptr
) > 0) {
5344 dictAdd(c
->db
->dict
,dstkey
,dstset
);
5345 incrRefCount(dstkey
);
5346 addReplyLongLong(c
,dictSize((dict
*)dstset
->ptr
));
5348 decrRefCount(dstset
);
5349 addReply(c
,shared
.czero
);
5353 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",cardinality
);
5358 static void sinterCommand(redisClient
*c
) {
5359 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
5362 static void sinterstoreCommand(redisClient
*c
) {
5363 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
5366 #define REDIS_OP_UNION 0
5367 #define REDIS_OP_DIFF 1
5368 #define REDIS_OP_INTER 2
5370 static void sunionDiffGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
, int op
) {
5371 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
5374 robj
*dstset
= NULL
;
5375 int j
, cardinality
= 0;
5377 for (j
= 0; j
< setsnum
; j
++) {
5381 lookupKeyWrite(c
->db
,setskeys
[j
]) :
5382 lookupKeyRead(c
->db
,setskeys
[j
]);
5387 if (setobj
->type
!= REDIS_SET
) {
5389 addReply(c
,shared
.wrongtypeerr
);
5392 dv
[j
] = setobj
->ptr
;
5395 /* We need a temp set object to store our union. If the dstkey
5396 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
5397 * this set object will be the resulting object to set into the target key*/
5398 dstset
= createSetObject();
5400 /* Iterate all the elements of all the sets, add every element a single
5401 * time to the result set */
5402 for (j
= 0; j
< setsnum
; j
++) {
5403 if (op
== REDIS_OP_DIFF
&& j
== 0 && !dv
[j
]) break; /* result set is empty */
5404 if (!dv
[j
]) continue; /* non existing keys are like empty sets */
5406 di
= dictGetIterator(dv
[j
]);
5408 while((de
= dictNext(di
)) != NULL
) {
5411 /* dictAdd will not add the same element multiple times */
5412 ele
= dictGetEntryKey(de
);
5413 if (op
== REDIS_OP_UNION
|| j
== 0) {
5414 if (dictAdd(dstset
->ptr
,ele
,NULL
) == DICT_OK
) {
5418 } else if (op
== REDIS_OP_DIFF
) {
5419 if (dictDelete(dstset
->ptr
,ele
) == DICT_OK
) {
5424 dictReleaseIterator(di
);
5426 /* result set is empty? Exit asap. */
5427 if (op
== REDIS_OP_DIFF
&& cardinality
== 0) break;
5430 /* Output the content of the resulting set, if not in STORE mode */
5432 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",cardinality
));
5433 di
= dictGetIterator(dstset
->ptr
);
5434 while((de
= dictNext(di
)) != NULL
) {
5437 ele
= dictGetEntryKey(de
);
5438 addReplyBulk(c
,ele
);
5440 dictReleaseIterator(di
);
5441 decrRefCount(dstset
);
5443 /* If we have a target key where to store the resulting set
5444 * create this key with the result set inside */
5445 deleteKey(c
->db
,dstkey
);
5446 if (dictSize((dict
*)dstset
->ptr
) > 0) {
5447 dictAdd(c
->db
->dict
,dstkey
,dstset
);
5448 incrRefCount(dstkey
);
5449 addReplyLongLong(c
,dictSize((dict
*)dstset
->ptr
));
5451 decrRefCount(dstset
);
5452 addReply(c
,shared
.czero
);
5459 static void sunionCommand(redisClient
*c
) {
5460 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_UNION
);
5463 static void sunionstoreCommand(redisClient
*c
) {
5464 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_UNION
);
5467 static void sdiffCommand(redisClient
*c
) {
5468 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_DIFF
);
5471 static void sdiffstoreCommand(redisClient
*c
) {
5472 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_DIFF
);
5475 /* ==================================== ZSets =============================== */
5477 /* ZSETs are ordered sets using two data structures to hold the same elements
5478 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
5481 * The elements are added to an hash table mapping Redis objects to scores.
5482 * At the same time the elements are added to a skip list mapping scores
5483 * to Redis objects (so objects are sorted by scores in this "view"). */
5485 /* This skiplist implementation is almost a C translation of the original
5486 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
5487 * Alternative to Balanced Trees", modified in three ways:
5488 * a) this implementation allows for repeated values.
5489 * b) the comparison is not just by key (our 'score') but by satellite data.
5490 * c) there is a back pointer, so it's a doubly linked list with the back
5491 * pointers being only at "level 1". This allows to traverse the list
5492 * from tail to head, useful for ZREVRANGE. */
5494 static zskiplistNode
*zslCreateNode(int level
, double score
, robj
*obj
) {
5495 zskiplistNode
*zn
= zmalloc(sizeof(*zn
));
5497 zn
->forward
= zmalloc(sizeof(zskiplistNode
*) * level
);
5499 zn
->span
= zmalloc(sizeof(unsigned int) * (level
- 1));
5507 static zskiplist
*zslCreate(void) {
5511 zsl
= zmalloc(sizeof(*zsl
));
5514 zsl
->header
= zslCreateNode(ZSKIPLIST_MAXLEVEL
,0,NULL
);
5515 for (j
= 0; j
< ZSKIPLIST_MAXLEVEL
; j
++) {
5516 zsl
->header
->forward
[j
] = NULL
;
5518 /* span has space for ZSKIPLIST_MAXLEVEL-1 elements */
5519 if (j
< ZSKIPLIST_MAXLEVEL
-1)
5520 zsl
->header
->span
[j
] = 0;
5522 zsl
->header
->backward
= NULL
;
5527 static void zslFreeNode(zskiplistNode
*node
) {
5528 decrRefCount(node
->obj
);
5529 zfree(node
->forward
);
5534 static void zslFree(zskiplist
*zsl
) {
5535 zskiplistNode
*node
= zsl
->header
->forward
[0], *next
;
5537 zfree(zsl
->header
->forward
);
5538 zfree(zsl
->header
->span
);
5541 next
= node
->forward
[0];
5548 static int zslRandomLevel(void) {
5550 while ((random()&0xFFFF) < (ZSKIPLIST_P
* 0xFFFF))
5552 return (level
<ZSKIPLIST_MAXLEVEL
) ? level
: ZSKIPLIST_MAXLEVEL
;
5555 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
) {
5556 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5557 unsigned int rank
[ZSKIPLIST_MAXLEVEL
];
5561 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5562 /* store rank that is crossed to reach the insert position */
5563 rank
[i
] = i
== (zsl
->level
-1) ? 0 : rank
[i
+1];
5565 while (x
->forward
[i
] &&
5566 (x
->forward
[i
]->score
< score
||
5567 (x
->forward
[i
]->score
== score
&&
5568 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0))) {
5569 rank
[i
] += i
> 0 ? x
->span
[i
-1] : 1;
5574 /* we assume the key is not already inside, since we allow duplicated
5575 * scores, and the re-insertion of score and redis object should never
5576 * happpen since the caller of zslInsert() should test in the hash table
5577 * if the element is already inside or not. */
5578 level
= zslRandomLevel();
5579 if (level
> zsl
->level
) {
5580 for (i
= zsl
->level
; i
< level
; i
++) {
5582 update
[i
] = zsl
->header
;
5583 update
[i
]->span
[i
-1] = zsl
->length
;
5587 x
= zslCreateNode(level
,score
,obj
);
5588 for (i
= 0; i
< level
; i
++) {
5589 x
->forward
[i
] = update
[i
]->forward
[i
];
5590 update
[i
]->forward
[i
] = x
;
5592 /* update span covered by update[i] as x is inserted here */
5594 x
->span
[i
-1] = update
[i
]->span
[i
-1] - (rank
[0] - rank
[i
]);
5595 update
[i
]->span
[i
-1] = (rank
[0] - rank
[i
]) + 1;
5599 /* increment span for untouched levels */
5600 for (i
= level
; i
< zsl
->level
; i
++) {
5601 update
[i
]->span
[i
-1]++;
5604 x
->backward
= (update
[0] == zsl
->header
) ? NULL
: update
[0];
5606 x
->forward
[0]->backward
= x
;
5612 /* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
5613 void zslDeleteNode(zskiplist
*zsl
, zskiplistNode
*x
, zskiplistNode
**update
) {
5615 for (i
= 0; i
< zsl
->level
; i
++) {
5616 if (update
[i
]->forward
[i
] == x
) {
5618 update
[i
]->span
[i
-1] += x
->span
[i
-1] - 1;
5620 update
[i
]->forward
[i
] = x
->forward
[i
];
5622 /* invariant: i > 0, because update[0]->forward[0]
5623 * is always equal to x */
5624 update
[i
]->span
[i
-1] -= 1;
5627 if (x
->forward
[0]) {
5628 x
->forward
[0]->backward
= x
->backward
;
5630 zsl
->tail
= x
->backward
;
5632 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
5637 /* Delete an element with matching score/object from the skiplist. */
5638 static int zslDelete(zskiplist
*zsl
, double score
, robj
*obj
) {
5639 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5643 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5644 while (x
->forward
[i
] &&
5645 (x
->forward
[i
]->score
< score
||
5646 (x
->forward
[i
]->score
== score
&&
5647 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
5651 /* We may have multiple elements with the same score, what we need
5652 * is to find the element with both the right score and object. */
5654 if (x
&& score
== x
->score
&& equalStringObjects(x
->obj
,obj
)) {
5655 zslDeleteNode(zsl
, x
, update
);
5659 return 0; /* not found */
5661 return 0; /* not found */
5664 /* Delete all the elements with score between min and max from the skiplist.
5665 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
5666 * Note that this function takes the reference to the hash table view of the
5667 * sorted set, in order to remove the elements from the hash table too. */
5668 static unsigned long zslDeleteRangeByScore(zskiplist
*zsl
, double min
, double max
, dict
*dict
) {
5669 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5670 unsigned long removed
= 0;
5674 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5675 while (x
->forward
[i
] && x
->forward
[i
]->score
< min
)
5679 /* We may have multiple elements with the same score, what we need
5680 * is to find the element with both the right score and object. */
5682 while (x
&& x
->score
<= max
) {
5683 zskiplistNode
*next
= x
->forward
[0];
5684 zslDeleteNode(zsl
, x
, update
);
5685 dictDelete(dict
,x
->obj
);
5690 return removed
; /* not found */
5693 /* Delete all the elements with rank between start and end from the skiplist.
5694 * Start and end are inclusive. Note that start and end need to be 1-based */
5695 static unsigned long zslDeleteRangeByRank(zskiplist
*zsl
, unsigned int start
, unsigned int end
, dict
*dict
) {
5696 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5697 unsigned long traversed
= 0, removed
= 0;
5701 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5702 while (x
->forward
[i
] && (traversed
+ (i
> 0 ? x
->span
[i
-1] : 1)) < start
) {
5703 traversed
+= i
> 0 ? x
->span
[i
-1] : 1;
5711 while (x
&& traversed
<= end
) {
5712 zskiplistNode
*next
= x
->forward
[0];
5713 zslDeleteNode(zsl
, x
, update
);
5714 dictDelete(dict
,x
->obj
);
5723 /* Find the first node having a score equal or greater than the specified one.
5724 * Returns NULL if there is no match. */
5725 static zskiplistNode
*zslFirstWithScore(zskiplist
*zsl
, double score
) {
5730 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5731 while (x
->forward
[i
] && x
->forward
[i
]->score
< score
)
5734 /* We may have multiple elements with the same score, what we need
5735 * is to find the element with both the right score and object. */
5736 return x
->forward
[0];
5739 /* Find the rank for an element by both score and key.
5740 * Returns 0 when the element cannot be found, rank otherwise.
5741 * Note that the rank is 1-based due to the span of zsl->header to the
5743 static unsigned long zslGetRank(zskiplist
*zsl
, double score
, robj
*o
) {
5745 unsigned long rank
= 0;
5749 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5750 while (x
->forward
[i
] &&
5751 (x
->forward
[i
]->score
< score
||
5752 (x
->forward
[i
]->score
== score
&&
5753 compareStringObjects(x
->forward
[i
]->obj
,o
) <= 0))) {
5754 rank
+= i
> 0 ? x
->span
[i
-1] : 1;
5758 /* x might be equal to zsl->header, so test if obj is non-NULL */
5759 if (x
->obj
&& equalStringObjects(x
->obj
,o
)) {
5766 /* Finds an element by its rank. The rank argument needs to be 1-based. */
5767 zskiplistNode
* zslGetElementByRank(zskiplist
*zsl
, unsigned long rank
) {
5769 unsigned long traversed
= 0;
5773 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5774 while (x
->forward
[i
] && (traversed
+ (i
>0 ? x
->span
[i
-1] : 1)) <= rank
)
5776 traversed
+= i
> 0 ? x
->span
[i
-1] : 1;
5779 if (traversed
== rank
) {
5786 /* The actual Z-commands implementations */
5788 /* This generic command implements both ZADD and ZINCRBY.
5789 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
5790 * the increment if the operation is a ZINCRBY (doincrement == 1). */
5791 static void zaddGenericCommand(redisClient
*c
, robj
*key
, robj
*ele
, double scoreval
, int doincrement
) {
5796 if (isnan(scoreval
)) {
5797 addReplySds(c
,sdsnew("-ERR provide score is Not A Number (nan)\r\n"));
5801 zsetobj
= lookupKeyWrite(c
->db
,key
);
5802 if (zsetobj
== NULL
) {
5803 zsetobj
= createZsetObject();
5804 dictAdd(c
->db
->dict
,key
,zsetobj
);
5807 if (zsetobj
->type
!= REDIS_ZSET
) {
5808 addReply(c
,shared
.wrongtypeerr
);
5814 /* Ok now since we implement both ZADD and ZINCRBY here the code
5815 * needs to handle the two different conditions. It's all about setting
5816 * '*score', that is, the new score to set, to the right value. */
5817 score
= zmalloc(sizeof(double));
5821 /* Read the old score. If the element was not present starts from 0 */
5822 de
= dictFind(zs
->dict
,ele
);
5824 double *oldscore
= dictGetEntryVal(de
);
5825 *score
= *oldscore
+ scoreval
;
5829 if (isnan(*score
)) {
5831 sdsnew("-ERR resulting score is Not A Number (nan)\r\n"));
5833 /* Note that we don't need to check if the zset may be empty and
5834 * should be removed here, as we can only obtain Nan as score if
5835 * there was already an element in the sorted set. */
5842 /* What follows is a simple remove and re-insert operation that is common
5843 * to both ZADD and ZINCRBY... */
5844 if (dictAdd(zs
->dict
,ele
,score
) == DICT_OK
) {
5845 /* case 1: New element */
5846 incrRefCount(ele
); /* added to hash */
5847 zslInsert(zs
->zsl
,*score
,ele
);
5848 incrRefCount(ele
); /* added to skiplist */
5851 addReplyDouble(c
,*score
);
5853 addReply(c
,shared
.cone
);
5858 /* case 2: Score update operation */
5859 de
= dictFind(zs
->dict
,ele
);
5860 redisAssert(de
!= NULL
);
5861 oldscore
= dictGetEntryVal(de
);
5862 if (*score
!= *oldscore
) {
5865 /* Remove and insert the element in the skip list with new score */
5866 deleted
= zslDelete(zs
->zsl
,*oldscore
,ele
);
5867 redisAssert(deleted
!= 0);
5868 zslInsert(zs
->zsl
,*score
,ele
);
5870 /* Update the score in the hash table */
5871 dictReplace(zs
->dict
,ele
,score
);
5877 addReplyDouble(c
,*score
);
5879 addReply(c
,shared
.czero
);
5883 static void zaddCommand(redisClient
*c
) {
5886 if (getDoubleFromObjectOrReply(c
, c
->argv
[2], &scoreval
, NULL
) != REDIS_OK
) return;
5887 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,0);
5890 static void zincrbyCommand(redisClient
*c
) {
5893 if (getDoubleFromObjectOrReply(c
, c
->argv
[2], &scoreval
, NULL
) != REDIS_OK
) return;
5894 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,1);
5897 static void zremCommand(redisClient
*c
) {
5904 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5905 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
5908 de
= dictFind(zs
->dict
,c
->argv
[2]);
5910 addReply(c
,shared
.czero
);
5913 /* Delete from the skiplist */
5914 oldscore
= dictGetEntryVal(de
);
5915 deleted
= zslDelete(zs
->zsl
,*oldscore
,c
->argv
[2]);
5916 redisAssert(deleted
!= 0);
5918 /* Delete from the hash table */
5919 dictDelete(zs
->dict
,c
->argv
[2]);
5920 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
5921 if (dictSize(zs
->dict
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5923 addReply(c
,shared
.cone
);
5926 static void zremrangebyscoreCommand(redisClient
*c
) {
5933 if ((getDoubleFromObjectOrReply(c
, c
->argv
[2], &min
, NULL
) != REDIS_OK
) ||
5934 (getDoubleFromObjectOrReply(c
, c
->argv
[3], &max
, NULL
) != REDIS_OK
)) return;
5936 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5937 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
5940 deleted
= zslDeleteRangeByScore(zs
->zsl
,min
,max
,zs
->dict
);
5941 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
5942 if (dictSize(zs
->dict
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5943 server
.dirty
+= deleted
;
5944 addReplyLongLong(c
,deleted
);
5947 static void zremrangebyrankCommand(redisClient
*c
) {
5955 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
5956 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
5958 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5959 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
5961 llen
= zs
->zsl
->length
;
5963 /* convert negative indexes */
5964 if (start
< 0) start
= llen
+start
;
5965 if (end
< 0) end
= llen
+end
;
5966 if (start
< 0) start
= 0;
5967 if (end
< 0) end
= 0;
5969 /* indexes sanity checks */
5970 if (start
> end
|| start
>= llen
) {
5971 addReply(c
,shared
.czero
);
5974 if (end
>= llen
) end
= llen
-1;
5976 /* increment start and end because zsl*Rank functions
5977 * use 1-based rank */
5978 deleted
= zslDeleteRangeByRank(zs
->zsl
,start
+1,end
+1,zs
->dict
);
5979 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
5980 if (dictSize(zs
->dict
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5981 server
.dirty
+= deleted
;
5982 addReplyLongLong(c
, deleted
);
5990 static int qsortCompareZsetopsrcByCardinality(const void *s1
, const void *s2
) {
5991 zsetopsrc
*d1
= (void*) s1
, *d2
= (void*) s2
;
5992 unsigned long size1
, size2
;
5993 size1
= d1
->dict
? dictSize(d1
->dict
) : 0;
5994 size2
= d2
->dict
? dictSize(d2
->dict
) : 0;
5995 return size1
- size2
;
5998 #define REDIS_AGGR_SUM 1
5999 #define REDIS_AGGR_MIN 2
6000 #define REDIS_AGGR_MAX 3
6001 #define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
6003 inline static void zunionInterAggregate(double *target
, double val
, int aggregate
) {
6004 if (aggregate
== REDIS_AGGR_SUM
) {
6005 *target
= *target
+ val
;
6006 } else if (aggregate
== REDIS_AGGR_MIN
) {
6007 *target
= val
< *target
? val
: *target
;
6008 } else if (aggregate
== REDIS_AGGR_MAX
) {
6009 *target
= val
> *target
? val
: *target
;
6012 redisPanic("Unknown ZUNION/INTER aggregate type");
6016 static void zunionInterGenericCommand(redisClient
*c
, robj
*dstkey
, int op
) {
6018 int aggregate
= REDIS_AGGR_SUM
;
6025 /* expect setnum input keys to be given */
6026 setnum
= atoi(c
->argv
[2]->ptr
);
6028 addReplySds(c
,sdsnew("-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE\r\n"));
6032 /* test if the expected number of keys would overflow */
6033 if (3+setnum
> c
->argc
) {
6034 addReply(c
,shared
.syntaxerr
);
6038 /* read keys to be used for input */
6039 src
= zmalloc(sizeof(zsetopsrc
) * setnum
);
6040 for (i
= 0, j
= 3; i
< setnum
; i
++, j
++) {
6041 robj
*obj
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
6045 if (obj
->type
== REDIS_ZSET
) {
6046 src
[i
].dict
= ((zset
*)obj
->ptr
)->dict
;
6047 } else if (obj
->type
== REDIS_SET
) {
6048 src
[i
].dict
= (obj
->ptr
);
6051 addReply(c
,shared
.wrongtypeerr
);
6056 /* default all weights to 1 */
6057 src
[i
].weight
= 1.0;
6060 /* parse optional extra arguments */
6062 int remaining
= c
->argc
- j
;
6065 if (remaining
>= (setnum
+ 1) && !strcasecmp(c
->argv
[j
]->ptr
,"weights")) {
6067 for (i
= 0; i
< setnum
; i
++, j
++, remaining
--) {
6068 if (getDoubleFromObjectOrReply(c
, c
->argv
[j
], &src
[i
].weight
, NULL
) != REDIS_OK
)
6071 } else if (remaining
>= 2 && !strcasecmp(c
->argv
[j
]->ptr
,"aggregate")) {
6073 if (!strcasecmp(c
->argv
[j
]->ptr
,"sum")) {
6074 aggregate
= REDIS_AGGR_SUM
;
6075 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"min")) {
6076 aggregate
= REDIS_AGGR_MIN
;
6077 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"max")) {
6078 aggregate
= REDIS_AGGR_MAX
;
6081 addReply(c
,shared
.syntaxerr
);
6087 addReply(c
,shared
.syntaxerr
);
6093 /* sort sets from the smallest to largest, this will improve our
6094 * algorithm's performance */
6095 qsort(src
,setnum
,sizeof(zsetopsrc
),qsortCompareZsetopsrcByCardinality
);
6097 dstobj
= createZsetObject();
6098 dstzset
= dstobj
->ptr
;
6100 if (op
== REDIS_OP_INTER
) {
6101 /* skip going over all entries if the smallest zset is NULL or empty */
6102 if (src
[0].dict
&& dictSize(src
[0].dict
) > 0) {
6103 /* precondition: as src[0].dict is non-empty and the zsets are ordered
6104 * from small to large, all src[i > 0].dict are non-empty too */
6105 di
= dictGetIterator(src
[0].dict
);
6106 while((de
= dictNext(di
)) != NULL
) {
6107 double *score
= zmalloc(sizeof(double)), value
;
6108 *score
= src
[0].weight
* zunionInterDictValue(de
);
6110 for (j
= 1; j
< setnum
; j
++) {
6111 dictEntry
*other
= dictFind(src
[j
].dict
,dictGetEntryKey(de
));
6113 value
= src
[j
].weight
* zunionInterDictValue(other
);
6114 zunionInterAggregate(score
, value
, aggregate
);
6120 /* skip entry when not present in every source dict */
6124 robj
*o
= dictGetEntryKey(de
);
6125 dictAdd(dstzset
->dict
,o
,score
);
6126 incrRefCount(o
); /* added to dictionary */
6127 zslInsert(dstzset
->zsl
,*score
,o
);
6128 incrRefCount(o
); /* added to skiplist */
6131 dictReleaseIterator(di
);
6133 } else if (op
== REDIS_OP_UNION
) {
6134 for (i
= 0; i
< setnum
; i
++) {
6135 if (!src
[i
].dict
) continue;
6137 di
= dictGetIterator(src
[i
].dict
);
6138 while((de
= dictNext(di
)) != NULL
) {
6139 /* skip key when already processed */
6140 if (dictFind(dstzset
->dict
,dictGetEntryKey(de
)) != NULL
) continue;
6142 double *score
= zmalloc(sizeof(double)), value
;
6143 *score
= src
[i
].weight
* zunionInterDictValue(de
);
6145 /* because the zsets are sorted by size, its only possible
6146 * for sets at larger indices to hold this entry */
6147 for (j
= (i
+1); j
< setnum
; j
++) {
6148 dictEntry
*other
= dictFind(src
[j
].dict
,dictGetEntryKey(de
));
6150 value
= src
[j
].weight
* zunionInterDictValue(other
);
6151 zunionInterAggregate(score
, value
, aggregate
);
6155 robj
*o
= dictGetEntryKey(de
);
6156 dictAdd(dstzset
->dict
,o
,score
);
6157 incrRefCount(o
); /* added to dictionary */
6158 zslInsert(dstzset
->zsl
,*score
,o
);
6159 incrRefCount(o
); /* added to skiplist */
6161 dictReleaseIterator(di
);
6164 /* unknown operator */
6165 redisAssert(op
== REDIS_OP_INTER
|| op
== REDIS_OP_UNION
);
6168 deleteKey(c
->db
,dstkey
);
6169 if (dstzset
->zsl
->length
) {
6170 dictAdd(c
->db
->dict
,dstkey
,dstobj
);
6171 incrRefCount(dstkey
);
6172 addReplyLongLong(c
, dstzset
->zsl
->length
);
6175 decrRefCount(dstobj
);
6176 addReply(c
, shared
.czero
);
6181 static void zunionstoreCommand(redisClient
*c
) {
6182 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_UNION
);
6185 static void zinterstoreCommand(redisClient
*c
) {
6186 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_INTER
);
6189 static void zrangeGenericCommand(redisClient
*c
, int reverse
) {
6201 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
6202 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
6204 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
6206 } else if (c
->argc
>= 5) {
6207 addReply(c
,shared
.syntaxerr
);
6211 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.emptymultibulk
)) == NULL
6212 || checkType(c
,o
,REDIS_ZSET
)) return;
6217 /* convert negative indexes */
6218 if (start
< 0) start
= llen
+start
;
6219 if (end
< 0) end
= llen
+end
;
6220 if (start
< 0) start
= 0;
6221 if (end
< 0) end
= 0;
6223 /* indexes sanity checks */
6224 if (start
> end
|| start
>= llen
) {
6225 /* Out of range start or start > end result in empty list */
6226 addReply(c
,shared
.emptymultibulk
);
6229 if (end
>= llen
) end
= llen
-1;
6230 rangelen
= (end
-start
)+1;
6232 /* check if starting point is trivial, before searching
6233 * the element in log(N) time */
6235 ln
= start
== 0 ? zsl
->tail
: zslGetElementByRank(zsl
, llen
-start
);
6238 zsl
->header
->forward
[0] : zslGetElementByRank(zsl
, start
+1);
6241 /* Return the result in form of a multi-bulk reply */
6242 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",
6243 withscores
? (rangelen
*2) : rangelen
));
6244 for (j
= 0; j
< rangelen
; j
++) {
6246 addReplyBulk(c
,ele
);
6248 addReplyDouble(c
,ln
->score
);
6249 ln
= reverse
? ln
->backward
: ln
->forward
[0];
6253 static void zrangeCommand(redisClient
*c
) {
6254 zrangeGenericCommand(c
,0);
6257 static void zrevrangeCommand(redisClient
*c
) {
6258 zrangeGenericCommand(c
,1);
6261 /* This command implements both ZRANGEBYSCORE and ZCOUNT.
6262 * If justcount is non-zero, just the count is returned. */
6263 static void genericZrangebyscoreCommand(redisClient
*c
, int justcount
) {
6266 int minex
= 0, maxex
= 0; /* are min or max exclusive? */
6267 int offset
= 0, limit
= -1;
6271 /* Parse the min-max interval. If one of the values is prefixed
6272 * by the "(" character, it's considered "open". For instance
6273 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
6274 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
6275 if (((char*)c
->argv
[2]->ptr
)[0] == '(') {
6276 min
= strtod((char*)c
->argv
[2]->ptr
+1,NULL
);
6279 min
= strtod(c
->argv
[2]->ptr
,NULL
);
6281 if (((char*)c
->argv
[3]->ptr
)[0] == '(') {
6282 max
= strtod((char*)c
->argv
[3]->ptr
+1,NULL
);
6285 max
= strtod(c
->argv
[3]->ptr
,NULL
);
6288 /* Parse "WITHSCORES": note that if the command was called with
6289 * the name ZCOUNT then we are sure that c->argc == 4, so we'll never
6290 * enter the following paths to parse WITHSCORES and LIMIT. */
6291 if (c
->argc
== 5 || c
->argc
== 8) {
6292 if (strcasecmp(c
->argv
[c
->argc
-1]->ptr
,"withscores") == 0)
6297 if (c
->argc
!= (4 + withscores
) && c
->argc
!= (7 + withscores
))
6301 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
6306 if (c
->argc
== (7 + withscores
) && strcasecmp(c
->argv
[4]->ptr
,"limit")) {
6307 addReply(c
,shared
.syntaxerr
);
6309 } else if (c
->argc
== (7 + withscores
)) {
6310 offset
= atoi(c
->argv
[5]->ptr
);
6311 limit
= atoi(c
->argv
[6]->ptr
);
6312 if (offset
< 0) offset
= 0;
6315 /* Ok, lookup the key and get the range */
6316 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
6318 addReply(c
,justcount
? shared
.czero
: shared
.emptymultibulk
);
6320 if (o
->type
!= REDIS_ZSET
) {
6321 addReply(c
,shared
.wrongtypeerr
);
6323 zset
*zsetobj
= o
->ptr
;
6324 zskiplist
*zsl
= zsetobj
->zsl
;
6326 robj
*ele
, *lenobj
= NULL
;
6327 unsigned long rangelen
= 0;
6329 /* Get the first node with the score >= min, or with
6330 * score > min if 'minex' is true. */
6331 ln
= zslFirstWithScore(zsl
,min
);
6332 while (minex
&& ln
&& ln
->score
== min
) ln
= ln
->forward
[0];
6335 /* No element matching the speciifed interval */
6336 addReply(c
,justcount
? shared
.czero
: shared
.emptymultibulk
);
6340 /* We don't know in advance how many matching elements there
6341 * are in the list, so we push this object that will represent
6342 * the multi-bulk length in the output buffer, and will "fix"
6345 lenobj
= createObject(REDIS_STRING
,NULL
);
6347 decrRefCount(lenobj
);
6350 while(ln
&& (maxex
? (ln
->score
< max
) : (ln
->score
<= max
))) {
6353 ln
= ln
->forward
[0];
6356 if (limit
== 0) break;
6359 addReplyBulk(c
,ele
);
6361 addReplyDouble(c
,ln
->score
);
6363 ln
= ln
->forward
[0];
6365 if (limit
> 0) limit
--;
6368 addReplyLongLong(c
,(long)rangelen
);
6370 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",
6371 withscores
? (rangelen
*2) : rangelen
);
6377 static void zrangebyscoreCommand(redisClient
*c
) {
6378 genericZrangebyscoreCommand(c
,0);
6381 static void zcountCommand(redisClient
*c
) {
6382 genericZrangebyscoreCommand(c
,1);
6385 static void zcardCommand(redisClient
*c
) {
6389 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
6390 checkType(c
,o
,REDIS_ZSET
)) return;
6393 addReplyUlong(c
,zs
->zsl
->length
);
6396 static void zscoreCommand(redisClient
*c
) {
6401 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
6402 checkType(c
,o
,REDIS_ZSET
)) return;
6405 de
= dictFind(zs
->dict
,c
->argv
[2]);
6407 addReply(c
,shared
.nullbulk
);
6409 double *score
= dictGetEntryVal(de
);
6411 addReplyDouble(c
,*score
);
6415 static void zrankGenericCommand(redisClient
*c
, int reverse
) {
6423 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
6424 checkType(c
,o
,REDIS_ZSET
)) return;
6428 de
= dictFind(zs
->dict
,c
->argv
[2]);
6430 addReply(c
,shared
.nullbulk
);
6434 score
= dictGetEntryVal(de
);
6435 rank
= zslGetRank(zsl
, *score
, c
->argv
[2]);
6438 addReplyLongLong(c
, zsl
->length
- rank
);
6440 addReplyLongLong(c
, rank
-1);
6443 addReply(c
,shared
.nullbulk
);
6447 static void zrankCommand(redisClient
*c
) {
6448 zrankGenericCommand(c
, 0);
6451 static void zrevrankCommand(redisClient
*c
) {
6452 zrankGenericCommand(c
, 1);
6455 /* ========================= Hashes utility functions ======================= */
6456 #define REDIS_HASH_KEY 1
6457 #define REDIS_HASH_VALUE 2
6459 /* Check the length of a number of objects to see if we need to convert a
6460 * zipmap to a real hash. Note that we only check string encoded objects
6461 * as their string length can be queried in constant time. */
6462 static void hashTryConversion(robj
*subject
, robj
**argv
, int start
, int end
) {
6464 if (subject
->encoding
!= REDIS_ENCODING_ZIPMAP
) return;
6466 for (i
= start
; i
<= end
; i
++) {
6467 if (argv
[i
]->encoding
== REDIS_ENCODING_RAW
&&
6468 sdslen(argv
[i
]->ptr
) > server
.hash_max_zipmap_value
)
6470 convertToRealHash(subject
);
6476 /* Encode given objects in-place when the hash uses a dict. */
6477 static void hashTryObjectEncoding(robj
*subject
, robj
**o1
, robj
**o2
) {
6478 if (subject
->encoding
== REDIS_ENCODING_HT
) {
6479 if (o1
) *o1
= tryObjectEncoding(*o1
);
6480 if (o2
) *o2
= tryObjectEncoding(*o2
);
6484 /* Get the value from a hash identified by key. Returns either a string
6485 * object or NULL if the value cannot be found. The refcount of the object
6486 * is always increased by 1 when the value was found. */
6487 static robj
*hashGet(robj
*o
, robj
*key
) {
6489 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6492 key
= getDecodedObject(key
);
6493 if (zipmapGet(o
->ptr
,key
->ptr
,sdslen(key
->ptr
),&v
,&vlen
)) {
6494 value
= createStringObject((char*)v
,vlen
);
6498 dictEntry
*de
= dictFind(o
->ptr
,key
);
6500 value
= dictGetEntryVal(de
);
6501 incrRefCount(value
);
6507 /* Test if the key exists in the given hash. Returns 1 if the key
6508 * exists and 0 when it doesn't. */
6509 static int hashExists(robj
*o
, robj
*key
) {
6510 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6511 key
= getDecodedObject(key
);
6512 if (zipmapExists(o
->ptr
,key
->ptr
,sdslen(key
->ptr
))) {
6518 if (dictFind(o
->ptr
,key
) != NULL
) {
6525 /* Add an element, discard the old if the key already exists.
6526 * Return 0 on insert and 1 on update. */
6527 static int hashSet(robj
*o
, robj
*key
, robj
*value
) {
6529 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6530 key
= getDecodedObject(key
);
6531 value
= getDecodedObject(value
);
6532 o
->ptr
= zipmapSet(o
->ptr
,
6533 key
->ptr
,sdslen(key
->ptr
),
6534 value
->ptr
,sdslen(value
->ptr
), &update
);
6536 decrRefCount(value
);
6538 /* Check if the zipmap needs to be upgraded to a real hash table */
6539 if (zipmapLen(o
->ptr
) > server
.hash_max_zipmap_entries
)
6540 convertToRealHash(o
);
6542 if (dictReplace(o
->ptr
,key
,value
)) {
6549 incrRefCount(value
);
6554 /* Delete an element from a hash.
6555 * Return 1 on deleted and 0 on not found. */
6556 static int hashDelete(robj
*o
, robj
*key
) {
6558 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6559 key
= getDecodedObject(key
);
6560 o
->ptr
= zipmapDel(o
->ptr
,key
->ptr
,sdslen(key
->ptr
), &deleted
);
6563 deleted
= dictDelete((dict
*)o
->ptr
,key
) == DICT_OK
;
6564 /* Always check if the dictionary needs a resize after a delete. */
6565 if (deleted
&& htNeedsResize(o
->ptr
)) dictResize(o
->ptr
);
6570 /* Return the number of elements in a hash. */
6571 static unsigned long hashLength(robj
*o
) {
6572 return (o
->encoding
== REDIS_ENCODING_ZIPMAP
) ?
6573 zipmapLen((unsigned char*)o
->ptr
) : dictSize((dict
*)o
->ptr
);
6576 /* Structure to hold hash iteration abstration. Note that iteration over
6577 * hashes involves both fields and values. Because it is possible that
6578 * not both are required, store pointers in the iterator to avoid
6579 * unnecessary memory allocation for fields/values. */
6583 unsigned char *zk
, *zv
;
6584 unsigned int zklen
, zvlen
;
6590 static hashIterator
*hashInitIterator(robj
*subject
) {
6591 hashIterator
*hi
= zmalloc(sizeof(hashIterator
));
6592 hi
->encoding
= subject
->encoding
;
6593 if (hi
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6594 hi
->zi
= zipmapRewind(subject
->ptr
);
6595 } else if (hi
->encoding
== REDIS_ENCODING_HT
) {
6596 hi
->di
= dictGetIterator(subject
->ptr
);
6603 static void hashReleaseIterator(hashIterator
*hi
) {
6604 if (hi
->encoding
== REDIS_ENCODING_HT
) {
6605 dictReleaseIterator(hi
->di
);
6610 /* Move to the next entry in the hash. Return REDIS_OK when the next entry
6611 * could be found and REDIS_ERR when the iterator reaches the end. */
6612 static int hashNext(hashIterator
*hi
) {
6613 if (hi
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6614 if ((hi
->zi
= zipmapNext(hi
->zi
, &hi
->zk
, &hi
->zklen
,
6615 &hi
->zv
, &hi
->zvlen
)) == NULL
) return REDIS_ERR
;
6617 if ((hi
->de
= dictNext(hi
->di
)) == NULL
) return REDIS_ERR
;
6622 /* Get key or value object at current iteration position.
6623 * This increases the refcount of the field object by 1. */
6624 static robj
*hashCurrent(hashIterator
*hi
, int what
) {
6626 if (hi
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6627 if (what
& REDIS_HASH_KEY
) {
6628 o
= createStringObject((char*)hi
->zk
,hi
->zklen
);
6630 o
= createStringObject((char*)hi
->zv
,hi
->zvlen
);
6633 if (what
& REDIS_HASH_KEY
) {
6634 o
= dictGetEntryKey(hi
->de
);
6636 o
= dictGetEntryVal(hi
->de
);
6643 static robj
*hashLookupWriteOrCreate(redisClient
*c
, robj
*key
) {
6644 robj
*o
= lookupKeyWrite(c
->db
,key
);
6646 o
= createHashObject();
6647 dictAdd(c
->db
->dict
,key
,o
);
6650 if (o
->type
!= REDIS_HASH
) {
6651 addReply(c
,shared
.wrongtypeerr
);
6658 /* ============================= Hash commands ============================== */
6659 static void hsetCommand(redisClient
*c
) {
6663 if ((o
= hashLookupWriteOrCreate(c
,c
->argv
[1])) == NULL
) return;
6664 hashTryConversion(o
,c
->argv
,2,3);
6665 hashTryObjectEncoding(o
,&c
->argv
[2], &c
->argv
[3]);
6666 update
= hashSet(o
,c
->argv
[2],c
->argv
[3]);
6667 addReply(c
, update
? shared
.czero
: shared
.cone
);
6671 static void hsetnxCommand(redisClient
*c
) {
6673 if ((o
= hashLookupWriteOrCreate(c
,c
->argv
[1])) == NULL
) return;
6674 hashTryConversion(o
,c
->argv
,2,3);
6676 if (hashExists(o
, c
->argv
[2])) {
6677 addReply(c
, shared
.czero
);
6679 hashTryObjectEncoding(o
,&c
->argv
[2], &c
->argv
[3]);
6680 hashSet(o
,c
->argv
[2],c
->argv
[3]);
6681 addReply(c
, shared
.cone
);
6686 static void hmsetCommand(redisClient
*c
) {
6690 if ((c
->argc
% 2) == 1) {
6691 addReplySds(c
,sdsnew("-ERR wrong number of arguments for HMSET\r\n"));
6695 if ((o
= hashLookupWriteOrCreate(c
,c
->argv
[1])) == NULL
) return;
6696 hashTryConversion(o
,c
->argv
,2,c
->argc
-1);
6697 for (i
= 2; i
< c
->argc
; i
+= 2) {
6698 hashTryObjectEncoding(o
,&c
->argv
[i
], &c
->argv
[i
+1]);
6699 hashSet(o
,c
->argv
[i
],c
->argv
[i
+1]);
6701 addReply(c
, shared
.ok
);
6705 static void hincrbyCommand(redisClient
*c
) {
6706 long long value
, incr
;
6707 robj
*o
, *current
, *new;
6709 if (getLongLongFromObjectOrReply(c
,c
->argv
[3],&incr
,NULL
) != REDIS_OK
) return;
6710 if ((o
= hashLookupWriteOrCreate(c
,c
->argv
[1])) == NULL
) return;
6711 if ((current
= hashGet(o
,c
->argv
[2])) != NULL
) {
6712 if (getLongLongFromObjectOrReply(c
,current
,&value
,
6713 "hash value is not an integer") != REDIS_OK
) {
6714 decrRefCount(current
);
6717 decrRefCount(current
);
6723 new = createStringObjectFromLongLong(value
);
6724 hashTryObjectEncoding(o
,&c
->argv
[2],NULL
);
6725 hashSet(o
,c
->argv
[2],new);
6727 addReplyLongLong(c
,value
);
6731 static void hgetCommand(redisClient
*c
) {
6733 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
6734 checkType(c
,o
,REDIS_HASH
)) return;
6736 if ((value
= hashGet(o
,c
->argv
[2])) != NULL
) {
6737 addReplyBulk(c
,value
);
6738 decrRefCount(value
);
6740 addReply(c
,shared
.nullbulk
);
6744 static void hmgetCommand(redisClient
*c
) {
6747 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
6748 if (o
!= NULL
&& o
->type
!= REDIS_HASH
) {
6749 addReply(c
,shared
.wrongtypeerr
);
6752 /* Note the check for o != NULL happens inside the loop. This is
6753 * done because objects that cannot be found are considered to be
6754 * an empty hash. The reply should then be a series of NULLs. */
6755 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-2));
6756 for (i
= 2; i
< c
->argc
; i
++) {
6757 if (o
!= NULL
&& (value
= hashGet(o
,c
->argv
[i
])) != NULL
) {
6758 addReplyBulk(c
,value
);
6759 decrRefCount(value
);
6761 addReply(c
,shared
.nullbulk
);
6766 static void hdelCommand(redisClient
*c
) {
6768 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
6769 checkType(c
,o
,REDIS_HASH
)) return;
6771 if (hashDelete(o
,c
->argv
[2])) {
6772 if (hashLength(o
) == 0) deleteKey(c
->db
,c
->argv
[1]);
6773 addReply(c
,shared
.cone
);
6776 addReply(c
,shared
.czero
);
6780 static void hlenCommand(redisClient
*c
) {
6782 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
6783 checkType(c
,o
,REDIS_HASH
)) return;
6785 addReplyUlong(c
,hashLength(o
));
6788 static void genericHgetallCommand(redisClient
*c
, int flags
) {
6789 robj
*o
, *lenobj
, *obj
;
6790 unsigned long count
= 0;
6793 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.emptymultibulk
)) == NULL
6794 || checkType(c
,o
,REDIS_HASH
)) return;
6796 lenobj
= createObject(REDIS_STRING
,NULL
);
6798 decrRefCount(lenobj
);
6800 hi
= hashInitIterator(o
);
6801 while (hashNext(hi
) != REDIS_ERR
) {
6802 if (flags
& REDIS_HASH_KEY
) {
6803 obj
= hashCurrent(hi
,REDIS_HASH_KEY
);
6804 addReplyBulk(c
,obj
);
6808 if (flags
& REDIS_HASH_VALUE
) {
6809 obj
= hashCurrent(hi
,REDIS_HASH_VALUE
);
6810 addReplyBulk(c
,obj
);
6815 hashReleaseIterator(hi
);
6817 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",count
);
6820 static void hkeysCommand(redisClient
*c
) {
6821 genericHgetallCommand(c
,REDIS_HASH_KEY
);
6824 static void hvalsCommand(redisClient
*c
) {
6825 genericHgetallCommand(c
,REDIS_HASH_VALUE
);
6828 static void hgetallCommand(redisClient
*c
) {
6829 genericHgetallCommand(c
,REDIS_HASH_KEY
|REDIS_HASH_VALUE
);
6832 static void hexistsCommand(redisClient
*c
) {
6834 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
6835 checkType(c
,o
,REDIS_HASH
)) return;
6837 addReply(c
, hashExists(o
,c
->argv
[2]) ? shared
.cone
: shared
.czero
);
6840 static void convertToRealHash(robj
*o
) {
6841 unsigned char *key
, *val
, *p
, *zm
= o
->ptr
;
6842 unsigned int klen
, vlen
;
6843 dict
*dict
= dictCreate(&hashDictType
,NULL
);
6845 assert(o
->type
== REDIS_HASH
&& o
->encoding
!= REDIS_ENCODING_HT
);
6846 p
= zipmapRewind(zm
);
6847 while((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) != NULL
) {
6848 robj
*keyobj
, *valobj
;
6850 keyobj
= createStringObject((char*)key
,klen
);
6851 valobj
= createStringObject((char*)val
,vlen
);
6852 keyobj
= tryObjectEncoding(keyobj
);
6853 valobj
= tryObjectEncoding(valobj
);
6854 dictAdd(dict
,keyobj
,valobj
);
6856 o
->encoding
= REDIS_ENCODING_HT
;
6861 /* ========================= Non type-specific commands ==================== */
6863 static void flushdbCommand(redisClient
*c
) {
6864 server
.dirty
+= dictSize(c
->db
->dict
);
6865 touchWatchedKeysOnFlush(c
->db
->id
);
6866 dictEmpty(c
->db
->dict
);
6867 dictEmpty(c
->db
->expires
);
6868 addReply(c
,shared
.ok
);
6871 static void flushallCommand(redisClient
*c
) {
6872 touchWatchedKeysOnFlush(-1);
6873 server
.dirty
+= emptyDb();
6874 addReply(c
,shared
.ok
);
6875 if (server
.bgsavechildpid
!= -1) {
6876 kill(server
.bgsavechildpid
,SIGKILL
);
6877 rdbRemoveTempFile(server
.bgsavechildpid
);
6879 rdbSave(server
.dbfilename
);
6883 static redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
6884 redisSortOperation
*so
= zmalloc(sizeof(*so
));
6886 so
->pattern
= pattern
;
6890 /* Return the value associated to the key with a name obtained
6891 * substituting the first occurence of '*' in 'pattern' with 'subst'.
6892 * The returned object will always have its refcount increased by 1
6893 * when it is non-NULL. */
6894 static robj
*lookupKeyByPattern(redisDb
*db
, robj
*pattern
, robj
*subst
) {
6897 robj keyobj
, fieldobj
, *o
;
6898 int prefixlen
, sublen
, postfixlen
, fieldlen
;
6899 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
6903 char buf
[REDIS_SORTKEY_MAX
+1];
6904 } keyname
, fieldname
;
6906 /* If the pattern is "#" return the substitution object itself in order
6907 * to implement the "SORT ... GET #" feature. */
6908 spat
= pattern
->ptr
;
6909 if (spat
[0] == '#' && spat
[1] == '\0') {
6910 incrRefCount(subst
);
6914 /* The substitution object may be specially encoded. If so we create
6915 * a decoded object on the fly. Otherwise getDecodedObject will just
6916 * increment the ref count, that we'll decrement later. */
6917 subst
= getDecodedObject(subst
);
6920 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
6921 p
= strchr(spat
,'*');
6923 decrRefCount(subst
);
6927 /* Find out if we're dealing with a hash dereference. */
6928 if ((f
= strstr(p
+1, "->")) != NULL
) {
6929 fieldlen
= sdslen(spat
)-(f
-spat
);
6930 /* this also copies \0 character */
6931 memcpy(fieldname
.buf
,f
+2,fieldlen
-1);
6932 fieldname
.len
= fieldlen
-2;
6938 sublen
= sdslen(ssub
);
6939 postfixlen
= sdslen(spat
)-(prefixlen
+1)-fieldlen
;
6940 memcpy(keyname
.buf
,spat
,prefixlen
);
6941 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
6942 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
6943 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
6944 keyname
.len
= prefixlen
+sublen
+postfixlen
;
6945 decrRefCount(subst
);
6947 /* Lookup substituted key */
6948 initStaticStringObject(keyobj
,((char*)&keyname
)+(sizeof(long)*2));
6949 o
= lookupKeyRead(db
,&keyobj
);
6950 if (o
== NULL
) return NULL
;
6953 if (o
->type
!= REDIS_HASH
|| fieldname
.len
< 1) return NULL
;
6955 /* Retrieve value from hash by the field name. This operation
6956 * already increases the refcount of the returned object. */
6957 initStaticStringObject(fieldobj
,((char*)&fieldname
)+(sizeof(long)*2));
6958 o
= hashGet(o
, &fieldobj
);
6960 if (o
->type
!= REDIS_STRING
) return NULL
;
6962 /* Every object that this function returns needs to have its refcount
6963 * increased. sortCommand decreases it again. */
6970 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
6971 * the additional parameter is not standard but a BSD-specific we have to
6972 * pass sorting parameters via the global 'server' structure */
6973 static int sortCompare(const void *s1
, const void *s2
) {
6974 const redisSortObject
*so1
= s1
, *so2
= s2
;
6977 if (!server
.sort_alpha
) {
6978 /* Numeric sorting. Here it's trivial as we precomputed scores */
6979 if (so1
->u
.score
> so2
->u
.score
) {
6981 } else if (so1
->u
.score
< so2
->u
.score
) {
6987 /* Alphanumeric sorting */
6988 if (server
.sort_bypattern
) {
6989 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
6990 /* At least one compare object is NULL */
6991 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
6993 else if (so1
->u
.cmpobj
== NULL
)
6998 /* We have both the objects, use strcoll */
6999 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
7002 /* Compare elements directly. */
7003 cmp
= compareStringObjects(so1
->obj
,so2
->obj
);
7006 return server
.sort_desc
? -cmp
: cmp
;
7009 /* The SORT command is the most complex command in Redis. Warning: this code
7010 * is optimized for speed and a bit less for readability */
7011 static void sortCommand(redisClient
*c
) {
7014 int desc
= 0, alpha
= 0;
7015 int limit_start
= 0, limit_count
= -1, start
, end
;
7016 int j
, dontsort
= 0, vectorlen
;
7017 int getop
= 0; /* GET operation counter */
7018 robj
*sortval
, *sortby
= NULL
, *storekey
= NULL
;
7019 redisSortObject
*vector
; /* Resulting vector to sort */
7021 /* Lookup the key to sort. It must be of the right types */
7022 sortval
= lookupKeyRead(c
->db
,c
->argv
[1]);
7023 if (sortval
== NULL
) {
7024 addReply(c
,shared
.emptymultibulk
);
7027 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
&&
7028 sortval
->type
!= REDIS_ZSET
)
7030 addReply(c
,shared
.wrongtypeerr
);
7034 /* Create a list of operations to perform for every sorted element.
7035 * Operations can be GET/DEL/INCR/DECR */
7036 operations
= listCreate();
7037 listSetFreeMethod(operations
,zfree
);
7040 /* Now we need to protect sortval incrementing its count, in the future
7041 * SORT may have options able to overwrite/delete keys during the sorting
7042 * and the sorted key itself may get destroied */
7043 incrRefCount(sortval
);
7045 /* The SORT command has an SQL-alike syntax, parse it */
7046 while(j
< c
->argc
) {
7047 int leftargs
= c
->argc
-j
-1;
7048 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
7050 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
7052 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
7054 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
7055 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
7056 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
7058 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"store") && leftargs
>= 1) {
7059 storekey
= c
->argv
[j
+1];
7061 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
7062 sortby
= c
->argv
[j
+1];
7063 /* If the BY pattern does not contain '*', i.e. it is constant,
7064 * we don't need to sort nor to lookup the weight keys. */
7065 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
7067 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
7068 listAddNodeTail(operations
,createSortOperation(
7069 REDIS_SORT_GET
,c
->argv
[j
+1]));
7073 decrRefCount(sortval
);
7074 listRelease(operations
);
7075 addReply(c
,shared
.syntaxerr
);
7081 /* Load the sorting vector with all the objects to sort */
7082 switch(sortval
->type
) {
7083 case REDIS_LIST
: vectorlen
= listLength((list
*)sortval
->ptr
); break;
7084 case REDIS_SET
: vectorlen
= dictSize((dict
*)sortval
->ptr
); break;
7085 case REDIS_ZSET
: vectorlen
= dictSize(((zset
*)sortval
->ptr
)->dict
); break;
7086 default: vectorlen
= 0; redisPanic("Bad SORT type"); /* Avoid GCC warning */
7088 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
7091 if (sortval
->type
== REDIS_LIST
) {
7092 list
*list
= sortval
->ptr
;
7096 listRewind(list
,&li
);
7097 while((ln
= listNext(&li
))) {
7098 robj
*ele
= ln
->value
;
7099 vector
[j
].obj
= ele
;
7100 vector
[j
].u
.score
= 0;
7101 vector
[j
].u
.cmpobj
= NULL
;
7109 if (sortval
->type
== REDIS_SET
) {
7112 zset
*zs
= sortval
->ptr
;
7116 di
= dictGetIterator(set
);
7117 while((setele
= dictNext(di
)) != NULL
) {
7118 vector
[j
].obj
= dictGetEntryKey(setele
);
7119 vector
[j
].u
.score
= 0;
7120 vector
[j
].u
.cmpobj
= NULL
;
7123 dictReleaseIterator(di
);
7125 redisAssert(j
== vectorlen
);
7127 /* Now it's time to load the right scores in the sorting vector */
7128 if (dontsort
== 0) {
7129 for (j
= 0; j
< vectorlen
; j
++) {
7132 /* lookup value to sort by */
7133 byval
= lookupKeyByPattern(c
->db
,sortby
,vector
[j
].obj
);
7134 if (!byval
) continue;
7136 /* use object itself to sort by */
7137 byval
= vector
[j
].obj
;
7141 if (sortby
) vector
[j
].u
.cmpobj
= getDecodedObject(byval
);
7143 if (byval
->encoding
== REDIS_ENCODING_RAW
) {
7144 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
7145 } else if (byval
->encoding
== REDIS_ENCODING_INT
) {
7146 /* Don't need to decode the object if it's
7147 * integer-encoded (the only encoding supported) so
7148 * far. We can just cast it */
7149 vector
[j
].u
.score
= (long)byval
->ptr
;
7151 redisAssert(1 != 1);
7155 /* when the object was retrieved using lookupKeyByPattern,
7156 * its refcount needs to be decreased. */
7158 decrRefCount(byval
);
7163 /* We are ready to sort the vector... perform a bit of sanity check
7164 * on the LIMIT option too. We'll use a partial version of quicksort. */
7165 start
= (limit_start
< 0) ? 0 : limit_start
;
7166 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
7167 if (start
>= vectorlen
) {
7168 start
= vectorlen
-1;
7171 if (end
>= vectorlen
) end
= vectorlen
-1;
7173 if (dontsort
== 0) {
7174 server
.sort_desc
= desc
;
7175 server
.sort_alpha
= alpha
;
7176 server
.sort_bypattern
= sortby
? 1 : 0;
7177 if (sortby
&& (start
!= 0 || end
!= vectorlen
-1))
7178 pqsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
, start
,end
);
7180 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
7183 /* Send command output to the output buffer, performing the specified
7184 * GET/DEL/INCR/DECR operations if any. */
7185 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
7186 if (storekey
== NULL
) {
7187 /* STORE option not specified, sent the sorting result to client */
7188 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
7189 for (j
= start
; j
<= end
; j
++) {
7193 if (!getop
) addReplyBulk(c
,vector
[j
].obj
);
7194 listRewind(operations
,&li
);
7195 while((ln
= listNext(&li
))) {
7196 redisSortOperation
*sop
= ln
->value
;
7197 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
7200 if (sop
->type
== REDIS_SORT_GET
) {
7202 addReply(c
,shared
.nullbulk
);
7204 addReplyBulk(c
,val
);
7208 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
7213 robj
*listObject
= createListObject();
7214 list
*listPtr
= (list
*) listObject
->ptr
;
7216 /* STORE option specified, set the sorting result as a List object */
7217 for (j
= start
; j
<= end
; j
++) {
7222 listAddNodeTail(listPtr
,vector
[j
].obj
);
7223 incrRefCount(vector
[j
].obj
);
7225 listRewind(operations
,&li
);
7226 while((ln
= listNext(&li
))) {
7227 redisSortOperation
*sop
= ln
->value
;
7228 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
7231 if (sop
->type
== REDIS_SORT_GET
) {
7233 listAddNodeTail(listPtr
,createStringObject("",0));
7235 /* We should do a incrRefCount on val because it is
7236 * added to the list, but also a decrRefCount because
7237 * it is returned by lookupKeyByPattern. This results
7238 * in doing nothing at all. */
7239 listAddNodeTail(listPtr
,val
);
7242 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
7246 if (dictReplace(c
->db
->dict
,storekey
,listObject
)) {
7247 incrRefCount(storekey
);
7249 /* Note: we add 1 because the DB is dirty anyway since even if the
7250 * SORT result is empty a new key is set and maybe the old content
7252 server
.dirty
+= 1+outputlen
;
7253 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",outputlen
));
7257 decrRefCount(sortval
);
7258 listRelease(operations
);
7259 for (j
= 0; j
< vectorlen
; j
++) {
7260 if (alpha
&& vector
[j
].u
.cmpobj
)
7261 decrRefCount(vector
[j
].u
.cmpobj
);
7266 /* Convert an amount of bytes into a human readable string in the form
7267 * of 100B, 2G, 100M, 4K, and so forth. */
7268 static void bytesToHuman(char *s
, unsigned long long n
) {
7273 sprintf(s
,"%lluB",n
);
7275 } else if (n
< (1024*1024)) {
7276 d
= (double)n
/(1024);
7277 sprintf(s
,"%.2fK",d
);
7278 } else if (n
< (1024LL*1024*1024)) {
7279 d
= (double)n
/(1024*1024);
7280 sprintf(s
,"%.2fM",d
);
7281 } else if (n
< (1024LL*1024*1024*1024)) {
7282 d
= (double)n
/(1024LL*1024*1024);
7283 sprintf(s
,"%.2fG",d
);
7287 /* Create the string returned by the INFO command. This is decoupled
7288 * by the INFO command itself as we need to report the same information
7289 * on memory corruption problems. */
7290 static sds
genRedisInfoString(void) {
7292 time_t uptime
= time(NULL
)-server
.stat_starttime
;
7296 bytesToHuman(hmem
,zmalloc_used_memory());
7297 info
= sdscatprintf(sdsempty(),
7298 "redis_version:%s\r\n"
7299 "redis_git_sha1:%s\r\n"
7300 "redis_git_dirty:%d\r\n"
7302 "multiplexing_api:%s\r\n"
7303 "process_id:%ld\r\n"
7304 "uptime_in_seconds:%ld\r\n"
7305 "uptime_in_days:%ld\r\n"
7306 "connected_clients:%d\r\n"
7307 "connected_slaves:%d\r\n"
7308 "blocked_clients:%d\r\n"
7309 "used_memory:%zu\r\n"
7310 "used_memory_human:%s\r\n"
7311 "changes_since_last_save:%lld\r\n"
7312 "bgsave_in_progress:%d\r\n"
7313 "last_save_time:%ld\r\n"
7314 "bgrewriteaof_in_progress:%d\r\n"
7315 "total_connections_received:%lld\r\n"
7316 "total_commands_processed:%lld\r\n"
7317 "expired_keys:%lld\r\n"
7318 "hash_max_zipmap_entries:%zu\r\n"
7319 "hash_max_zipmap_value:%zu\r\n"
7320 "pubsub_channels:%ld\r\n"
7321 "pubsub_patterns:%u\r\n"
7326 strtol(REDIS_GIT_DIRTY
,NULL
,10) > 0,
7327 (sizeof(long) == 8) ? "64" : "32",
7332 listLength(server
.clients
)-listLength(server
.slaves
),
7333 listLength(server
.slaves
),
7334 server
.blpop_blocked_clients
,
7335 zmalloc_used_memory(),
7338 server
.bgsavechildpid
!= -1,
7340 server
.bgrewritechildpid
!= -1,
7341 server
.stat_numconnections
,
7342 server
.stat_numcommands
,
7343 server
.stat_expiredkeys
,
7344 server
.hash_max_zipmap_entries
,
7345 server
.hash_max_zipmap_value
,
7346 dictSize(server
.pubsub_channels
),
7347 listLength(server
.pubsub_patterns
),
7348 server
.vm_enabled
!= 0,
7349 server
.masterhost
== NULL
? "master" : "slave"
7351 if (server
.masterhost
) {
7352 info
= sdscatprintf(info
,
7353 "master_host:%s\r\n"
7354 "master_port:%d\r\n"
7355 "master_link_status:%s\r\n"
7356 "master_last_io_seconds_ago:%d\r\n"
7359 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
7361 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1
7364 if (server
.vm_enabled
) {
7366 info
= sdscatprintf(info
,
7367 "vm_conf_max_memory:%llu\r\n"
7368 "vm_conf_page_size:%llu\r\n"
7369 "vm_conf_pages:%llu\r\n"
7370 "vm_stats_used_pages:%llu\r\n"
7371 "vm_stats_swapped_objects:%llu\r\n"
7372 "vm_stats_swappin_count:%llu\r\n"
7373 "vm_stats_swappout_count:%llu\r\n"
7374 "vm_stats_io_newjobs_len:%lu\r\n"
7375 "vm_stats_io_processing_len:%lu\r\n"
7376 "vm_stats_io_processed_len:%lu\r\n"
7377 "vm_stats_io_active_threads:%lu\r\n"
7378 "vm_stats_blocked_clients:%lu\r\n"
7379 ,(unsigned long long) server
.vm_max_memory
,
7380 (unsigned long long) server
.vm_page_size
,
7381 (unsigned long long) server
.vm_pages
,
7382 (unsigned long long) server
.vm_stats_used_pages
,
7383 (unsigned long long) server
.vm_stats_swapped_objects
,
7384 (unsigned long long) server
.vm_stats_swapins
,
7385 (unsigned long long) server
.vm_stats_swapouts
,
7386 (unsigned long) listLength(server
.io_newjobs
),
7387 (unsigned long) listLength(server
.io_processing
),
7388 (unsigned long) listLength(server
.io_processed
),
7389 (unsigned long) server
.io_active_threads
,
7390 (unsigned long) server
.vm_blocked_clients
7394 for (j
= 0; j
< server
.dbnum
; j
++) {
7395 long long keys
, vkeys
;
7397 keys
= dictSize(server
.db
[j
].dict
);
7398 vkeys
= dictSize(server
.db
[j
].expires
);
7399 if (keys
|| vkeys
) {
7400 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
7407 static void infoCommand(redisClient
*c
) {
7408 sds info
= genRedisInfoString();
7409 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
7410 (unsigned long)sdslen(info
)));
7411 addReplySds(c
,info
);
7412 addReply(c
,shared
.crlf
);
7415 static void monitorCommand(redisClient
*c
) {
7416 /* ignore MONITOR if aleady slave or in monitor mode */
7417 if (c
->flags
& REDIS_SLAVE
) return;
7419 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
7421 listAddNodeTail(server
.monitors
,c
);
7422 addReply(c
,shared
.ok
);
7425 /* ================================= Expire ================================= */
7426 static int removeExpire(redisDb
*db
, robj
*key
) {
7427 if (dictDelete(db
->expires
,key
) == DICT_OK
) {
7434 static int setExpire(redisDb
*db
, robj
*key
, time_t when
) {
7435 if (dictAdd(db
->expires
,key
,(void*)when
) == DICT_ERR
) {
7443 /* Return the expire time of the specified key, or -1 if no expire
7444 * is associated with this key (i.e. the key is non volatile) */
7445 static time_t getExpire(redisDb
*db
, robj
*key
) {
7448 /* No expire? return ASAP */
7449 if (dictSize(db
->expires
) == 0 ||
7450 (de
= dictFind(db
->expires
,key
)) == NULL
) return -1;
7452 return (time_t) dictGetEntryVal(de
);
7455 static int expireIfNeeded(redisDb
*db
, robj
*key
) {
7459 /* No expire? return ASAP */
7460 if (dictSize(db
->expires
) == 0 ||
7461 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
7463 /* Lookup the expire */
7464 when
= (time_t) dictGetEntryVal(de
);
7465 if (time(NULL
) <= when
) return 0;
7467 /* Delete the key */
7468 dictDelete(db
->expires
,key
);
7469 server
.stat_expiredkeys
++;
7470 return dictDelete(db
->dict
,key
) == DICT_OK
;
7473 static int deleteIfVolatile(redisDb
*db
, robj
*key
) {
7476 /* No expire? return ASAP */
7477 if (dictSize(db
->expires
) == 0 ||
7478 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
7480 /* Delete the key */
7482 server
.stat_expiredkeys
++;
7483 dictDelete(db
->expires
,key
);
7484 return dictDelete(db
->dict
,key
) == DICT_OK
;
7487 static void expireGenericCommand(redisClient
*c
, robj
*key
, robj
*param
, long offset
) {
7491 if (getLongFromObjectOrReply(c
, param
, &seconds
, NULL
) != REDIS_OK
) return;
7495 de
= dictFind(c
->db
->dict
,key
);
7497 addReply(c
,shared
.czero
);
7501 if (deleteKey(c
->db
,key
)) server
.dirty
++;
7502 addReply(c
, shared
.cone
);
7505 time_t when
= time(NULL
)+seconds
;
7506 if (setExpire(c
->db
,key
,when
)) {
7507 addReply(c
,shared
.cone
);
7510 addReply(c
,shared
.czero
);
7516 static void expireCommand(redisClient
*c
) {
7517 expireGenericCommand(c
,c
->argv
[1],c
->argv
[2],0);
7520 static void expireatCommand(redisClient
*c
) {
7521 expireGenericCommand(c
,c
->argv
[1],c
->argv
[2],time(NULL
));
7524 static void ttlCommand(redisClient
*c
) {
7528 expire
= getExpire(c
->db
,c
->argv
[1]);
7530 ttl
= (int) (expire
-time(NULL
));
7531 if (ttl
< 0) ttl
= -1;
7533 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",ttl
));
7536 /* ================================ MULTI/EXEC ============================== */
7538 /* Client state initialization for MULTI/EXEC */
7539 static void initClientMultiState(redisClient
*c
) {
7540 c
->mstate
.commands
= NULL
;
7541 c
->mstate
.count
= 0;
7544 /* Release all the resources associated with MULTI/EXEC state */
7545 static void freeClientMultiState(redisClient
*c
) {
7548 for (j
= 0; j
< c
->mstate
.count
; j
++) {
7550 multiCmd
*mc
= c
->mstate
.commands
+j
;
7552 for (i
= 0; i
< mc
->argc
; i
++)
7553 decrRefCount(mc
->argv
[i
]);
7556 zfree(c
->mstate
.commands
);
7559 /* Add a new command into the MULTI commands queue */
7560 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
) {
7564 c
->mstate
.commands
= zrealloc(c
->mstate
.commands
,
7565 sizeof(multiCmd
)*(c
->mstate
.count
+1));
7566 mc
= c
->mstate
.commands
+c
->mstate
.count
;
7569 mc
->argv
= zmalloc(sizeof(robj
*)*c
->argc
);
7570 memcpy(mc
->argv
,c
->argv
,sizeof(robj
*)*c
->argc
);
7571 for (j
= 0; j
< c
->argc
; j
++)
7572 incrRefCount(mc
->argv
[j
]);
7576 static void multiCommand(redisClient
*c
) {
7577 if (c
->flags
& REDIS_MULTI
) {
7578 addReplySds(c
,sdsnew("-ERR MULTI calls can not be nested\r\n"));
7581 c
->flags
|= REDIS_MULTI
;
7582 addReply(c
,shared
.ok
);
7585 static void discardCommand(redisClient
*c
) {
7586 if (!(c
->flags
& REDIS_MULTI
)) {
7587 addReplySds(c
,sdsnew("-ERR DISCARD without MULTI\r\n"));
7591 freeClientMultiState(c
);
7592 initClientMultiState(c
);
7593 c
->flags
&= (~REDIS_MULTI
);
7594 addReply(c
,shared
.ok
);
7597 /* Send a MULTI command to all the slaves and AOF file. Check the execCommand
7598 * implememntation for more information. */
7599 static void execCommandReplicateMulti(redisClient
*c
) {
7600 struct redisCommand
*cmd
;
7601 robj
*multistring
= createStringObject("MULTI",5);
7603 cmd
= lookupCommand("multi");
7604 if (server
.appendonly
)
7605 feedAppendOnlyFile(cmd
,c
->db
->id
,&multistring
,1);
7606 if (listLength(server
.slaves
))
7607 replicationFeedSlaves(server
.slaves
,c
->db
->id
,&multistring
,1);
7608 decrRefCount(multistring
);
7611 static void execCommand(redisClient
*c
) {
7616 if (!(c
->flags
& REDIS_MULTI
)) {
7617 addReplySds(c
,sdsnew("-ERR EXEC without MULTI\r\n"));
7621 /* Check if we need to abort the EXEC if some WATCHed key was touched.
7622 * A failed EXEC will return a multi bulk nil object. */
7623 if (c
->flags
& REDIS_DIRTY_CAS
) {
7624 freeClientMultiState(c
);
7625 initClientMultiState(c
);
7626 c
->flags
&= ~(REDIS_MULTI
|REDIS_DIRTY_CAS
);
7628 addReply(c
,shared
.nullmultibulk
);
7632 /* Replicate a MULTI request now that we are sure the block is executed.
7633 * This way we'll deliver the MULTI/..../EXEC block as a whole and
7634 * both the AOF and the replication link will have the same consistency
7635 * and atomicity guarantees. */
7636 execCommandReplicateMulti(c
);
7638 /* Exec all the queued commands */
7639 unwatchAllKeys(c
); /* Unwatch ASAP otherwise we'll waste CPU cycles */
7640 orig_argv
= c
->argv
;
7641 orig_argc
= c
->argc
;
7642 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->mstate
.count
));
7643 for (j
= 0; j
< c
->mstate
.count
; j
++) {
7644 c
->argc
= c
->mstate
.commands
[j
].argc
;
7645 c
->argv
= c
->mstate
.commands
[j
].argv
;
7646 call(c
,c
->mstate
.commands
[j
].cmd
);
7648 c
->argv
= orig_argv
;
7649 c
->argc
= orig_argc
;
7650 freeClientMultiState(c
);
7651 initClientMultiState(c
);
7652 c
->flags
&= ~(REDIS_MULTI
|REDIS_DIRTY_CAS
);
7653 /* Make sure the EXEC command is always replicated / AOF, since we
7654 * always send the MULTI command (we can't know beforehand if the
7655 * next operations will contain at least a modification to the DB). */
7659 /* =========================== Blocking Operations ========================= */
7661 /* Currently Redis blocking operations support is limited to list POP ops,
7662 * so the current implementation is not fully generic, but it is also not
7663 * completely specific so it will not require a rewrite to support new
7664 * kind of blocking operations in the future.
7666 * Still it's important to note that list blocking operations can be already
7667 * used as a notification mechanism in order to implement other blocking
7668 * operations at application level, so there must be a very strong evidence
7669 * of usefulness and generality before new blocking operations are implemented.
7671 * This is how the current blocking POP works, we use BLPOP as example:
7672 * - If the user calls BLPOP and the key exists and contains a non empty list
7673 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
7674 * if there is not to block.
7675 * - If instead BLPOP is called and the key does not exists or the list is
7676 * empty we need to block. In order to do so we remove the notification for
7677 * new data to read in the client socket (so that we'll not serve new
7678 * requests if the blocking request is not served). Also we put the client
7679 * in a dictionary (db->blocking_keys) mapping keys to a list of clients
7680 * blocking for this keys.
7681 * - If a PUSH operation against a key with blocked clients waiting is
7682 * performed, we serve the first in the list: basically instead to push
7683 * the new element inside the list we return it to the (first / oldest)
7684 * blocking client, unblock the client, and remove it form the list.
7686 * The above comment and the source code should be enough in order to understand
7687 * the implementation and modify / fix it later.
7690 /* Set a client in blocking mode for the specified key, with the specified
7692 static void blockForKeys(redisClient
*c
, robj
**keys
, int numkeys
, time_t timeout
) {
7697 c
->blocking_keys
= zmalloc(sizeof(robj
*)*numkeys
);
7698 c
->blocking_keys_num
= numkeys
;
7699 c
->blockingto
= timeout
;
7700 for (j
= 0; j
< numkeys
; j
++) {
7701 /* Add the key in the client structure, to map clients -> keys */
7702 c
->blocking_keys
[j
] = keys
[j
];
7703 incrRefCount(keys
[j
]);
7705 /* And in the other "side", to map keys -> clients */
7706 de
= dictFind(c
->db
->blocking_keys
,keys
[j
]);
7710 /* For every key we take a list of clients blocked for it */
7712 retval
= dictAdd(c
->db
->blocking_keys
,keys
[j
],l
);
7713 incrRefCount(keys
[j
]);
7714 assert(retval
== DICT_OK
);
7716 l
= dictGetEntryVal(de
);
7718 listAddNodeTail(l
,c
);
7720 /* Mark the client as a blocked client */
7721 c
->flags
|= REDIS_BLOCKED
;
7722 server
.blpop_blocked_clients
++;
7725 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
7726 static void unblockClientWaitingData(redisClient
*c
) {
7731 assert(c
->blocking_keys
!= NULL
);
7732 /* The client may wait for multiple keys, so unblock it for every key. */
7733 for (j
= 0; j
< c
->blocking_keys_num
; j
++) {
7734 /* Remove this client from the list of clients waiting for this key. */
7735 de
= dictFind(c
->db
->blocking_keys
,c
->blocking_keys
[j
]);
7737 l
= dictGetEntryVal(de
);
7738 listDelNode(l
,listSearchKey(l
,c
));
7739 /* If the list is empty we need to remove it to avoid wasting memory */
7740 if (listLength(l
) == 0)
7741 dictDelete(c
->db
->blocking_keys
,c
->blocking_keys
[j
]);
7742 decrRefCount(c
->blocking_keys
[j
]);
7744 /* Cleanup the client structure */
7745 zfree(c
->blocking_keys
);
7746 c
->blocking_keys
= NULL
;
7747 c
->flags
&= (~REDIS_BLOCKED
);
7748 server
.blpop_blocked_clients
--;
7749 /* We want to process data if there is some command waiting
7750 * in the input buffer. Note that this is safe even if
7751 * unblockClientWaitingData() gets called from freeClient() because
7752 * freeClient() will be smart enough to call this function
7753 * *after* c->querybuf was set to NULL. */
7754 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0) processInputBuffer(c
);
7757 /* This should be called from any function PUSHing into lists.
7758 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
7759 * 'ele' is the element pushed.
7761 * If the function returns 0 there was no client waiting for a list push
7764 * If the function returns 1 there was a client waiting for a list push
7765 * against this key, the element was passed to this client thus it's not
7766 * needed to actually add it to the list and the caller should return asap. */
7767 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
) {
7768 struct dictEntry
*de
;
7769 redisClient
*receiver
;
7773 de
= dictFind(c
->db
->blocking_keys
,key
);
7774 if (de
== NULL
) return 0;
7775 l
= dictGetEntryVal(de
);
7778 receiver
= ln
->value
;
7780 addReplySds(receiver
,sdsnew("*2\r\n"));
7781 addReplyBulk(receiver
,key
);
7782 addReplyBulk(receiver
,ele
);
7783 unblockClientWaitingData(receiver
);
7787 /* Blocking RPOP/LPOP */
7788 static void blockingPopGenericCommand(redisClient
*c
, int where
) {
7793 for (j
= 1; j
< c
->argc
-1; j
++) {
7794 o
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
7796 if (o
->type
!= REDIS_LIST
) {
7797 addReply(c
,shared
.wrongtypeerr
);
7800 list
*list
= o
->ptr
;
7801 if (listLength(list
) != 0) {
7802 /* If the list contains elements fall back to the usual
7803 * non-blocking POP operation */
7804 robj
*argv
[2], **orig_argv
;
7807 /* We need to alter the command arguments before to call
7808 * popGenericCommand() as the command takes a single key. */
7809 orig_argv
= c
->argv
;
7810 orig_argc
= c
->argc
;
7811 argv
[1] = c
->argv
[j
];
7815 /* Also the return value is different, we need to output
7816 * the multi bulk reply header and the key name. The
7817 * "real" command will add the last element (the value)
7818 * for us. If this souds like an hack to you it's just
7819 * because it is... */
7820 addReplySds(c
,sdsnew("*2\r\n"));
7821 addReplyBulk(c
,argv
[1]);
7822 popGenericCommand(c
,where
);
7824 /* Fix the client structure with the original stuff */
7825 c
->argv
= orig_argv
;
7826 c
->argc
= orig_argc
;
7832 /* If the list is empty or the key does not exists we must block */
7833 timeout
= strtol(c
->argv
[c
->argc
-1]->ptr
,NULL
,10);
7834 if (timeout
> 0) timeout
+= time(NULL
);
7835 blockForKeys(c
,c
->argv
+1,c
->argc
-2,timeout
);
7838 static void blpopCommand(redisClient
*c
) {
7839 blockingPopGenericCommand(c
,REDIS_HEAD
);
7842 static void brpopCommand(redisClient
*c
) {
7843 blockingPopGenericCommand(c
,REDIS_TAIL
);
7846 /* =============================== Replication ============================= */
7848 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) {
7849 ssize_t nwritten
, ret
= size
;
7850 time_t start
= time(NULL
);
7854 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
7855 nwritten
= write(fd
,ptr
,size
);
7856 if (nwritten
== -1) return -1;
7860 if ((time(NULL
)-start
) > timeout
) {
7868 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) {
7869 ssize_t nread
, totread
= 0;
7870 time_t start
= time(NULL
);
7874 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
7875 nread
= read(fd
,ptr
,size
);
7876 if (nread
== -1) return -1;
7881 if ((time(NULL
)-start
) > timeout
) {
7889 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
7896 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
7899 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
7910 static void syncCommand(redisClient
*c
) {
7911 /* ignore SYNC if aleady slave or in monitor mode */
7912 if (c
->flags
& REDIS_SLAVE
) return;
7914 /* SYNC can't be issued when the server has pending data to send to
7915 * the client about already issued commands. We need a fresh reply
7916 * buffer registering the differences between the BGSAVE and the current
7917 * dataset, so that we can copy to other slaves if needed. */
7918 if (listLength(c
->reply
) != 0) {
7919 addReplySds(c
,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
7923 redisLog(REDIS_NOTICE
,"Slave ask for synchronization");
7924 /* Here we need to check if there is a background saving operation
7925 * in progress, or if it is required to start one */
7926 if (server
.bgsavechildpid
!= -1) {
7927 /* Ok a background save is in progress. Let's check if it is a good
7928 * one for replication, i.e. if there is another slave that is
7929 * registering differences since the server forked to save */
7934 listRewind(server
.slaves
,&li
);
7935 while((ln
= listNext(&li
))) {
7937 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) break;
7940 /* Perfect, the server is already registering differences for
7941 * another slave. Set the right state, and copy the buffer. */
7942 listRelease(c
->reply
);
7943 c
->reply
= listDup(slave
->reply
);
7944 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
7945 redisLog(REDIS_NOTICE
,"Waiting for end of BGSAVE for SYNC");
7947 /* No way, we need to wait for the next BGSAVE in order to
7948 * register differences */
7949 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
7950 redisLog(REDIS_NOTICE
,"Waiting for next BGSAVE for SYNC");
7953 /* Ok we don't have a BGSAVE in progress, let's start one */
7954 redisLog(REDIS_NOTICE
,"Starting BGSAVE for SYNC");
7955 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
7956 redisLog(REDIS_NOTICE
,"Replication failed, can't BGSAVE");
7957 addReplySds(c
,sdsnew("-ERR Unalbe to perform background save\r\n"));
7960 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
7963 c
->flags
|= REDIS_SLAVE
;
7965 listAddNodeTail(server
.slaves
,c
);
7969 static void sendBulkToSlave(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
7970 redisClient
*slave
= privdata
;
7972 REDIS_NOTUSED(mask
);
7973 char buf
[REDIS_IOBUF_LEN
];
7974 ssize_t nwritten
, buflen
;
7976 if (slave
->repldboff
== 0) {
7977 /* Write the bulk write count before to transfer the DB. In theory here
7978 * we don't know how much room there is in the output buffer of the
7979 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
7980 * operations) will never be smaller than the few bytes we need. */
7983 bulkcount
= sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
7985 if (write(fd
,bulkcount
,sdslen(bulkcount
)) != (signed)sdslen(bulkcount
))
7993 lseek(slave
->repldbfd
,slave
->repldboff
,SEEK_SET
);
7994 buflen
= read(slave
->repldbfd
,buf
,REDIS_IOBUF_LEN
);
7996 redisLog(REDIS_WARNING
,"Read error sending DB to slave: %s",
7997 (buflen
== 0) ? "premature EOF" : strerror(errno
));
8001 if ((nwritten
= write(fd
,buf
,buflen
)) == -1) {
8002 redisLog(REDIS_VERBOSE
,"Write error sending DB to slave: %s",
8007 slave
->repldboff
+= nwritten
;
8008 if (slave
->repldboff
== slave
->repldbsize
) {
8009 close(slave
->repldbfd
);
8010 slave
->repldbfd
= -1;
8011 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
8012 slave
->replstate
= REDIS_REPL_ONLINE
;
8013 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
,
8014 sendReplyToClient
, slave
) == AE_ERR
) {
8018 addReplySds(slave
,sdsempty());
8019 redisLog(REDIS_NOTICE
,"Synchronization with slave succeeded");
8023 /* This function is called at the end of every backgrond saving.
8024 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
8025 * otherwise REDIS_ERR is passed to the function.
8027 * The goal of this function is to handle slaves waiting for a successful
8028 * background saving in order to perform non-blocking synchronization. */
8029 static void updateSlavesWaitingBgsave(int bgsaveerr
) {
8031 int startbgsave
= 0;
8034 listRewind(server
.slaves
,&li
);
8035 while((ln
= listNext(&li
))) {
8036 redisClient
*slave
= ln
->value
;
8038 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) {
8040 slave
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
8041 } else if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) {
8042 struct redis_stat buf
;
8044 if (bgsaveerr
!= REDIS_OK
) {
8046 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE child returned an error");
8049 if ((slave
->repldbfd
= open(server
.dbfilename
,O_RDONLY
)) == -1 ||
8050 redis_fstat(slave
->repldbfd
,&buf
) == -1) {
8052 redisLog(REDIS_WARNING
,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno
));
8055 slave
->repldboff
= 0;
8056 slave
->repldbsize
= buf
.st_size
;
8057 slave
->replstate
= REDIS_REPL_SEND_BULK
;
8058 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
8059 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
, sendBulkToSlave
, slave
) == AE_ERR
) {
8066 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
8069 listRewind(server
.slaves
,&li
);
8070 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE failed");
8071 while((ln
= listNext(&li
))) {
8072 redisClient
*slave
= ln
->value
;
8074 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
)
8081 static int syncWithMaster(void) {
8082 char buf
[1024], tmpfile
[256], authcmd
[1024];
8084 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
8085 int dfd
, maxtries
= 5;
8088 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
8093 /* AUTH with the master if required. */
8094 if(server
.masterauth
) {
8095 snprintf(authcmd
, 1024, "AUTH %s\r\n", server
.masterauth
);
8096 if (syncWrite(fd
, authcmd
, strlen(server
.masterauth
)+7, 5) == -1) {
8098 redisLog(REDIS_WARNING
,"Unable to AUTH to MASTER: %s",
8102 /* Read the AUTH result. */
8103 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
8105 redisLog(REDIS_WARNING
,"I/O error reading auth result from MASTER: %s",
8109 if (buf
[0] != '+') {
8111 redisLog(REDIS_WARNING
,"Cannot AUTH to MASTER, is the masterauth password correct?");
8116 /* Issue the SYNC command */
8117 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
8119 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
8123 /* Read the bulk write count */
8124 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
8126 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
8130 if (buf
[0] != '$') {
8132 redisLog(REDIS_WARNING
,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
8135 dumpsize
= strtol(buf
+1,NULL
,10);
8136 redisLog(REDIS_NOTICE
,"Receiving %ld bytes data dump from MASTER",dumpsize
);
8137 /* Read the bulk write data on a temp file */
8139 snprintf(tmpfile
,256,
8140 "temp-%d.%ld.rdb",(int)time(NULL
),(long int)getpid());
8141 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
|O_EXCL
,0644);
8142 if (dfd
!= -1) break;
8147 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
8151 int nread
, nwritten
;
8153 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
8155 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
8161 nwritten
= write(dfd
,buf
,nread
);
8162 if (nwritten
== -1) {
8163 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
8171 if (rename(tmpfile
,server
.dbfilename
) == -1) {
8172 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
8178 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
8179 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
8183 server
.master
= createClient(fd
);
8184 server
.master
->flags
|= REDIS_MASTER
;
8185 server
.master
->authenticated
= 1;
8186 server
.replstate
= REDIS_REPL_CONNECTED
;
8190 static void slaveofCommand(redisClient
*c
) {
8191 if (!strcasecmp(c
->argv
[1]->ptr
,"no") &&
8192 !strcasecmp(c
->argv
[2]->ptr
,"one")) {
8193 if (server
.masterhost
) {
8194 sdsfree(server
.masterhost
);
8195 server
.masterhost
= NULL
;
8196 if (server
.master
) freeClient(server
.master
);
8197 server
.replstate
= REDIS_REPL_NONE
;
8198 redisLog(REDIS_NOTICE
,"MASTER MODE enabled (user request)");
8201 sdsfree(server
.masterhost
);
8202 server
.masterhost
= sdsdup(c
->argv
[1]->ptr
);
8203 server
.masterport
= atoi(c
->argv
[2]->ptr
);
8204 if (server
.master
) freeClient(server
.master
);
8205 server
.replstate
= REDIS_REPL_CONNECT
;
8206 redisLog(REDIS_NOTICE
,"SLAVE OF %s:%d enabled (user request)",
8207 server
.masterhost
, server
.masterport
);
8209 addReply(c
,shared
.ok
);
8212 /* ============================ Maxmemory directive ======================== */
8214 /* Try to free one object form the pre-allocated objects free list.
8215 * This is useful under low mem conditions as by default we take 1 million
8216 * free objects allocated. On success REDIS_OK is returned, otherwise
8218 static int tryFreeOneObjectFromFreelist(void) {
8221 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
8222 if (listLength(server
.objfreelist
)) {
8223 listNode
*head
= listFirst(server
.objfreelist
);
8224 o
= listNodeValue(head
);
8225 listDelNode(server
.objfreelist
,head
);
8226 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
8230 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
8235 /* This function gets called when 'maxmemory' is set on the config file to limit
8236 * the max memory used by the server, and we are out of memory.
8237 * This function will try to, in order:
8239 * - Free objects from the free list
8240 * - Try to remove keys with an EXPIRE set
8242 * It is not possible to free enough memory to reach used-memory < maxmemory
8243 * the server will start refusing commands that will enlarge even more the
8246 static void freeMemoryIfNeeded(void) {
8247 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
8248 int j
, k
, freed
= 0;
8250 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
8251 for (j
= 0; j
< server
.dbnum
; j
++) {
8253 robj
*minkey
= NULL
;
8254 struct dictEntry
*de
;
8256 if (dictSize(server
.db
[j
].expires
)) {
8258 /* From a sample of three keys drop the one nearest to
8259 * the natural expire */
8260 for (k
= 0; k
< 3; k
++) {
8263 de
= dictGetRandomKey(server
.db
[j
].expires
);
8264 t
= (time_t) dictGetEntryVal(de
);
8265 if (minttl
== -1 || t
< minttl
) {
8266 minkey
= dictGetEntryKey(de
);
8270 deleteKey(server
.db
+j
,minkey
);
8273 if (!freed
) return; /* nothing to free... */
8277 /* ============================== Append Only file ========================== */
8279 /* Called when the user switches from "appendonly yes" to "appendonly no"
8280 * at runtime using the CONFIG command. */
8281 static void stopAppendOnly(void) {
8282 flushAppendOnlyFile();
8283 aof_fsync(server
.appendfd
);
8284 close(server
.appendfd
);
8286 server
.appendfd
= -1;
8287 server
.appendseldb
= -1;
8288 server
.appendonly
= 0;
8289 /* rewrite operation in progress? kill it, wait child exit */
8290 if (server
.bgsavechildpid
!= -1) {
8293 if (kill(server
.bgsavechildpid
,SIGKILL
) != -1)
8294 wait3(&statloc
,0,NULL
);
8295 /* reset the buffer accumulating changes while the child saves */
8296 sdsfree(server
.bgrewritebuf
);
8297 server
.bgrewritebuf
= sdsempty();
8298 server
.bgsavechildpid
= -1;
8302 /* Called when the user switches from "appendonly no" to "appendonly yes"
8303 * at runtime using the CONFIG command. */
8304 static int startAppendOnly(void) {
8305 server
.appendonly
= 1;
8306 server
.lastfsync
= time(NULL
);
8307 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
8308 if (server
.appendfd
== -1) {
8309 redisLog(REDIS_WARNING
,"Used tried to switch on AOF via CONFIG, but I can't open the AOF file: %s",strerror(errno
));
8312 if (rewriteAppendOnlyFileBackground() == REDIS_ERR
) {
8313 server
.appendonly
= 0;
8314 close(server
.appendfd
);
8315 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
));
8321 /* Write the append only file buffer on disk.
8323 * Since we are required to write the AOF before replying to the client,
8324 * and the only way the client socket can get a write is entering when the
8325 * the event loop, we accumulate all the AOF writes in a memory
8326 * buffer and write it on disk using this function just before entering
8327 * the event loop again. */
8328 static void flushAppendOnlyFile(void) {
8332 if (sdslen(server
.aofbuf
) == 0) return;
8334 /* We want to perform a single write. This should be guaranteed atomic
8335 * at least if the filesystem we are writing is a real physical one.
8336 * While this will save us against the server being killed I don't think
8337 * there is much to do about the whole server stopping for power problems
8339 nwritten
= write(server
.appendfd
,server
.aofbuf
,sdslen(server
.aofbuf
));
8340 if (nwritten
!= (signed)sdslen(server
.aofbuf
)) {
8341 /* Ooops, we are in troubles. The best thing to do for now is
8342 * aborting instead of giving the illusion that everything is
8343 * working as expected. */
8344 if (nwritten
== -1) {
8345 redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
));
8347 redisLog(REDIS_WARNING
,"Exiting on short write while writing to the append-only file: %s",strerror(errno
));
8351 sdsfree(server
.aofbuf
);
8352 server
.aofbuf
= sdsempty();
8354 /* Don't Fsync if no-appendfsync-on-rewrite is set to yes and we have
8355 * childs performing heavy I/O on disk. */
8356 if (server
.no_appendfsync_on_rewrite
&&
8357 (server
.bgrewritechildpid
!= -1 || server
.bgsavechildpid
!= -1))
8359 /* Fsync if needed */
8361 if (server
.appendfsync
== APPENDFSYNC_ALWAYS
||
8362 (server
.appendfsync
== APPENDFSYNC_EVERYSEC
&&
8363 now
-server
.lastfsync
> 1))
8365 /* aof_fsync is defined as fdatasync() for Linux in order to avoid
8366 * flushing metadata. */
8367 aof_fsync(server
.appendfd
); /* Let's try to get this data on the disk */
8368 server
.lastfsync
= now
;
8372 static sds
catAppendOnlyGenericCommand(sds buf
, int argc
, robj
**argv
) {
8374 buf
= sdscatprintf(buf
,"*%d\r\n",argc
);
8375 for (j
= 0; j
< argc
; j
++) {
8376 robj
*o
= getDecodedObject(argv
[j
]);
8377 buf
= sdscatprintf(buf
,"$%lu\r\n",(unsigned long)sdslen(o
->ptr
));
8378 buf
= sdscatlen(buf
,o
->ptr
,sdslen(o
->ptr
));
8379 buf
= sdscatlen(buf
,"\r\n",2);
8385 static sds
catAppendOnlyExpireAtCommand(sds buf
, robj
*key
, robj
*seconds
) {
8390 /* Make sure we can use strtol */
8391 seconds
= getDecodedObject(seconds
);
8392 when
= time(NULL
)+strtol(seconds
->ptr
,NULL
,10);
8393 decrRefCount(seconds
);
8395 argv
[0] = createStringObject("EXPIREAT",8);
8397 argv
[2] = createObject(REDIS_STRING
,
8398 sdscatprintf(sdsempty(),"%ld",when
));
8399 buf
= catAppendOnlyGenericCommand(buf
, argc
, argv
);
8400 decrRefCount(argv
[0]);
8401 decrRefCount(argv
[2]);
8405 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
8406 sds buf
= sdsempty();
8409 /* The DB this command was targetting is not the same as the last command
8410 * we appendend. To issue a SELECT command is needed. */
8411 if (dictid
!= server
.appendseldb
) {
8414 snprintf(seldb
,sizeof(seldb
),"%d",dictid
);
8415 buf
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
8416 (unsigned long)strlen(seldb
),seldb
);
8417 server
.appendseldb
= dictid
;
8420 if (cmd
->proc
== expireCommand
) {
8421 /* Translate EXPIRE into EXPIREAT */
8422 buf
= catAppendOnlyExpireAtCommand(buf
,argv
[1],argv
[2]);
8423 } else if (cmd
->proc
== setexCommand
) {
8424 /* Translate SETEX to SET and EXPIREAT */
8425 tmpargv
[0] = createStringObject("SET",3);
8426 tmpargv
[1] = argv
[1];
8427 tmpargv
[2] = argv
[3];
8428 buf
= catAppendOnlyGenericCommand(buf
,3,tmpargv
);
8429 decrRefCount(tmpargv
[0]);
8430 buf
= catAppendOnlyExpireAtCommand(buf
,argv
[1],argv
[2]);
8432 buf
= catAppendOnlyGenericCommand(buf
,argc
,argv
);
8435 /* Append to the AOF buffer. This will be flushed on disk just before
8436 * of re-entering the event loop, so before the client will get a
8437 * positive reply about the operation performed. */
8438 server
.aofbuf
= sdscatlen(server
.aofbuf
,buf
,sdslen(buf
));
8440 /* If a background append only file rewriting is in progress we want to
8441 * accumulate the differences between the child DB and the current one
8442 * in a buffer, so that when the child process will do its work we
8443 * can append the differences to the new append only file. */
8444 if (server
.bgrewritechildpid
!= -1)
8445 server
.bgrewritebuf
= sdscatlen(server
.bgrewritebuf
,buf
,sdslen(buf
));
8450 /* In Redis commands are always executed in the context of a client, so in
8451 * order to load the append only file we need to create a fake client. */
8452 static struct redisClient
*createFakeClient(void) {
8453 struct redisClient
*c
= zmalloc(sizeof(*c
));
8457 c
->querybuf
= sdsempty();
8461 /* We set the fake client as a slave waiting for the synchronization
8462 * so that Redis will not try to send replies to this client. */
8463 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
8464 c
->reply
= listCreate();
8465 listSetFreeMethod(c
->reply
,decrRefCount
);
8466 listSetDupMethod(c
->reply
,dupClientReplyValue
);
8467 initClientMultiState(c
);
8471 static void freeFakeClient(struct redisClient
*c
) {
8472 sdsfree(c
->querybuf
);
8473 listRelease(c
->reply
);
8474 freeClientMultiState(c
);
8478 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
8479 * error (the append only file is zero-length) REDIS_ERR is returned. On
8480 * fatal error an error message is logged and the program exists. */
8481 int loadAppendOnlyFile(char *filename
) {
8482 struct redisClient
*fakeClient
;
8483 FILE *fp
= fopen(filename
,"r");
8484 struct redis_stat sb
;
8485 int appendonly
= server
.appendonly
;
8487 if (redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0)
8491 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
8495 /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
8496 * to the same file we're about to read. */
8497 server
.appendonly
= 0;
8499 fakeClient
= createFakeClient();
8506 struct redisCommand
*cmd
;
8509 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
8515 if (buf
[0] != '*') goto fmterr
;
8517 argv
= zmalloc(sizeof(robj
*)*argc
);
8518 for (j
= 0; j
< argc
; j
++) {
8519 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
8520 if (buf
[0] != '$') goto fmterr
;
8521 len
= strtol(buf
+1,NULL
,10);
8522 argsds
= sdsnewlen(NULL
,len
);
8523 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
8524 argv
[j
] = createObject(REDIS_STRING
,argsds
);
8525 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
8528 /* Command lookup */
8529 cmd
= lookupCommand(argv
[0]->ptr
);
8531 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
8534 /* Try object encoding */
8535 if (cmd
->flags
& REDIS_CMD_BULK
)
8536 argv
[argc
-1] = tryObjectEncoding(argv
[argc
-1]);
8537 /* Run the command in the context of a fake client */
8538 fakeClient
->argc
= argc
;
8539 fakeClient
->argv
= argv
;
8540 cmd
->proc(fakeClient
);
8541 /* Discard the reply objects list from the fake client */
8542 while(listLength(fakeClient
->reply
))
8543 listDelNode(fakeClient
->reply
,listFirst(fakeClient
->reply
));
8544 /* Clean up, ready for the next command */
8545 for (j
= 0; j
< argc
; j
++) decrRefCount(argv
[j
]);
8547 /* Handle swapping while loading big datasets when VM is on */
8549 if ((zmalloc_used_memory() - server
.vm_max_memory
) > 1024*1024*32)
8552 if (server
.vm_enabled
&& force_swapout
) {
8553 while (zmalloc_used_memory() > server
.vm_max_memory
) {
8554 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
8559 /* This point can only be reached when EOF is reached without errors.
8560 * If the client is in the middle of a MULTI/EXEC, log error and quit. */
8561 if (fakeClient
->flags
& REDIS_MULTI
) goto readerr
;
8564 freeFakeClient(fakeClient
);
8565 server
.appendonly
= appendonly
;
8570 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
8572 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
8576 redisLog(REDIS_WARNING
,"Bad file format reading the append only file");
8580 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
8581 static int fwriteBulkObject(FILE *fp
, robj
*obj
) {
8585 /* Avoid the incr/decr ref count business if possible to help
8586 * copy-on-write (we are often in a child process when this function
8588 * Also makes sure that key objects don't get incrRefCount-ed when VM
8590 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
8591 obj
= getDecodedObject(obj
);
8594 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(long)sdslen(obj
->ptr
));
8595 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) goto err
;
8596 if (sdslen(obj
->ptr
) && fwrite(obj
->ptr
,sdslen(obj
->ptr
),1,fp
) == 0)
8598 if (fwrite("\r\n",2,1,fp
) == 0) goto err
;
8599 if (decrrc
) decrRefCount(obj
);
8602 if (decrrc
) decrRefCount(obj
);
8606 /* Write binary-safe string into a file in the bulkformat
8607 * $<count>\r\n<payload>\r\n */
8608 static int fwriteBulkString(FILE *fp
, char *s
, unsigned long len
) {
8611 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(unsigned long)len
);
8612 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
8613 if (len
&& fwrite(s
,len
,1,fp
) == 0) return 0;
8614 if (fwrite("\r\n",2,1,fp
) == 0) return 0;
8618 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
8619 static int fwriteBulkDouble(FILE *fp
, double d
) {
8620 char buf
[128], dbuf
[128];
8622 snprintf(dbuf
,sizeof(dbuf
),"%.17g\r\n",d
);
8623 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(dbuf
)-2);
8624 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
8625 if (fwrite(dbuf
,strlen(dbuf
),1,fp
) == 0) return 0;
8629 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
8630 static int fwriteBulkLong(FILE *fp
, long l
) {
8631 char buf
[128], lbuf
[128];
8633 snprintf(lbuf
,sizeof(lbuf
),"%ld\r\n",l
);
8634 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(lbuf
)-2);
8635 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
8636 if (fwrite(lbuf
,strlen(lbuf
),1,fp
) == 0) return 0;
8640 /* Write a sequence of commands able to fully rebuild the dataset into
8641 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
8642 static int rewriteAppendOnlyFile(char *filename
) {
8643 dictIterator
*di
= NULL
;
8648 time_t now
= time(NULL
);
8650 /* Note that we have to use a different temp name here compared to the
8651 * one used by rewriteAppendOnlyFileBackground() function. */
8652 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
8653 fp
= fopen(tmpfile
,"w");
8655 redisLog(REDIS_WARNING
, "Failed rewriting the append only file: %s", strerror(errno
));
8658 for (j
= 0; j
< server
.dbnum
; j
++) {
8659 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
8660 redisDb
*db
= server
.db
+j
;
8662 if (dictSize(d
) == 0) continue;
8663 di
= dictGetIterator(d
);
8669 /* SELECT the new DB */
8670 if (fwrite(selectcmd
,sizeof(selectcmd
)-1,1,fp
) == 0) goto werr
;
8671 if (fwriteBulkLong(fp
,j
) == 0) goto werr
;
8673 /* Iterate this DB writing every entry */
8674 while((de
= dictNext(di
)) != NULL
) {
8679 key
= dictGetEntryKey(de
);
8680 o
= dictGetEntryVal(de
);
8681 /* If the value for this key is swapped, load a preview in memory.
8682 * We use a "swapped" flag to remember if we need to free the
8683 * value object instead to just increment the ref count anyway
8684 * in order to avoid copy-on-write of pages if we are forked() */
8685 if (!server
.vm_enabled
|| o
->storage
== REDIS_VM_MEMORY
||
8686 o
->storage
== REDIS_VM_SWAPPING
) {
8689 o
= vmPreviewObject(o
);
8692 expiretime
= getExpire(db
,key
);
8694 /* Save the key and associated value */
8695 if (o
->type
== REDIS_STRING
) {
8696 /* Emit a SET command */
8697 char cmd
[]="*3\r\n$3\r\nSET\r\n";
8698 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8700 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8701 if (fwriteBulkObject(fp
,o
) == 0) goto werr
;
8702 } else if (o
->type
== REDIS_LIST
) {
8703 /* Emit the RPUSHes needed to rebuild the list */
8704 list
*list
= o
->ptr
;
8708 listRewind(list
,&li
);
8709 while((ln
= listNext(&li
))) {
8710 char cmd
[]="*3\r\n$5\r\nRPUSH\r\n";
8711 robj
*eleobj
= listNodeValue(ln
);
8713 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8714 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8715 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
8717 } else if (o
->type
== REDIS_SET
) {
8718 /* Emit the SADDs needed to rebuild the set */
8720 dictIterator
*di
= dictGetIterator(set
);
8723 while((de
= dictNext(di
)) != NULL
) {
8724 char cmd
[]="*3\r\n$4\r\nSADD\r\n";
8725 robj
*eleobj
= dictGetEntryKey(de
);
8727 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8728 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8729 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
8731 dictReleaseIterator(di
);
8732 } else if (o
->type
== REDIS_ZSET
) {
8733 /* Emit the ZADDs needed to rebuild the sorted set */
8735 dictIterator
*di
= dictGetIterator(zs
->dict
);
8738 while((de
= dictNext(di
)) != NULL
) {
8739 char cmd
[]="*4\r\n$4\r\nZADD\r\n";
8740 robj
*eleobj
= dictGetEntryKey(de
);
8741 double *score
= dictGetEntryVal(de
);
8743 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8744 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8745 if (fwriteBulkDouble(fp
,*score
) == 0) goto werr
;
8746 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
8748 dictReleaseIterator(di
);
8749 } else if (o
->type
== REDIS_HASH
) {
8750 char cmd
[]="*4\r\n$4\r\nHSET\r\n";
8752 /* Emit the HSETs needed to rebuild the hash */
8753 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
8754 unsigned char *p
= zipmapRewind(o
->ptr
);
8755 unsigned char *field
, *val
;
8756 unsigned int flen
, vlen
;
8758 while((p
= zipmapNext(p
,&field
,&flen
,&val
,&vlen
)) != NULL
) {
8759 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8760 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8761 if (fwriteBulkString(fp
,(char*)field
,flen
) == -1)
8763 if (fwriteBulkString(fp
,(char*)val
,vlen
) == -1)
8767 dictIterator
*di
= dictGetIterator(o
->ptr
);
8770 while((de
= dictNext(di
)) != NULL
) {
8771 robj
*field
= dictGetEntryKey(de
);
8772 robj
*val
= dictGetEntryVal(de
);
8774 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8775 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8776 if (fwriteBulkObject(fp
,field
) == -1) return -1;
8777 if (fwriteBulkObject(fp
,val
) == -1) return -1;
8779 dictReleaseIterator(di
);
8782 redisPanic("Unknown object type");
8784 /* Save the expire time */
8785 if (expiretime
!= -1) {
8786 char cmd
[]="*3\r\n$8\r\nEXPIREAT\r\n";
8787 /* If this key is already expired skip it */
8788 if (expiretime
< now
) continue;
8789 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8790 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8791 if (fwriteBulkLong(fp
,expiretime
) == 0) goto werr
;
8793 if (swapped
) decrRefCount(o
);
8795 dictReleaseIterator(di
);
8798 /* Make sure data will not remain on the OS's output buffers */
8800 aof_fsync(fileno(fp
));
8803 /* Use RENAME to make sure the DB file is changed atomically only
8804 * if the generate DB file is ok. */
8805 if (rename(tmpfile
,filename
) == -1) {
8806 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
8810 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
8816 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
8817 if (di
) dictReleaseIterator(di
);
8821 /* This is how rewriting of the append only file in background works:
8823 * 1) The user calls BGREWRITEAOF
8824 * 2) Redis calls this function, that forks():
8825 * 2a) the child rewrite the append only file in a temp file.
8826 * 2b) the parent accumulates differences in server.bgrewritebuf.
8827 * 3) When the child finished '2a' exists.
8828 * 4) The parent will trap the exit code, if it's OK, will append the
8829 * data accumulated into server.bgrewritebuf into the temp file, and
8830 * finally will rename(2) the temp file in the actual file name.
8831 * The the new file is reopened as the new append only file. Profit!
8833 static int rewriteAppendOnlyFileBackground(void) {
8836 if (server
.bgrewritechildpid
!= -1) return REDIS_ERR
;
8837 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
8838 if ((childpid
= fork()) == 0) {
8842 if (server
.vm_enabled
) vmReopenSwapFile();
8844 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
8845 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
8852 if (childpid
== -1) {
8853 redisLog(REDIS_WARNING
,
8854 "Can't rewrite append only file in background: fork: %s",
8858 redisLog(REDIS_NOTICE
,
8859 "Background append only file rewriting started by pid %d",childpid
);
8860 server
.bgrewritechildpid
= childpid
;
8861 updateDictResizePolicy();
8862 /* We set appendseldb to -1 in order to force the next call to the
8863 * feedAppendOnlyFile() to issue a SELECT command, so the differences
8864 * accumulated by the parent into server.bgrewritebuf will start
8865 * with a SELECT statement and it will be safe to merge. */
8866 server
.appendseldb
= -1;
8869 return REDIS_OK
; /* unreached */
8872 static void bgrewriteaofCommand(redisClient
*c
) {
8873 if (server
.bgrewritechildpid
!= -1) {
8874 addReplySds(c
,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
8877 if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
8878 char *status
= "+Background append only file rewriting started\r\n";
8879 addReplySds(c
,sdsnew(status
));
8881 addReply(c
,shared
.err
);
8885 static void aofRemoveTempFile(pid_t childpid
) {
8888 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
8892 /* Virtual Memory is composed mainly of two subsystems:
8893 * - Blocking Virutal Memory
8894 * - Threaded Virtual Memory I/O
8895 * The two parts are not fully decoupled, but functions are split among two
8896 * different sections of the source code (delimited by comments) in order to
8897 * make more clear what functionality is about the blocking VM and what about
8898 * the threaded (not blocking) VM.
8902 * Redis VM is a blocking VM (one that blocks reading swapped values from
8903 * disk into memory when a value swapped out is needed in memory) that is made
8904 * unblocking by trying to examine the command argument vector in order to
8905 * load in background values that will likely be needed in order to exec
8906 * the command. The command is executed only once all the relevant keys
8907 * are loaded into memory.
8909 * This basically is almost as simple of a blocking VM, but almost as parallel
8910 * as a fully non-blocking VM.
8913 /* =================== Virtual Memory - Blocking Side ====================== */
8915 /* Create a VM pointer object. This kind of objects are used in place of
8916 * values in the key -> value hash table, for swapped out objects. */
8917 static vmpointer
*createVmPointer(int vtype
) {
8918 vmpointer
*vp
= zmalloc(sizeof(vmpointer
));
8920 vp
->type
= REDIS_VMPOINTER
;
8921 vp
->storage
= REDIS_VM_SWAPPED
;
8926 static void vmInit(void) {
8932 if (server
.vm_max_threads
!= 0)
8933 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
8935 redisLog(REDIS_NOTICE
,"Using '%s' as swap file",server
.vm_swap_file
);
8936 /* Try to open the old swap file, otherwise create it */
8937 if ((server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b")) == NULL
) {
8938 server
.vm_fp
= fopen(server
.vm_swap_file
,"w+b");
8940 if (server
.vm_fp
== NULL
) {
8941 redisLog(REDIS_WARNING
,
8942 "Can't open the swap file: %s. Exiting.",
8946 server
.vm_fd
= fileno(server
.vm_fp
);
8947 /* Lock the swap file for writing, this is useful in order to avoid
8948 * another instance to use the same swap file for a config error. */
8949 fl
.l_type
= F_WRLCK
;
8950 fl
.l_whence
= SEEK_SET
;
8951 fl
.l_start
= fl
.l_len
= 0;
8952 if (fcntl(server
.vm_fd
,F_SETLK
,&fl
) == -1) {
8953 redisLog(REDIS_WARNING
,
8954 "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
));
8958 server
.vm_next_page
= 0;
8959 server
.vm_near_pages
= 0;
8960 server
.vm_stats_used_pages
= 0;
8961 server
.vm_stats_swapped_objects
= 0;
8962 server
.vm_stats_swapouts
= 0;
8963 server
.vm_stats_swapins
= 0;
8964 totsize
= server
.vm_pages
*server
.vm_page_size
;
8965 redisLog(REDIS_NOTICE
,"Allocating %lld bytes of swap file",totsize
);
8966 if (ftruncate(server
.vm_fd
,totsize
) == -1) {
8967 redisLog(REDIS_WARNING
,"Can't ftruncate swap file: %s. Exiting.",
8971 redisLog(REDIS_NOTICE
,"Swap file allocated with success");
8973 server
.vm_bitmap
= zmalloc((server
.vm_pages
+7)/8);
8974 redisLog(REDIS_VERBOSE
,"Allocated %lld bytes page table for %lld pages",
8975 (long long) (server
.vm_pages
+7)/8, server
.vm_pages
);
8976 memset(server
.vm_bitmap
,0,(server
.vm_pages
+7)/8);
8978 /* Initialize threaded I/O (used by Virtual Memory) */
8979 server
.io_newjobs
= listCreate();
8980 server
.io_processing
= listCreate();
8981 server
.io_processed
= listCreate();
8982 server
.io_ready_clients
= listCreate();
8983 pthread_mutex_init(&server
.io_mutex
,NULL
);
8984 pthread_mutex_init(&server
.obj_freelist_mutex
,NULL
);
8985 pthread_mutex_init(&server
.io_swapfile_mutex
,NULL
);
8986 server
.io_active_threads
= 0;
8987 if (pipe(pipefds
) == -1) {
8988 redisLog(REDIS_WARNING
,"Unable to intialized VM: pipe(2): %s. Exiting."
8992 server
.io_ready_pipe_read
= pipefds
[0];
8993 server
.io_ready_pipe_write
= pipefds
[1];
8994 redisAssert(anetNonBlock(NULL
,server
.io_ready_pipe_read
) != ANET_ERR
);
8995 /* LZF requires a lot of stack */
8996 pthread_attr_init(&server
.io_threads_attr
);
8997 pthread_attr_getstacksize(&server
.io_threads_attr
, &stacksize
);
8998 while (stacksize
< REDIS_THREAD_STACK_SIZE
) stacksize
*= 2;
8999 pthread_attr_setstacksize(&server
.io_threads_attr
, stacksize
);
9000 /* Listen for events in the threaded I/O pipe */
9001 if (aeCreateFileEvent(server
.el
, server
.io_ready_pipe_read
, AE_READABLE
,
9002 vmThreadedIOCompletedJob
, NULL
) == AE_ERR
)
9003 oom("creating file event");
9006 /* Mark the page as used */
9007 static void vmMarkPageUsed(off_t page
) {
9008 off_t byte
= page
/8;
9010 redisAssert(vmFreePage(page
) == 1);
9011 server
.vm_bitmap
[byte
] |= 1<<bit
;
9014 /* Mark N contiguous pages as used, with 'page' being the first. */
9015 static void vmMarkPagesUsed(off_t page
, off_t count
) {
9018 for (j
= 0; j
< count
; j
++)
9019 vmMarkPageUsed(page
+j
);
9020 server
.vm_stats_used_pages
+= count
;
9021 redisLog(REDIS_DEBUG
,"Mark USED pages: %lld pages at %lld\n",
9022 (long long)count
, (long long)page
);
9025 /* Mark the page as free */
9026 static void vmMarkPageFree(off_t page
) {
9027 off_t byte
= page
/8;
9029 redisAssert(vmFreePage(page
) == 0);
9030 server
.vm_bitmap
[byte
] &= ~(1<<bit
);
9033 /* Mark N contiguous pages as free, with 'page' being the first. */
9034 static void vmMarkPagesFree(off_t page
, off_t count
) {
9037 for (j
= 0; j
< count
; j
++)
9038 vmMarkPageFree(page
+j
);
9039 server
.vm_stats_used_pages
-= count
;
9040 redisLog(REDIS_DEBUG
,"Mark FREE pages: %lld pages at %lld\n",
9041 (long long)count
, (long long)page
);
9044 /* Test if the page is free */
9045 static int vmFreePage(off_t page
) {
9046 off_t byte
= page
/8;
9048 return (server
.vm_bitmap
[byte
] & (1<<bit
)) == 0;
9051 /* Find N contiguous free pages storing the first page of the cluster in *first.
9052 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
9053 * REDIS_ERR is returned.
9055 * This function uses a simple algorithm: we try to allocate
9056 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
9057 * again from the start of the swap file searching for free spaces.
9059 * If it looks pretty clear that there are no free pages near our offset
9060 * we try to find less populated places doing a forward jump of
9061 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
9062 * without hurry, and then we jump again and so forth...
9064 * This function can be improved using a free list to avoid to guess
9065 * too much, since we could collect data about freed pages.
9067 * note: I implemented this function just after watching an episode of
9068 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
9070 static int vmFindContiguousPages(off_t
*first
, off_t n
) {
9071 off_t base
, offset
= 0, since_jump
= 0, numfree
= 0;
9073 if (server
.vm_near_pages
== REDIS_VM_MAX_NEAR_PAGES
) {
9074 server
.vm_near_pages
= 0;
9075 server
.vm_next_page
= 0;
9077 server
.vm_near_pages
++; /* Yet another try for pages near to the old ones */
9078 base
= server
.vm_next_page
;
9080 while(offset
< server
.vm_pages
) {
9081 off_t
this = base
+offset
;
9083 /* If we overflow, restart from page zero */
9084 if (this >= server
.vm_pages
) {
9085 this -= server
.vm_pages
;
9087 /* Just overflowed, what we found on tail is no longer
9088 * interesting, as it's no longer contiguous. */
9092 if (vmFreePage(this)) {
9093 /* This is a free page */
9095 /* Already got N free pages? Return to the caller, with success */
9097 *first
= this-(n
-1);
9098 server
.vm_next_page
= this+1;
9099 redisLog(REDIS_DEBUG
, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n
, (long long) *first
);
9103 /* The current one is not a free page */
9107 /* Fast-forward if the current page is not free and we already
9108 * searched enough near this place. */
9110 if (!numfree
&& since_jump
>= REDIS_VM_MAX_RANDOM_JUMP
/4) {
9111 offset
+= random() % REDIS_VM_MAX_RANDOM_JUMP
;
9113 /* Note that even if we rewind after the jump, we are don't need
9114 * to make sure numfree is set to zero as we only jump *if* it
9115 * is set to zero. */
9117 /* Otherwise just check the next page */
9124 /* Write the specified object at the specified page of the swap file */
9125 static int vmWriteObjectOnSwap(robj
*o
, off_t page
) {
9126 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
9127 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
9128 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
9129 redisLog(REDIS_WARNING
,
9130 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
9134 rdbSaveObject(server
.vm_fp
,o
);
9135 fflush(server
.vm_fp
);
9136 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
9140 /* Transfers the 'val' object to disk. Store all the information
9141 * a 'vmpointer' object containing all the information needed to load the
9142 * object back later is returned.
9144 * If we can't find enough contiguous empty pages to swap the object on disk
9145 * NULL is returned. */
9146 static vmpointer
*vmSwapObjectBlocking(robj
*val
) {
9147 off_t pages
= rdbSavedObjectPages(val
,NULL
);
9151 assert(val
->storage
== REDIS_VM_MEMORY
);
9152 assert(val
->refcount
== 1);
9153 if (vmFindContiguousPages(&page
,pages
) == REDIS_ERR
) return NULL
;
9154 if (vmWriteObjectOnSwap(val
,page
) == REDIS_ERR
) return NULL
;
9156 vp
= createVmPointer(val
->type
);
9158 vp
->usedpages
= pages
;
9159 decrRefCount(val
); /* Deallocate the object from memory. */
9160 vmMarkPagesUsed(page
,pages
);
9161 redisLog(REDIS_DEBUG
,"VM: object %p swapped out at %lld (%lld pages)",
9163 (unsigned long long) page
, (unsigned long long) pages
);
9164 server
.vm_stats_swapped_objects
++;
9165 server
.vm_stats_swapouts
++;
9169 static robj
*vmReadObjectFromSwap(off_t page
, int type
) {
9172 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
9173 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
9174 redisLog(REDIS_WARNING
,
9175 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
9179 o
= rdbLoadObject(type
,server
.vm_fp
);
9181 redisLog(REDIS_WARNING
, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno
));
9184 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
9188 /* Load the specified object from swap to memory.
9189 * The newly allocated object is returned.
9191 * If preview is true the unserialized object is returned to the caller but
9192 * the pages are not marked as freed, nor the vp object is freed. */
9193 static robj
*vmGenericLoadObject(vmpointer
*vp
, int preview
) {
9196 redisAssert(vp
->type
== REDIS_VMPOINTER
&&
9197 (vp
->storage
== REDIS_VM_SWAPPED
|| vp
->storage
== REDIS_VM_LOADING
));
9198 val
= vmReadObjectFromSwap(vp
->page
,vp
->vtype
);
9200 redisLog(REDIS_DEBUG
, "VM: object %p loaded from disk", (void*)vp
);
9201 vmMarkPagesFree(vp
->page
,vp
->usedpages
);
9203 server
.vm_stats_swapped_objects
--;
9205 redisLog(REDIS_DEBUG
, "VM: object %p previewed from disk", (void*)vp
);
9207 server
.vm_stats_swapins
++;
9211 /* Plain object loading, from swap to memory.
9213 * 'o' is actually a redisVmPointer structure that will be freed by the call.
9214 * The return value is the loaded object. */
9215 static robj
*vmLoadObject(robj
*o
) {
9216 /* If we are loading the object in background, stop it, we
9217 * need to load this object synchronously ASAP. */
9218 if (o
->storage
== REDIS_VM_LOADING
)
9219 vmCancelThreadedIOJob(o
);
9220 return vmGenericLoadObject((vmpointer
*)o
,0);
9223 /* Just load the value on disk, without to modify the key.
9224 * This is useful when we want to perform some operation on the value
9225 * without to really bring it from swap to memory, like while saving the
9226 * dataset or rewriting the append only log. */
9227 static robj
*vmPreviewObject(robj
*o
) {
9228 return vmGenericLoadObject((vmpointer
*)o
,1);
9231 /* How a good candidate is this object for swapping?
9232 * The better candidate it is, the greater the returned value.
9234 * Currently we try to perform a fast estimation of the object size in
9235 * memory, and combine it with aging informations.
9237 * Basically swappability = idle-time * log(estimated size)
9239 * Bigger objects are preferred over smaller objects, but not
9240 * proportionally, this is why we use the logarithm. This algorithm is
9241 * just a first try and will probably be tuned later. */
9242 static double computeObjectSwappability(robj
*o
) {
9243 /* actual age can be >= minage, but not < minage. As we use wrapping
9244 * 21 bit clocks with minutes resolution for the LRU. */
9245 time_t minage
= abs(server
.lruclock
- o
->lru
);
9249 struct dictEntry
*de
;
9252 if (minage
<= 0) return 0;
9255 if (o
->encoding
!= REDIS_ENCODING_RAW
) {
9258 asize
= sdslen(o
->ptr
)+sizeof(*o
)+sizeof(long)*2;
9263 listNode
*ln
= listFirst(l
);
9265 asize
= sizeof(list
);
9267 robj
*ele
= ln
->value
;
9270 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
9271 (sizeof(*o
)+sdslen(ele
->ptr
)) : sizeof(*o
);
9272 asize
+= (sizeof(listNode
)+elesize
)*listLength(l
);
9277 z
= (o
->type
== REDIS_ZSET
);
9278 d
= z
? ((zset
*)o
->ptr
)->dict
: o
->ptr
;
9280 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
9281 if (z
) asize
+= sizeof(zset
)-sizeof(dict
);
9286 de
= dictGetRandomKey(d
);
9287 ele
= dictGetEntryKey(de
);
9288 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
9289 (sizeof(*o
)+sdslen(ele
->ptr
)) : sizeof(*o
);
9290 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
9291 if (z
) asize
+= sizeof(zskiplistNode
)*dictSize(d
);
9295 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
9296 unsigned char *p
= zipmapRewind((unsigned char*)o
->ptr
);
9297 unsigned int len
= zipmapLen((unsigned char*)o
->ptr
);
9298 unsigned int klen
, vlen
;
9299 unsigned char *key
, *val
;
9301 if ((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) == NULL
) {
9305 asize
= len
*(klen
+vlen
+3);
9306 } else if (o
->encoding
== REDIS_ENCODING_HT
) {
9308 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
9313 de
= dictGetRandomKey(d
);
9314 ele
= dictGetEntryKey(de
);
9315 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
9316 (sizeof(*o
)+sdslen(ele
->ptr
)) : sizeof(*o
);
9317 ele
= dictGetEntryVal(de
);
9318 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
9319 (sizeof(*o
)+sdslen(ele
->ptr
)) : sizeof(*o
);
9320 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
9325 return (double)minage
*log(1+asize
);
9328 /* Try to swap an object that's a good candidate for swapping.
9329 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
9330 * to swap any object at all.
9332 * If 'usethreaded' is true, Redis will try to swap the object in background
9333 * using I/O threads. */
9334 static int vmSwapOneObject(int usethreads
) {
9336 struct dictEntry
*best
= NULL
;
9337 double best_swappability
= 0;
9338 redisDb
*best_db
= NULL
;
9341 for (j
= 0; j
< server
.dbnum
; j
++) {
9342 redisDb
*db
= server
.db
+j
;
9343 /* Why maxtries is set to 100?
9344 * Because this way (usually) we'll find 1 object even if just 1% - 2%
9345 * are swappable objects */
9348 if (dictSize(db
->dict
) == 0) continue;
9349 for (i
= 0; i
< 5; i
++) {
9351 double swappability
;
9353 if (maxtries
) maxtries
--;
9354 de
= dictGetRandomKey(db
->dict
);
9355 key
= dictGetEntryKey(de
);
9356 val
= dictGetEntryVal(de
);
9357 /* Only swap objects that are currently in memory.
9359 * Also don't swap shared objects: not a good idea in general and
9360 * we need to ensure that the main thread does not touch the
9361 * object while the I/O thread is using it, but we can't
9362 * control other keys without adding additional mutex. */
9363 if (val
->storage
!= REDIS_VM_MEMORY
|| val
->refcount
!= 1) {
9364 if (maxtries
) i
--; /* don't count this try */
9367 swappability
= computeObjectSwappability(val
);
9368 if (!best
|| swappability
> best_swappability
) {
9370 best_swappability
= swappability
;
9375 if (best
== NULL
) return REDIS_ERR
;
9376 key
= dictGetEntryKey(best
);
9377 val
= dictGetEntryVal(best
);
9379 redisLog(REDIS_DEBUG
,"Key with best swappability: %s, %f",
9380 key
->ptr
, best_swappability
);
9384 vmSwapObjectThreaded(key
,val
,best_db
);
9389 if ((vp
= vmSwapObjectBlocking(val
)) != NULL
) {
9390 dictGetEntryVal(best
) = vp
;
9398 static int vmSwapOneObjectBlocking() {
9399 return vmSwapOneObject(0);
9402 static int vmSwapOneObjectThreaded() {
9403 return vmSwapOneObject(1);
9406 /* Return true if it's safe to swap out objects in a given moment.
9407 * Basically we don't want to swap objects out while there is a BGSAVE
9408 * or a BGAEOREWRITE running in backgroud. */
9409 static int vmCanSwapOut(void) {
9410 return (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1);
9413 /* Delete a key if swapped. Returns 1 if the key was found, was swapped
9414 * and was deleted. Otherwise 0 is returned. */
9415 static int deleteIfSwapped(redisDb
*db
, robj
*key
) {
9418 if ((val
= dictFetchValue(db
->dict
,key
)) == NULL
) return 0;
9419 if (val
->storage
== REDIS_VM_MEMORY
) return 0;
9424 /* =================== Virtual Memory - Threaded I/O ======================= */
9426 static void freeIOJob(iojob
*j
) {
9427 if ((j
->type
== REDIS_IOJOB_PREPARE_SWAP
||
9428 j
->type
== REDIS_IOJOB_DO_SWAP
||
9429 j
->type
== REDIS_IOJOB_LOAD
) && j
->val
!= NULL
)
9431 /* we fix the storage type, otherwise decrRefCount() will try to
9432 * kill the I/O thread Job (that does no longer exists). */
9433 if (j
->val
->storage
== REDIS_VM_SWAPPING
)
9434 j
->val
->storage
= REDIS_VM_MEMORY
;
9435 decrRefCount(j
->val
);
9437 decrRefCount(j
->key
);
9441 /* Every time a thread finished a Job, it writes a byte into the write side
9442 * of an unix pipe in order to "awake" the main thread, and this function
9444 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
,
9448 int retval
, processed
= 0, toprocess
= -1, trytoswap
= 1;
9450 REDIS_NOTUSED(mask
);
9451 REDIS_NOTUSED(privdata
);
9453 /* For every byte we read in the read side of the pipe, there is one
9454 * I/O job completed to process. */
9455 while((retval
= read(fd
,buf
,1)) == 1) {
9458 struct dictEntry
*de
;
9460 redisLog(REDIS_DEBUG
,"Processing I/O completed job");
9462 /* Get the processed element (the oldest one) */
9464 assert(listLength(server
.io_processed
) != 0);
9465 if (toprocess
== -1) {
9466 toprocess
= (listLength(server
.io_processed
)*REDIS_MAX_COMPLETED_JOBS_PROCESSED
)/100;
9467 if (toprocess
<= 0) toprocess
= 1;
9469 ln
= listFirst(server
.io_processed
);
9471 listDelNode(server
.io_processed
,ln
);
9473 /* If this job is marked as canceled, just ignore it */
9478 /* Post process it in the main thread, as there are things we
9479 * can do just here to avoid race conditions and/or invasive locks */
9480 redisLog(REDIS_DEBUG
,"COMPLETED Job type: %d, ID %p, key: %s", j
->type
, (void*)j
->id
, (unsigned char*)j
->key
->ptr
);
9481 de
= dictFind(j
->db
->dict
,j
->key
);
9482 redisAssert(de
!= NULL
);
9483 if (j
->type
== REDIS_IOJOB_LOAD
) {
9485 vmpointer
*vp
= dictGetEntryVal(de
);
9487 /* Key loaded, bring it at home */
9488 vmMarkPagesFree(vp
->page
,vp
->usedpages
);
9489 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk (threaded)",
9490 (unsigned char*) j
->key
->ptr
);
9491 server
.vm_stats_swapped_objects
--;
9492 server
.vm_stats_swapins
++;
9493 dictGetEntryVal(de
) = j
->val
;
9494 incrRefCount(j
->val
);
9496 /* Handle clients waiting for this key to be loaded. */
9497 handleClientsBlockedOnSwappedKey(db
,j
->key
);
9500 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
9501 /* Now we know the amount of pages required to swap this object.
9502 * Let's find some space for it, and queue this task again
9503 * rebranded as REDIS_IOJOB_DO_SWAP. */
9504 if (!vmCanSwapOut() ||
9505 vmFindContiguousPages(&j
->page
,j
->pages
) == REDIS_ERR
)
9507 /* Ooops... no space or we can't swap as there is
9508 * a fork()ed Redis trying to save stuff on disk. */
9509 j
->val
->storage
= REDIS_VM_MEMORY
; /* undo operation */
9512 /* Note that we need to mark this pages as used now,
9513 * if the job will be canceled, we'll mark them as freed
9515 vmMarkPagesUsed(j
->page
,j
->pages
);
9516 j
->type
= REDIS_IOJOB_DO_SWAP
;
9521 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
9524 /* Key swapped. We can finally free some memory. */
9525 if (j
->val
->storage
!= REDIS_VM_SWAPPING
) {
9526 vmpointer
*vp
= (vmpointer
*) j
->id
;
9527 printf("storage: %d\n",vp
->storage
);
9528 printf("key->name: %s\n",(char*)j
->key
->ptr
);
9529 printf("val: %p\n",(void*)j
->val
);
9530 printf("val->type: %d\n",j
->val
->type
);
9531 printf("val->ptr: %s\n",(char*)j
->val
->ptr
);
9533 redisAssert(j
->val
->storage
== REDIS_VM_SWAPPING
);
9534 vp
= createVmPointer(j
->val
->type
);
9536 vp
->usedpages
= j
->pages
;
9537 dictGetEntryVal(de
) = vp
;
9538 /* Fix the storage otherwise decrRefCount will attempt to
9539 * remove the associated I/O job */
9540 j
->val
->storage
= REDIS_VM_MEMORY
;
9541 decrRefCount(j
->val
);
9542 redisLog(REDIS_DEBUG
,
9543 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
9544 (unsigned char*) j
->key
->ptr
,
9545 (unsigned long long) j
->page
, (unsigned long long) j
->pages
);
9546 server
.vm_stats_swapped_objects
++;
9547 server
.vm_stats_swapouts
++;
9549 /* Put a few more swap requests in queue if we are still
9551 if (trytoswap
&& vmCanSwapOut() &&
9552 zmalloc_used_memory() > server
.vm_max_memory
)
9557 more
= listLength(server
.io_newjobs
) <
9558 (unsigned) server
.vm_max_threads
;
9560 /* Don't waste CPU time if swappable objects are rare. */
9561 if (vmSwapOneObjectThreaded() == REDIS_ERR
) {
9569 if (processed
== toprocess
) return;
9571 if (retval
< 0 && errno
!= EAGAIN
) {
9572 redisLog(REDIS_WARNING
,
9573 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
9578 static void lockThreadedIO(void) {
9579 pthread_mutex_lock(&server
.io_mutex
);
9582 static void unlockThreadedIO(void) {
9583 pthread_mutex_unlock(&server
.io_mutex
);
9586 /* Remove the specified object from the threaded I/O queue if still not
9587 * processed, otherwise make sure to flag it as canceled. */
9588 static void vmCancelThreadedIOJob(robj
*o
) {
9590 server
.io_newjobs
, /* 0 */
9591 server
.io_processing
, /* 1 */
9592 server
.io_processed
/* 2 */
9596 assert(o
->storage
== REDIS_VM_LOADING
|| o
->storage
== REDIS_VM_SWAPPING
);
9599 /* Search for a matching object in one of the queues */
9600 for (i
= 0; i
< 3; i
++) {
9604 listRewind(lists
[i
],&li
);
9605 while ((ln
= listNext(&li
)) != NULL
) {
9606 iojob
*job
= ln
->value
;
9608 if (job
->canceled
) continue; /* Skip this, already canceled. */
9610 redisLog(REDIS_DEBUG
,"*** CANCELED %p (key %s) (type %d) (LIST ID %d)\n",
9611 (void*)job
, (char*)job
->key
->ptr
, job
->type
, i
);
9612 /* Mark the pages as free since the swap didn't happened
9613 * or happened but is now discarded. */
9614 if (i
!= 1 && job
->type
== REDIS_IOJOB_DO_SWAP
)
9615 vmMarkPagesFree(job
->page
,job
->pages
);
9616 /* Cancel the job. It depends on the list the job is
9619 case 0: /* io_newjobs */
9620 /* If the job was yet not processed the best thing to do
9621 * is to remove it from the queue at all */
9623 listDelNode(lists
[i
],ln
);
9625 case 1: /* io_processing */
9626 /* Oh Shi- the thread is messing with the Job:
9628 * Probably it's accessing the object if this is a
9629 * PREPARE_SWAP or DO_SWAP job.
9630 * If it's a LOAD job it may be reading from disk and
9631 * if we don't wait for the job to terminate before to
9632 * cancel it, maybe in a few microseconds data can be
9633 * corrupted in this pages. So the short story is:
9635 * Better to wait for the job to move into the
9636 * next queue (processed)... */
9638 /* We try again and again until the job is completed. */
9640 /* But let's wait some time for the I/O thread
9641 * to finish with this job. After all this condition
9642 * should be very rare. */
9645 case 2: /* io_processed */
9646 /* The job was already processed, that's easy...
9647 * just mark it as canceled so that we'll ignore it
9648 * when processing completed jobs. */
9652 /* Finally we have to adjust the storage type of the object
9653 * in order to "UNDO" the operaiton. */
9654 if (o
->storage
== REDIS_VM_LOADING
)
9655 o
->storage
= REDIS_VM_SWAPPED
;
9656 else if (o
->storage
== REDIS_VM_SWAPPING
)
9657 o
->storage
= REDIS_VM_MEMORY
;
9659 redisLog(REDIS_DEBUG
,"*** DONE");
9665 printf("Not found: %p\n", (void*)o
);
9666 redisAssert(1 != 1); /* We should never reach this */
9669 static void *IOThreadEntryPoint(void *arg
) {
9674 pthread_detach(pthread_self());
9676 /* Get a new job to process */
9678 if (listLength(server
.io_newjobs
) == 0) {
9679 /* No new jobs in queue, exit. */
9680 redisLog(REDIS_DEBUG
,"Thread %ld exiting, nothing to do",
9681 (long) pthread_self());
9682 server
.io_active_threads
--;
9686 ln
= listFirst(server
.io_newjobs
);
9688 listDelNode(server
.io_newjobs
,ln
);
9689 /* Add the job in the processing queue */
9690 j
->thread
= pthread_self();
9691 listAddNodeTail(server
.io_processing
,j
);
9692 ln
= listLast(server
.io_processing
); /* We use ln later to remove it */
9694 redisLog(REDIS_DEBUG
,"Thread %ld got a new job (type %d): %p about key '%s'",
9695 (long) pthread_self(), j
->type
, (void*)j
, (char*)j
->key
->ptr
);
9697 /* Process the Job */
9698 if (j
->type
== REDIS_IOJOB_LOAD
) {
9699 vmpointer
*vp
= (vmpointer
*)j
->id
;
9700 j
->val
= vmReadObjectFromSwap(j
->page
,vp
->vtype
);
9701 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
9702 FILE *fp
= fopen("/dev/null","w+");
9703 j
->pages
= rdbSavedObjectPages(j
->val
,fp
);
9705 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
9706 if (vmWriteObjectOnSwap(j
->val
,j
->page
) == REDIS_ERR
)
9710 /* Done: insert the job into the processed queue */
9711 redisLog(REDIS_DEBUG
,"Thread %ld completed the job: %p (key %s)",
9712 (long) pthread_self(), (void*)j
, (char*)j
->key
->ptr
);
9714 listDelNode(server
.io_processing
,ln
);
9715 listAddNodeTail(server
.io_processed
,j
);
9718 /* Signal the main thread there is new stuff to process */
9719 assert(write(server
.io_ready_pipe_write
,"x",1) == 1);
9721 return NULL
; /* never reached */
9724 static void spawnIOThread(void) {
9726 sigset_t mask
, omask
;
9730 sigaddset(&mask
,SIGCHLD
);
9731 sigaddset(&mask
,SIGHUP
);
9732 sigaddset(&mask
,SIGPIPE
);
9733 pthread_sigmask(SIG_SETMASK
, &mask
, &omask
);
9734 while ((err
= pthread_create(&thread
,&server
.io_threads_attr
,IOThreadEntryPoint
,NULL
)) != 0) {
9735 redisLog(REDIS_WARNING
,"Unable to spawn an I/O thread: %s",
9739 pthread_sigmask(SIG_SETMASK
, &omask
, NULL
);
9740 server
.io_active_threads
++;
9743 /* We need to wait for the last thread to exit before we are able to
9744 * fork() in order to BGSAVE or BGREWRITEAOF. */
9745 static void waitEmptyIOJobsQueue(void) {
9747 int io_processed_len
;
9750 if (listLength(server
.io_newjobs
) == 0 &&
9751 listLength(server
.io_processing
) == 0 &&
9752 server
.io_active_threads
== 0)
9757 /* While waiting for empty jobs queue condition we post-process some
9758 * finshed job, as I/O threads may be hanging trying to write against
9759 * the io_ready_pipe_write FD but there are so much pending jobs that
9761 io_processed_len
= listLength(server
.io_processed
);
9763 if (io_processed_len
) {
9764 vmThreadedIOCompletedJob(NULL
,server
.io_ready_pipe_read
,NULL
,0);
9765 usleep(1000); /* 1 millisecond */
9767 usleep(10000); /* 10 milliseconds */
9772 static void vmReopenSwapFile(void) {
9773 /* Note: we don't close the old one as we are in the child process
9774 * and don't want to mess at all with the original file object. */
9775 server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b");
9776 if (server
.vm_fp
== NULL
) {
9777 redisLog(REDIS_WARNING
,"Can't re-open the VM swap file: %s. Exiting.",
9778 server
.vm_swap_file
);
9781 server
.vm_fd
= fileno(server
.vm_fp
);
9784 /* This function must be called while with threaded IO locked */
9785 static void queueIOJob(iojob
*j
) {
9786 redisLog(REDIS_DEBUG
,"Queued IO Job %p type %d about key '%s'\n",
9787 (void*)j
, j
->type
, (char*)j
->key
->ptr
);
9788 listAddNodeTail(server
.io_newjobs
,j
);
9789 if (server
.io_active_threads
< server
.vm_max_threads
)
9793 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
) {
9796 assert(key
->storage
== REDIS_VM_MEMORY
);
9798 j
= zmalloc(sizeof(*j
));
9799 j
->type
= REDIS_IOJOB_PREPARE_SWAP
;
9803 j
->id
= j
->val
= val
;
9806 j
->thread
= (pthread_t
) -1;
9807 val
->storage
= REDIS_VM_SWAPPING
;
9815 /* ============ Virtual Memory - Blocking clients on missing keys =========== */
9817 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
9818 * If there is not already a job loading the key, it is craeted.
9819 * The key is added to the io_keys list in the client structure, and also
9820 * in the hash table mapping swapped keys to waiting clients, that is,
9821 * server.io_waited_keys. */
9822 static int waitForSwappedKey(redisClient
*c
, robj
*key
) {
9823 struct dictEntry
*de
;
9827 /* If the key does not exist or is already in RAM we don't need to
9828 * block the client at all. */
9829 de
= dictFind(c
->db
->dict
,key
);
9830 if (de
== NULL
) return 0;
9831 o
= dictGetEntryVal(de
);
9832 if (o
->storage
== REDIS_VM_MEMORY
) {
9834 } else if (o
->storage
== REDIS_VM_SWAPPING
) {
9835 /* We were swapping the key, undo it! */
9836 vmCancelThreadedIOJob(o
);
9840 /* OK: the key is either swapped, or being loaded just now. */
9842 /* Add the key to the list of keys this client is waiting for.
9843 * This maps clients to keys they are waiting for. */
9844 listAddNodeTail(c
->io_keys
,key
);
9847 /* Add the client to the swapped keys => clients waiting map. */
9848 de
= dictFind(c
->db
->io_keys
,key
);
9852 /* For every key we take a list of clients blocked for it */
9854 retval
= dictAdd(c
->db
->io_keys
,key
,l
);
9856 assert(retval
== DICT_OK
);
9858 l
= dictGetEntryVal(de
);
9860 listAddNodeTail(l
,c
);
9862 /* Are we already loading the key from disk? If not create a job */
9863 if (o
->storage
== REDIS_VM_SWAPPED
) {
9865 vmpointer
*vp
= (vmpointer
*)o
;
9867 o
->storage
= REDIS_VM_LOADING
;
9868 j
= zmalloc(sizeof(*j
));
9869 j
->type
= REDIS_IOJOB_LOAD
;
9877 j
->thread
= (pthread_t
) -1;
9885 /* Preload keys for any command with first, last and step values for
9886 * the command keys prototype, as defined in the command table. */
9887 static void waitForMultipleSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
9889 if (cmd
->vm_firstkey
== 0) return;
9890 last
= cmd
->vm_lastkey
;
9891 if (last
< 0) last
= argc
+last
;
9892 for (j
= cmd
->vm_firstkey
; j
<= last
; j
+= cmd
->vm_keystep
) {
9893 redisAssert(j
< argc
);
9894 waitForSwappedKey(c
,argv
[j
]);
9898 /* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
9899 * Note that the number of keys to preload is user-defined, so we need to
9900 * apply a sanity check against argc. */
9901 static void zunionInterBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
9905 num
= atoi(argv
[2]->ptr
);
9906 if (num
> (argc
-3)) return;
9907 for (i
= 0; i
< num
; i
++) {
9908 waitForSwappedKey(c
,argv
[3+i
]);
9912 /* Preload keys needed to execute the entire MULTI/EXEC block.
9914 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
9915 * and will block the client when any command requires a swapped out value. */
9916 static void execBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
9918 struct redisCommand
*mcmd
;
9921 REDIS_NOTUSED(argc
);
9922 REDIS_NOTUSED(argv
);
9924 if (!(c
->flags
& REDIS_MULTI
)) return;
9925 for (i
= 0; i
< c
->mstate
.count
; i
++) {
9926 mcmd
= c
->mstate
.commands
[i
].cmd
;
9927 margc
= c
->mstate
.commands
[i
].argc
;
9928 margv
= c
->mstate
.commands
[i
].argv
;
9930 if (mcmd
->vm_preload_proc
!= NULL
) {
9931 mcmd
->vm_preload_proc(c
,mcmd
,margc
,margv
);
9933 waitForMultipleSwappedKeys(c
,mcmd
,margc
,margv
);
9938 /* Is this client attempting to run a command against swapped keys?
9939 * If so, block it ASAP, load the keys in background, then resume it.
9941 * The important idea about this function is that it can fail! If keys will
9942 * still be swapped when the client is resumed, this key lookups will
9943 * just block loading keys from disk. In practical terms this should only
9944 * happen with SORT BY command or if there is a bug in this function.
9946 * Return 1 if the client is marked as blocked, 0 if the client can
9947 * continue as the keys it is going to access appear to be in memory. */
9948 static int blockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
) {
9949 if (cmd
->vm_preload_proc
!= NULL
) {
9950 cmd
->vm_preload_proc(c
,cmd
,c
->argc
,c
->argv
);
9952 waitForMultipleSwappedKeys(c
,cmd
,c
->argc
,c
->argv
);
9955 /* If the client was blocked for at least one key, mark it as blocked. */
9956 if (listLength(c
->io_keys
)) {
9957 c
->flags
|= REDIS_IO_WAIT
;
9958 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
9959 server
.vm_blocked_clients
++;
9966 /* Remove the 'key' from the list of blocked keys for a given client.
9968 * The function returns 1 when there are no longer blocking keys after
9969 * the current one was removed (and the client can be unblocked). */
9970 static int dontWaitForSwappedKey(redisClient
*c
, robj
*key
) {
9974 struct dictEntry
*de
;
9976 /* Remove the key from the list of keys this client is waiting for. */
9977 listRewind(c
->io_keys
,&li
);
9978 while ((ln
= listNext(&li
)) != NULL
) {
9979 if (equalStringObjects(ln
->value
,key
)) {
9980 listDelNode(c
->io_keys
,ln
);
9986 /* Remove the client form the key => waiting clients map. */
9987 de
= dictFind(c
->db
->io_keys
,key
);
9989 l
= dictGetEntryVal(de
);
9990 ln
= listSearchKey(l
,c
);
9993 if (listLength(l
) == 0)
9994 dictDelete(c
->db
->io_keys
,key
);
9996 return listLength(c
->io_keys
) == 0;
9999 /* Every time we now a key was loaded back in memory, we handle clients
10000 * waiting for this key if any. */
10001 static void handleClientsBlockedOnSwappedKey(redisDb
*db
, robj
*key
) {
10002 struct dictEntry
*de
;
10007 de
= dictFind(db
->io_keys
,key
);
10010 l
= dictGetEntryVal(de
);
10011 len
= listLength(l
);
10012 /* Note: we can't use something like while(listLength(l)) as the list
10013 * can be freed by the calling function when we remove the last element. */
10016 redisClient
*c
= ln
->value
;
10018 if (dontWaitForSwappedKey(c
,key
)) {
10019 /* Put the client in the list of clients ready to go as we
10020 * loaded all the keys about it. */
10021 listAddNodeTail(server
.io_ready_clients
,c
);
10026 /* =========================== Remote Configuration ========================= */
10028 static void configSetCommand(redisClient
*c
) {
10029 robj
*o
= getDecodedObject(c
->argv
[3]);
10032 if (!strcasecmp(c
->argv
[2]->ptr
,"dbfilename")) {
10033 zfree(server
.dbfilename
);
10034 server
.dbfilename
= zstrdup(o
->ptr
);
10035 } else if (!strcasecmp(c
->argv
[2]->ptr
,"requirepass")) {
10036 zfree(server
.requirepass
);
10037 server
.requirepass
= zstrdup(o
->ptr
);
10038 } else if (!strcasecmp(c
->argv
[2]->ptr
,"masterauth")) {
10039 zfree(server
.masterauth
);
10040 server
.masterauth
= zstrdup(o
->ptr
);
10041 } else if (!strcasecmp(c
->argv
[2]->ptr
,"maxmemory")) {
10042 if (getLongLongFromObject(o
,&ll
) == REDIS_ERR
||
10043 ll
< 0) goto badfmt
;
10044 server
.maxmemory
= ll
;
10045 } else if (!strcasecmp(c
->argv
[2]->ptr
,"timeout")) {
10046 if (getLongLongFromObject(o
,&ll
) == REDIS_ERR
||
10047 ll
< 0 || ll
> LONG_MAX
) goto badfmt
;
10048 server
.maxidletime
= ll
;
10049 } else if (!strcasecmp(c
->argv
[2]->ptr
,"appendfsync")) {
10050 if (!strcasecmp(o
->ptr
,"no")) {
10051 server
.appendfsync
= APPENDFSYNC_NO
;
10052 } else if (!strcasecmp(o
->ptr
,"everysec")) {
10053 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
10054 } else if (!strcasecmp(o
->ptr
,"always")) {
10055 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
10059 } else if (!strcasecmp(c
->argv
[2]->ptr
,"no-appendfsync-on-rewrite")) {
10060 int yn
= yesnotoi(o
->ptr
);
10062 if (yn
== -1) goto badfmt
;
10063 server
.no_appendfsync_on_rewrite
= yn
;
10064 } else if (!strcasecmp(c
->argv
[2]->ptr
,"appendonly")) {
10065 int old
= server
.appendonly
;
10066 int new = yesnotoi(o
->ptr
);
10068 if (new == -1) goto badfmt
;
10073 if (startAppendOnly() == REDIS_ERR
) {
10074 addReplySds(c
,sdscatprintf(sdsempty(),
10075 "-ERR Unable to turn on AOF. Check server logs.\r\n"));
10081 } else if (!strcasecmp(c
->argv
[2]->ptr
,"save")) {
10083 sds
*v
= sdssplitlen(o
->ptr
,sdslen(o
->ptr
)," ",1,&vlen
);
10085 /* Perform sanity check before setting the new config:
10086 * - Even number of args
10087 * - Seconds >= 1, changes >= 0 */
10089 sdsfreesplitres(v
,vlen
);
10092 for (j
= 0; j
< vlen
; j
++) {
10096 val
= strtoll(v
[j
], &eptr
, 10);
10097 if (eptr
[0] != '\0' ||
10098 ((j
& 1) == 0 && val
< 1) ||
10099 ((j
& 1) == 1 && val
< 0)) {
10100 sdsfreesplitres(v
,vlen
);
10104 /* Finally set the new config */
10105 resetServerSaveParams();
10106 for (j
= 0; j
< vlen
; j
+= 2) {
10110 seconds
= strtoll(v
[j
],NULL
,10);
10111 changes
= strtoll(v
[j
+1],NULL
,10);
10112 appendServerSaveParams(seconds
, changes
);
10114 sdsfreesplitres(v
,vlen
);
10116 addReplySds(c
,sdscatprintf(sdsempty(),
10117 "-ERR not supported CONFIG parameter %s\r\n",
10118 (char*)c
->argv
[2]->ptr
));
10123 addReply(c
,shared
.ok
);
10126 badfmt
: /* Bad format errors */
10127 addReplySds(c
,sdscatprintf(sdsempty(),
10128 "-ERR invalid argument '%s' for CONFIG SET '%s'\r\n",
10130 (char*)c
->argv
[2]->ptr
));
10134 static void configGetCommand(redisClient
*c
) {
10135 robj
*o
= getDecodedObject(c
->argv
[2]);
10136 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
10137 char *pattern
= o
->ptr
;
10140 addReply(c
,lenobj
);
10141 decrRefCount(lenobj
);
10143 if (stringmatch(pattern
,"dbfilename",0)) {
10144 addReplyBulkCString(c
,"dbfilename");
10145 addReplyBulkCString(c
,server
.dbfilename
);
10148 if (stringmatch(pattern
,"requirepass",0)) {
10149 addReplyBulkCString(c
,"requirepass");
10150 addReplyBulkCString(c
,server
.requirepass
);
10153 if (stringmatch(pattern
,"masterauth",0)) {
10154 addReplyBulkCString(c
,"masterauth");
10155 addReplyBulkCString(c
,server
.masterauth
);
10158 if (stringmatch(pattern
,"maxmemory",0)) {
10161 ll2string(buf
,128,server
.maxmemory
);
10162 addReplyBulkCString(c
,"maxmemory");
10163 addReplyBulkCString(c
,buf
);
10166 if (stringmatch(pattern
,"timeout",0)) {
10169 ll2string(buf
,128,server
.maxidletime
);
10170 addReplyBulkCString(c
,"timeout");
10171 addReplyBulkCString(c
,buf
);
10174 if (stringmatch(pattern
,"appendonly",0)) {
10175 addReplyBulkCString(c
,"appendonly");
10176 addReplyBulkCString(c
,server
.appendonly
? "yes" : "no");
10179 if (stringmatch(pattern
,"no-appendfsync-on-rewrite",0)) {
10180 addReplyBulkCString(c
,"no-appendfsync-on-rewrite");
10181 addReplyBulkCString(c
,server
.no_appendfsync_on_rewrite
? "yes" : "no");
10184 if (stringmatch(pattern
,"appendfsync",0)) {
10187 switch(server
.appendfsync
) {
10188 case APPENDFSYNC_NO
: policy
= "no"; break;
10189 case APPENDFSYNC_EVERYSEC
: policy
= "everysec"; break;
10190 case APPENDFSYNC_ALWAYS
: policy
= "always"; break;
10191 default: policy
= "unknown"; break; /* too harmless to panic */
10193 addReplyBulkCString(c
,"appendfsync");
10194 addReplyBulkCString(c
,policy
);
10197 if (stringmatch(pattern
,"save",0)) {
10198 sds buf
= sdsempty();
10201 for (j
= 0; j
< server
.saveparamslen
; j
++) {
10202 buf
= sdscatprintf(buf
,"%ld %d",
10203 server
.saveparams
[j
].seconds
,
10204 server
.saveparams
[j
].changes
);
10205 if (j
!= server
.saveparamslen
-1)
10206 buf
= sdscatlen(buf
," ",1);
10208 addReplyBulkCString(c
,"save");
10209 addReplyBulkCString(c
,buf
);
10214 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%d\r\n",matches
*2);
10217 static void configCommand(redisClient
*c
) {
10218 if (!strcasecmp(c
->argv
[1]->ptr
,"set")) {
10219 if (c
->argc
!= 4) goto badarity
;
10220 configSetCommand(c
);
10221 } else if (!strcasecmp(c
->argv
[1]->ptr
,"get")) {
10222 if (c
->argc
!= 3) goto badarity
;
10223 configGetCommand(c
);
10224 } else if (!strcasecmp(c
->argv
[1]->ptr
,"resetstat")) {
10225 if (c
->argc
!= 2) goto badarity
;
10226 server
.stat_numcommands
= 0;
10227 server
.stat_numconnections
= 0;
10228 server
.stat_expiredkeys
= 0;
10229 server
.stat_starttime
= time(NULL
);
10230 addReply(c
,shared
.ok
);
10232 addReplySds(c
,sdscatprintf(sdsempty(),
10233 "-ERR CONFIG subcommand must be one of GET, SET, RESETSTAT\r\n"));
10238 addReplySds(c
,sdscatprintf(sdsempty(),
10239 "-ERR Wrong number of arguments for CONFIG %s\r\n",
10240 (char*) c
->argv
[1]->ptr
));
10243 /* =========================== Pubsub implementation ======================== */
10245 static void freePubsubPattern(void *p
) {
10246 pubsubPattern
*pat
= p
;
10248 decrRefCount(pat
->pattern
);
10252 static int listMatchPubsubPattern(void *a
, void *b
) {
10253 pubsubPattern
*pa
= a
, *pb
= b
;
10255 return (pa
->client
== pb
->client
) &&
10256 (equalStringObjects(pa
->pattern
,pb
->pattern
));
10259 /* Subscribe a client to a channel. Returns 1 if the operation succeeded, or
10260 * 0 if the client was already subscribed to that channel. */
10261 static int pubsubSubscribeChannel(redisClient
*c
, robj
*channel
) {
10262 struct dictEntry
*de
;
10263 list
*clients
= NULL
;
10266 /* Add the channel to the client -> channels hash table */
10267 if (dictAdd(c
->pubsub_channels
,channel
,NULL
) == DICT_OK
) {
10269 incrRefCount(channel
);
10270 /* Add the client to the channel -> list of clients hash table */
10271 de
= dictFind(server
.pubsub_channels
,channel
);
10273 clients
= listCreate();
10274 dictAdd(server
.pubsub_channels
,channel
,clients
);
10275 incrRefCount(channel
);
10277 clients
= dictGetEntryVal(de
);
10279 listAddNodeTail(clients
,c
);
10281 /* Notify the client */
10282 addReply(c
,shared
.mbulk3
);
10283 addReply(c
,shared
.subscribebulk
);
10284 addReplyBulk(c
,channel
);
10285 addReplyLongLong(c
,dictSize(c
->pubsub_channels
)+listLength(c
->pubsub_patterns
));
10289 /* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10290 * 0 if the client was not subscribed to the specified channel. */
10291 static int pubsubUnsubscribeChannel(redisClient
*c
, robj
*channel
, int notify
) {
10292 struct dictEntry
*de
;
10297 /* Remove the channel from the client -> channels hash table */
10298 incrRefCount(channel
); /* channel may be just a pointer to the same object
10299 we have in the hash tables. Protect it... */
10300 if (dictDelete(c
->pubsub_channels
,channel
) == DICT_OK
) {
10302 /* Remove the client from the channel -> clients list hash table */
10303 de
= dictFind(server
.pubsub_channels
,channel
);
10304 assert(de
!= NULL
);
10305 clients
= dictGetEntryVal(de
);
10306 ln
= listSearchKey(clients
,c
);
10307 assert(ln
!= NULL
);
10308 listDelNode(clients
,ln
);
10309 if (listLength(clients
) == 0) {
10310 /* Free the list and associated hash entry at all if this was
10311 * the latest client, so that it will be possible to abuse
10312 * Redis PUBSUB creating millions of channels. */
10313 dictDelete(server
.pubsub_channels
,channel
);
10316 /* Notify the client */
10318 addReply(c
,shared
.mbulk3
);
10319 addReply(c
,shared
.unsubscribebulk
);
10320 addReplyBulk(c
,channel
);
10321 addReplyLongLong(c
,dictSize(c
->pubsub_channels
)+
10322 listLength(c
->pubsub_patterns
));
10325 decrRefCount(channel
); /* it is finally safe to release it */
10329 /* Subscribe a client to a pattern. Returns 1 if the operation succeeded, or 0 if the clinet was already subscribed to that pattern. */
10330 static int pubsubSubscribePattern(redisClient
*c
, robj
*pattern
) {
10333 if (listSearchKey(c
->pubsub_patterns
,pattern
) == NULL
) {
10335 pubsubPattern
*pat
;
10336 listAddNodeTail(c
->pubsub_patterns
,pattern
);
10337 incrRefCount(pattern
);
10338 pat
= zmalloc(sizeof(*pat
));
10339 pat
->pattern
= getDecodedObject(pattern
);
10341 listAddNodeTail(server
.pubsub_patterns
,pat
);
10343 /* Notify the client */
10344 addReply(c
,shared
.mbulk3
);
10345 addReply(c
,shared
.psubscribebulk
);
10346 addReplyBulk(c
,pattern
);
10347 addReplyLongLong(c
,dictSize(c
->pubsub_channels
)+listLength(c
->pubsub_patterns
));
10351 /* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10352 * 0 if the client was not subscribed to the specified channel. */
10353 static int pubsubUnsubscribePattern(redisClient
*c
, robj
*pattern
, int notify
) {
10358 incrRefCount(pattern
); /* Protect the object. May be the same we remove */
10359 if ((ln
= listSearchKey(c
->pubsub_patterns
,pattern
)) != NULL
) {
10361 listDelNode(c
->pubsub_patterns
,ln
);
10363 pat
.pattern
= pattern
;
10364 ln
= listSearchKey(server
.pubsub_patterns
,&pat
);
10365 listDelNode(server
.pubsub_patterns
,ln
);
10367 /* Notify the client */
10369 addReply(c
,shared
.mbulk3
);
10370 addReply(c
,shared
.punsubscribebulk
);
10371 addReplyBulk(c
,pattern
);
10372 addReplyLongLong(c
,dictSize(c
->pubsub_channels
)+
10373 listLength(c
->pubsub_patterns
));
10375 decrRefCount(pattern
);
10379 /* Unsubscribe from all the channels. Return the number of channels the
10380 * client was subscribed from. */
10381 static int pubsubUnsubscribeAllChannels(redisClient
*c
, int notify
) {
10382 dictIterator
*di
= dictGetIterator(c
->pubsub_channels
);
10386 while((de
= dictNext(di
)) != NULL
) {
10387 robj
*channel
= dictGetEntryKey(de
);
10389 count
+= pubsubUnsubscribeChannel(c
,channel
,notify
);
10391 dictReleaseIterator(di
);
10395 /* Unsubscribe from all the patterns. Return the number of patterns the
10396 * client was subscribed from. */
10397 static int pubsubUnsubscribeAllPatterns(redisClient
*c
, int notify
) {
10402 listRewind(c
->pubsub_patterns
,&li
);
10403 while ((ln
= listNext(&li
)) != NULL
) {
10404 robj
*pattern
= ln
->value
;
10406 count
+= pubsubUnsubscribePattern(c
,pattern
,notify
);
10411 /* Publish a message */
10412 static int pubsubPublishMessage(robj
*channel
, robj
*message
) {
10414 struct dictEntry
*de
;
10418 /* Send to clients listening for that channel */
10419 de
= dictFind(server
.pubsub_channels
,channel
);
10421 list
*list
= dictGetEntryVal(de
);
10425 listRewind(list
,&li
);
10426 while ((ln
= listNext(&li
)) != NULL
) {
10427 redisClient
*c
= ln
->value
;
10429 addReply(c
,shared
.mbulk3
);
10430 addReply(c
,shared
.messagebulk
);
10431 addReplyBulk(c
,channel
);
10432 addReplyBulk(c
,message
);
10436 /* Send to clients listening to matching channels */
10437 if (listLength(server
.pubsub_patterns
)) {
10438 listRewind(server
.pubsub_patterns
,&li
);
10439 channel
= getDecodedObject(channel
);
10440 while ((ln
= listNext(&li
)) != NULL
) {
10441 pubsubPattern
*pat
= ln
->value
;
10443 if (stringmatchlen((char*)pat
->pattern
->ptr
,
10444 sdslen(pat
->pattern
->ptr
),
10445 (char*)channel
->ptr
,
10446 sdslen(channel
->ptr
),0)) {
10447 addReply(pat
->client
,shared
.mbulk4
);
10448 addReply(pat
->client
,shared
.pmessagebulk
);
10449 addReplyBulk(pat
->client
,pat
->pattern
);
10450 addReplyBulk(pat
->client
,channel
);
10451 addReplyBulk(pat
->client
,message
);
10455 decrRefCount(channel
);
10460 static void subscribeCommand(redisClient
*c
) {
10463 for (j
= 1; j
< c
->argc
; j
++)
10464 pubsubSubscribeChannel(c
,c
->argv
[j
]);
10467 static void unsubscribeCommand(redisClient
*c
) {
10468 if (c
->argc
== 1) {
10469 pubsubUnsubscribeAllChannels(c
,1);
10474 for (j
= 1; j
< c
->argc
; j
++)
10475 pubsubUnsubscribeChannel(c
,c
->argv
[j
],1);
10479 static void psubscribeCommand(redisClient
*c
) {
10482 for (j
= 1; j
< c
->argc
; j
++)
10483 pubsubSubscribePattern(c
,c
->argv
[j
]);
10486 static void punsubscribeCommand(redisClient
*c
) {
10487 if (c
->argc
== 1) {
10488 pubsubUnsubscribeAllPatterns(c
,1);
10493 for (j
= 1; j
< c
->argc
; j
++)
10494 pubsubUnsubscribePattern(c
,c
->argv
[j
],1);
10498 static void publishCommand(redisClient
*c
) {
10499 int receivers
= pubsubPublishMessage(c
->argv
[1],c
->argv
[2]);
10500 addReplyLongLong(c
,receivers
);
10503 /* ===================== WATCH (CAS alike for MULTI/EXEC) ===================
10505 * The implementation uses a per-DB hash table mapping keys to list of clients
10506 * WATCHing those keys, so that given a key that is going to be modified
10507 * we can mark all the associated clients as dirty.
10509 * Also every client contains a list of WATCHed keys so that's possible to
10510 * un-watch such keys when the client is freed or when UNWATCH is called. */
10512 /* In the client->watched_keys list we need to use watchedKey structures
10513 * as in order to identify a key in Redis we need both the key name and the
10515 typedef struct watchedKey
{
10520 /* Watch for the specified key */
10521 static void watchForKey(redisClient
*c
, robj
*key
) {
10522 list
*clients
= NULL
;
10527 /* Check if we are already watching for this key */
10528 listRewind(c
->watched_keys
,&li
);
10529 while((ln
= listNext(&li
))) {
10530 wk
= listNodeValue(ln
);
10531 if (wk
->db
== c
->db
&& equalStringObjects(key
,wk
->key
))
10532 return; /* Key already watched */
10534 /* This key is not already watched in this DB. Let's add it */
10535 clients
= dictFetchValue(c
->db
->watched_keys
,key
);
10537 clients
= listCreate();
10538 dictAdd(c
->db
->watched_keys
,key
,clients
);
10541 listAddNodeTail(clients
,c
);
10542 /* Add the new key to the lits of keys watched by this client */
10543 wk
= zmalloc(sizeof(*wk
));
10547 listAddNodeTail(c
->watched_keys
,wk
);
10550 /* Unwatch all the keys watched by this client. To clean the EXEC dirty
10551 * flag is up to the caller. */
10552 static void unwatchAllKeys(redisClient
*c
) {
10556 if (listLength(c
->watched_keys
) == 0) return;
10557 listRewind(c
->watched_keys
,&li
);
10558 while((ln
= listNext(&li
))) {
10562 /* Lookup the watched key -> clients list and remove the client
10564 wk
= listNodeValue(ln
);
10565 clients
= dictFetchValue(wk
->db
->watched_keys
, wk
->key
);
10566 assert(clients
!= NULL
);
10567 listDelNode(clients
,listSearchKey(clients
,c
));
10568 /* Kill the entry at all if this was the only client */
10569 if (listLength(clients
) == 0)
10570 dictDelete(wk
->db
->watched_keys
, wk
->key
);
10571 /* Remove this watched key from the client->watched list */
10572 listDelNode(c
->watched_keys
,ln
);
10573 decrRefCount(wk
->key
);
10578 /* "Touch" a key, so that if this key is being WATCHed by some client the
10579 * next EXEC will fail. */
10580 static void touchWatchedKey(redisDb
*db
, robj
*key
) {
10585 if (dictSize(db
->watched_keys
) == 0) return;
10586 clients
= dictFetchValue(db
->watched_keys
, key
);
10587 if (!clients
) return;
10589 /* Mark all the clients watching this key as REDIS_DIRTY_CAS */
10590 /* Check if we are already watching for this key */
10591 listRewind(clients
,&li
);
10592 while((ln
= listNext(&li
))) {
10593 redisClient
*c
= listNodeValue(ln
);
10595 c
->flags
|= REDIS_DIRTY_CAS
;
10599 /* On FLUSHDB or FLUSHALL all the watched keys that are present before the
10600 * flush but will be deleted as effect of the flushing operation should
10601 * be touched. "dbid" is the DB that's getting the flush. -1 if it is
10602 * a FLUSHALL operation (all the DBs flushed). */
10603 static void touchWatchedKeysOnFlush(int dbid
) {
10607 /* For every client, check all the waited keys */
10608 listRewind(server
.clients
,&li1
);
10609 while((ln
= listNext(&li1
))) {
10610 redisClient
*c
= listNodeValue(ln
);
10611 listRewind(c
->watched_keys
,&li2
);
10612 while((ln
= listNext(&li2
))) {
10613 watchedKey
*wk
= listNodeValue(ln
);
10615 /* For every watched key matching the specified DB, if the
10616 * key exists, mark the client as dirty, as the key will be
10618 if (dbid
== -1 || wk
->db
->id
== dbid
) {
10619 if (dictFind(wk
->db
->dict
, wk
->key
) != NULL
)
10620 c
->flags
|= REDIS_DIRTY_CAS
;
10626 static void watchCommand(redisClient
*c
) {
10629 if (c
->flags
& REDIS_MULTI
) {
10630 addReplySds(c
,sdsnew("-ERR WATCH inside MULTI is not allowed\r\n"));
10633 for (j
= 1; j
< c
->argc
; j
++)
10634 watchForKey(c
,c
->argv
[j
]);
10635 addReply(c
,shared
.ok
);
10638 static void unwatchCommand(redisClient
*c
) {
10640 c
->flags
&= (~REDIS_DIRTY_CAS
);
10641 addReply(c
,shared
.ok
);
10644 /* ================================= Debugging ============================== */
10646 /* Compute the sha1 of string at 's' with 'len' bytes long.
10647 * The SHA1 is then xored againt the string pointed by digest.
10648 * Since xor is commutative, this operation is used in order to
10649 * "add" digests relative to unordered elements.
10651 * So digest(a,b,c,d) will be the same of digest(b,a,c,d) */
10652 static void xorDigest(unsigned char *digest
, void *ptr
, size_t len
) {
10654 unsigned char hash
[20], *s
= ptr
;
10658 SHA1Update(&ctx
,s
,len
);
10659 SHA1Final(hash
,&ctx
);
10661 for (j
= 0; j
< 20; j
++)
10662 digest
[j
] ^= hash
[j
];
10665 static void xorObjectDigest(unsigned char *digest
, robj
*o
) {
10666 o
= getDecodedObject(o
);
10667 xorDigest(digest
,o
->ptr
,sdslen(o
->ptr
));
10671 /* This function instead of just computing the SHA1 and xoring it
10672 * against diget, also perform the digest of "digest" itself and
10673 * replace the old value with the new one.
10675 * So the final digest will be:
10677 * digest = SHA1(digest xor SHA1(data))
10679 * This function is used every time we want to preserve the order so
10680 * that digest(a,b,c,d) will be different than digest(b,c,d,a)
10682 * Also note that mixdigest("foo") followed by mixdigest("bar")
10683 * will lead to a different digest compared to "fo", "obar".
10685 static void mixDigest(unsigned char *digest
, void *ptr
, size_t len
) {
10689 xorDigest(digest
,s
,len
);
10691 SHA1Update(&ctx
,digest
,20);
10692 SHA1Final(digest
,&ctx
);
10695 static void mixObjectDigest(unsigned char *digest
, robj
*o
) {
10696 o
= getDecodedObject(o
);
10697 mixDigest(digest
,o
->ptr
,sdslen(o
->ptr
));
10701 /* Compute the dataset digest. Since keys, sets elements, hashes elements
10702 * are not ordered, we use a trick: every aggregate digest is the xor
10703 * of the digests of their elements. This way the order will not change
10704 * the result. For list instead we use a feedback entering the output digest
10705 * as input in order to ensure that a different ordered list will result in
10706 * a different digest. */
10707 static void computeDatasetDigest(unsigned char *final
) {
10708 unsigned char digest
[20];
10710 dictIterator
*di
= NULL
;
10715 memset(final
,0,20); /* Start with a clean result */
10717 for (j
= 0; j
< server
.dbnum
; j
++) {
10718 redisDb
*db
= server
.db
+j
;
10720 if (dictSize(db
->dict
) == 0) continue;
10721 di
= dictGetIterator(db
->dict
);
10723 /* hash the DB id, so the same dataset moved in a different
10724 * DB will lead to a different digest */
10726 mixDigest(final
,&aux
,sizeof(aux
));
10728 /* Iterate this DB writing every entry */
10729 while((de
= dictNext(di
)) != NULL
) {
10730 robj
*key
, *o
, *kcopy
;
10733 memset(digest
,0,20); /* This key-val digest */
10734 key
= dictGetEntryKey(de
);
10736 if (!server
.vm_enabled
) {
10737 mixObjectDigest(digest
,key
);
10738 o
= dictGetEntryVal(de
);
10740 /* Don't work with the key directly as when VM is active
10741 * this is unsafe: TODO: fix decrRefCount to check if the
10742 * count really reached 0 to avoid this mess */
10743 kcopy
= dupStringObject(key
);
10744 mixObjectDigest(digest
,kcopy
);
10745 o
= lookupKeyRead(db
,kcopy
);
10746 decrRefCount(kcopy
);
10748 aux
= htonl(o
->type
);
10749 mixDigest(digest
,&aux
,sizeof(aux
));
10750 expiretime
= getExpire(db
,key
);
10752 /* Save the key and associated value */
10753 if (o
->type
== REDIS_STRING
) {
10754 mixObjectDigest(digest
,o
);
10755 } else if (o
->type
== REDIS_LIST
) {
10756 list
*list
= o
->ptr
;
10760 listRewind(list
,&li
);
10761 while((ln
= listNext(&li
))) {
10762 robj
*eleobj
= listNodeValue(ln
);
10764 mixObjectDigest(digest
,eleobj
);
10766 } else if (o
->type
== REDIS_SET
) {
10767 dict
*set
= o
->ptr
;
10768 dictIterator
*di
= dictGetIterator(set
);
10771 while((de
= dictNext(di
)) != NULL
) {
10772 robj
*eleobj
= dictGetEntryKey(de
);
10774 xorObjectDigest(digest
,eleobj
);
10776 dictReleaseIterator(di
);
10777 } else if (o
->type
== REDIS_ZSET
) {
10779 dictIterator
*di
= dictGetIterator(zs
->dict
);
10782 while((de
= dictNext(di
)) != NULL
) {
10783 robj
*eleobj
= dictGetEntryKey(de
);
10784 double *score
= dictGetEntryVal(de
);
10785 unsigned char eledigest
[20];
10787 snprintf(buf
,sizeof(buf
),"%.17g",*score
);
10788 memset(eledigest
,0,20);
10789 mixObjectDigest(eledigest
,eleobj
);
10790 mixDigest(eledigest
,buf
,strlen(buf
));
10791 xorDigest(digest
,eledigest
,20);
10793 dictReleaseIterator(di
);
10794 } else if (o
->type
== REDIS_HASH
) {
10798 hi
= hashInitIterator(o
);
10799 while (hashNext(hi
) != REDIS_ERR
) {
10800 unsigned char eledigest
[20];
10802 memset(eledigest
,0,20);
10803 obj
= hashCurrent(hi
,REDIS_HASH_KEY
);
10804 mixObjectDigest(eledigest
,obj
);
10806 obj
= hashCurrent(hi
,REDIS_HASH_VALUE
);
10807 mixObjectDigest(eledigest
,obj
);
10809 xorDigest(digest
,eledigest
,20);
10811 hashReleaseIterator(hi
);
10813 redisPanic("Unknown object type");
10815 /* If the key has an expire, add it to the mix */
10816 if (expiretime
!= -1) xorDigest(digest
,"!!expire!!",10);
10817 /* We can finally xor the key-val digest to the final digest */
10818 xorDigest(final
,digest
,20);
10820 dictReleaseIterator(di
);
10824 static void debugCommand(redisClient
*c
) {
10825 if (!strcasecmp(c
->argv
[1]->ptr
,"segfault")) {
10826 *((char*)-1) = 'x';
10827 } else if (!strcasecmp(c
->argv
[1]->ptr
,"reload")) {
10828 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
10829 addReply(c
,shared
.err
);
10833 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
10834 addReply(c
,shared
.err
);
10837 redisLog(REDIS_WARNING
,"DB reloaded by DEBUG RELOAD");
10838 addReply(c
,shared
.ok
);
10839 } else if (!strcasecmp(c
->argv
[1]->ptr
,"loadaof")) {
10841 if (loadAppendOnlyFile(server
.appendfilename
) != REDIS_OK
) {
10842 addReply(c
,shared
.err
);
10845 redisLog(REDIS_WARNING
,"Append Only File loaded by DEBUG LOADAOF");
10846 addReply(c
,shared
.ok
);
10847 } else if (!strcasecmp(c
->argv
[1]->ptr
,"object") && c
->argc
== 3) {
10848 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
10852 addReply(c
,shared
.nokeyerr
);
10855 key
= dictGetEntryKey(de
);
10856 val
= dictGetEntryVal(de
);
10857 if (!server
.vm_enabled
|| (val
->storage
== REDIS_VM_MEMORY
||
10858 val
->storage
== REDIS_VM_SWAPPING
)) {
10862 if (val
->encoding
< (sizeof(strencoding
)/sizeof(char*))) {
10863 strenc
= strencoding
[val
->encoding
];
10865 snprintf(buf
,64,"unknown encoding %d\n", val
->encoding
);
10868 addReplySds(c
,sdscatprintf(sdsempty(),
10869 "+Key at:%p refcount:%d, value at:%p refcount:%d "
10870 "encoding:%s serializedlength:%lld\r\n",
10871 (void*)key
, key
->refcount
, (void*)val
, val
->refcount
,
10872 strenc
, (long long) rdbSavedObjectLen(val
,NULL
)));
10874 vmpointer
*vp
= (vmpointer
*) val
;
10875 addReplySds(c
,sdscatprintf(sdsempty(),
10876 "+Key at:%p refcount:%d, value swapped at: page %llu "
10877 "using %llu pages\r\n",
10878 (void*)key
, key
->refcount
, (unsigned long long) vp
->page
,
10879 (unsigned long long) vp
->usedpages
));
10881 } else if (!strcasecmp(c
->argv
[1]->ptr
,"swapin") && c
->argc
== 3) {
10882 lookupKeyRead(c
->db
,c
->argv
[2]);
10883 addReply(c
,shared
.ok
);
10884 } else if (!strcasecmp(c
->argv
[1]->ptr
,"swapout") && c
->argc
== 3) {
10885 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
10889 if (!server
.vm_enabled
) {
10890 addReplySds(c
,sdsnew("-ERR Virtual Memory is disabled\r\n"));
10894 addReply(c
,shared
.nokeyerr
);
10897 key
= dictGetEntryKey(de
);
10898 val
= dictGetEntryVal(de
);
10900 if (val
->storage
!= REDIS_VM_MEMORY
) {
10901 addReplySds(c
,sdsnew("-ERR This key is not in memory\r\n"));
10902 } else if (val
->refcount
!= 1) {
10903 addReplySds(c
,sdsnew("-ERR Object is shared\r\n"));
10904 } else if ((vp
= vmSwapObjectBlocking(val
)) != NULL
) {
10905 dictGetEntryVal(de
) = vp
;
10906 addReply(c
,shared
.ok
);
10908 addReply(c
,shared
.err
);
10910 } else if (!strcasecmp(c
->argv
[1]->ptr
,"populate") && c
->argc
== 3) {
10915 if (getLongFromObjectOrReply(c
, c
->argv
[2], &keys
, NULL
) != REDIS_OK
)
10917 for (j
= 0; j
< keys
; j
++) {
10918 snprintf(buf
,sizeof(buf
),"key:%lu",j
);
10919 key
= createStringObject(buf
,strlen(buf
));
10920 if (lookupKeyRead(c
->db
,key
) != NULL
) {
10924 snprintf(buf
,sizeof(buf
),"value:%lu",j
);
10925 val
= createStringObject(buf
,strlen(buf
));
10926 dictAdd(c
->db
->dict
,key
,val
);
10928 addReply(c
,shared
.ok
);
10929 } else if (!strcasecmp(c
->argv
[1]->ptr
,"digest") && c
->argc
== 2) {
10930 unsigned char digest
[20];
10931 sds d
= sdsnew("+");
10934 computeDatasetDigest(digest
);
10935 for (j
= 0; j
< 20; j
++)
10936 d
= sdscatprintf(d
, "%02x",digest
[j
]);
10938 d
= sdscatlen(d
,"\r\n",2);
10941 addReplySds(c
,sdsnew(
10942 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPIN <key>|SWAPOUT <key>|RELOAD]\r\n"));
10946 static void _redisAssert(char *estr
, char *file
, int line
) {
10947 redisLog(REDIS_WARNING
,"=== ASSERTION FAILED ===");
10948 redisLog(REDIS_WARNING
,"==> %s:%d '%s' is not true",file
,line
,estr
);
10949 #ifdef HAVE_BACKTRACE
10950 redisLog(REDIS_WARNING
,"(forcing SIGSEGV in order to print the stack trace)");
10951 *((char*)-1) = 'x';
10955 static void _redisPanic(char *msg
, char *file
, int line
) {
10956 redisLog(REDIS_WARNING
,"!!! Software Failure. Press left mouse button to continue");
10957 redisLog(REDIS_WARNING
,"Guru Meditation: %s #%s:%d",msg
,file
,line
);
10958 #ifdef HAVE_BACKTRACE
10959 redisLog(REDIS_WARNING
,"(forcing SIGSEGV in order to print the stack trace)");
10960 *((char*)-1) = 'x';
10964 /* =================================== Main! ================================ */
10967 int linuxOvercommitMemoryValue(void) {
10968 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
10971 if (!fp
) return -1;
10972 if (fgets(buf
,64,fp
) == NULL
) {
10981 void linuxOvercommitMemoryWarning(void) {
10982 if (linuxOvercommitMemoryValue() == 0) {
10983 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.");
10986 #endif /* __linux__ */
10988 static void daemonize(void) {
10992 if (fork() != 0) exit(0); /* parent exits */
10993 setsid(); /* create a new session */
10995 /* Every output goes to /dev/null. If Redis is daemonized but
10996 * the 'logfile' is set to 'stdout' in the configuration file
10997 * it will not log at all. */
10998 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
10999 dup2(fd
, STDIN_FILENO
);
11000 dup2(fd
, STDOUT_FILENO
);
11001 dup2(fd
, STDERR_FILENO
);
11002 if (fd
> STDERR_FILENO
) close(fd
);
11004 /* Try to write the pid file */
11005 fp
= fopen(server
.pidfile
,"w");
11007 fprintf(fp
,"%d\n",getpid());
11012 static void version() {
11013 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION
,
11014 REDIS_GIT_SHA1
, atoi(REDIS_GIT_DIRTY
) > 0);
11018 static void usage() {
11019 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
11020 fprintf(stderr
," ./redis-server - (read config from stdin)\n");
11024 int main(int argc
, char **argv
) {
11027 initServerConfig();
11028 sortCommandTable();
11030 if (strcmp(argv
[1], "-v") == 0 ||
11031 strcmp(argv
[1], "--version") == 0) version();
11032 if (strcmp(argv
[1], "--help") == 0) usage();
11033 resetServerSaveParams();
11034 loadServerConfig(argv
[1]);
11035 } else if ((argc
> 2)) {
11038 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'");
11040 if (server
.daemonize
) daemonize();
11042 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
11044 linuxOvercommitMemoryWarning();
11046 start
= time(NULL
);
11047 if (server
.appendonly
) {
11048 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
11049 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %ld seconds",time(NULL
)-start
);
11051 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
11052 redisLog(REDIS_NOTICE
,"DB loaded from disk: %ld seconds",time(NULL
)-start
);
11054 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
11055 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
11057 aeDeleteEventLoop(server
.el
);
11061 /* ============================= Backtrace support ========================= */
11063 #ifdef HAVE_BACKTRACE
11064 static char *findFuncName(void *pointer
, unsigned long *offset
);
11066 static void *getMcontextEip(ucontext_t
*uc
) {
11067 #if defined(__FreeBSD__)
11068 return (void*) uc
->uc_mcontext
.mc_eip
;
11069 #elif defined(__dietlibc__)
11070 return (void*) uc
->uc_mcontext
.eip
;
11071 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
11073 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
11075 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
11077 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
11078 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
11079 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
11081 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
11083 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
11084 return (void*) uc
->uc_mcontext
.gregs
[REG_EIP
]; /* Linux 32/64 bit */
11085 #elif defined(__ia64__) /* Linux IA64 */
11086 return (void*) uc
->uc_mcontext
.sc_ip
;
11092 static void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
11094 char **messages
= NULL
;
11095 int i
, trace_size
= 0;
11096 unsigned long offset
=0;
11097 ucontext_t
*uc
= (ucontext_t
*) secret
;
11099 REDIS_NOTUSED(info
);
11101 redisLog(REDIS_WARNING
,
11102 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
11103 infostring
= genRedisInfoString();
11104 redisLog(REDIS_WARNING
, "%s",infostring
);
11105 /* It's not safe to sdsfree() the returned string under memory
11106 * corruption conditions. Let it leak as we are going to abort */
11108 trace_size
= backtrace(trace
, 100);
11109 /* overwrite sigaction with caller's address */
11110 if (getMcontextEip(uc
) != NULL
) {
11111 trace
[1] = getMcontextEip(uc
);
11113 messages
= backtrace_symbols(trace
, trace_size
);
11115 for (i
=1; i
<trace_size
; ++i
) {
11116 char *fn
= findFuncName(trace
[i
], &offset
), *p
;
11118 p
= strchr(messages
[i
],'+');
11119 if (!fn
|| (p
&& ((unsigned long)strtol(p
+1,NULL
,10)) < offset
)) {
11120 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
11122 redisLog(REDIS_WARNING
,"%d redis-server %p %s + %d", i
, trace
[i
], fn
, (unsigned int)offset
);
11125 /* free(messages); Don't call free() with possibly corrupted memory. */
11129 static void sigtermHandler(int sig
) {
11130 REDIS_NOTUSED(sig
);
11132 redisLog(REDIS_WARNING
,"SIGTERM received, scheduling shutting down...");
11133 server
.shutdown_asap
= 1;
11136 static void setupSigSegvAction(void) {
11137 struct sigaction act
;
11139 sigemptyset (&act
.sa_mask
);
11140 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
11141 * is used. Otherwise, sa_handler is used */
11142 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
11143 act
.sa_sigaction
= segvHandler
;
11144 sigaction (SIGSEGV
, &act
, NULL
);
11145 sigaction (SIGBUS
, &act
, NULL
);
11146 sigaction (SIGFPE
, &act
, NULL
);
11147 sigaction (SIGILL
, &act
, NULL
);
11148 sigaction (SIGBUS
, &act
, NULL
);
11150 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
11151 act
.sa_handler
= sigtermHandler
;
11152 sigaction (SIGTERM
, &act
, NULL
);
11156 #include "staticsymbols.h"
11157 /* This function try to convert a pointer into a function name. It's used in
11158 * oreder to provide a backtrace under segmentation fault that's able to
11159 * display functions declared as static (otherwise the backtrace is useless). */
11160 static char *findFuncName(void *pointer
, unsigned long *offset
){
11162 unsigned long off
, minoff
= 0;
11164 /* Try to match against the Symbol with the smallest offset */
11165 for (i
=0; symsTable
[i
].pointer
; i
++) {
11166 unsigned long lp
= (unsigned long) pointer
;
11168 if (lp
!= (unsigned long)-1 && lp
>= symsTable
[i
].pointer
) {
11169 off
=lp
-symsTable
[i
].pointer
;
11170 if (ret
< 0 || off
< minoff
) {
11176 if (ret
== -1) return NULL
;
11178 return symsTable
[ret
].name
;
11180 #else /* HAVE_BACKTRACE */
11181 static void setupSigSegvAction(void) {
11183 #endif /* HAVE_BACKTRACE */