2 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
8 * * Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * * Neither the name of Redis nor the names of its contributors may be used
14 * to endorse or promote products derived from this software without
15 * specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 * POSSIBILITY OF SUCH DAMAGE.
30 #define REDIS_VERSION "1.3.4"
40 #define __USE_POSIX199309
47 #endif /* HAVE_BACKTRACE */
55 #include <arpa/inet.h>
59 #include <sys/resource.h>
66 #include "solarisfixes.h"
70 #include "ae.h" /* Event driven programming library */
71 #include "sds.h" /* Dynamic safe strings */
72 #include "anet.h" /* Networking the easy way */
73 #include "dict.h" /* Hash tables */
74 #include "adlist.h" /* Linked lists */
75 #include "zmalloc.h" /* total memory usage aware version of malloc/free */
76 #include "lzf.h" /* LZF compression library */
77 #include "pqsort.h" /* Partial qsort for SORT+LIMIT */
84 /* Static server configuration */
85 #define REDIS_SERVERPORT 6379 /* TCP port */
86 #define REDIS_MAXIDLETIME (60*5) /* default client timeout */
87 #define REDIS_IOBUF_LEN 1024
88 #define REDIS_LOADBUF_LEN 1024
89 #define REDIS_STATIC_ARGS 4
90 #define REDIS_DEFAULT_DBNUM 16
91 #define REDIS_CONFIGLINE_MAX 1024
92 #define REDIS_OBJFREELIST_MAX 1000000 /* Max number of objects to cache */
93 #define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
94 #define REDIS_EXPIRELOOKUPS_PER_CRON 100 /* try to expire 100 keys/second */
95 #define REDIS_MAX_WRITE_PER_EVENT (1024*64)
96 #define REDIS_REQUEST_MAX_SIZE (1024*1024*256) /* max bytes in inline command */
98 /* If more then REDIS_WRITEV_THRESHOLD write packets are pending use writev */
99 #define REDIS_WRITEV_THRESHOLD 3
100 /* Max number of iovecs used for each writev call */
101 #define REDIS_WRITEV_IOVEC_COUNT 256
103 /* Hash table parameters */
104 #define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
107 #define REDIS_CMD_BULK 1 /* Bulk write command */
108 #define REDIS_CMD_INLINE 2 /* Inline command */
109 /* REDIS_CMD_DENYOOM reserves a longer comment: all the commands marked with
110 this flags will return an error when the 'maxmemory' option is set in the
111 config file and the server is using more than maxmemory bytes of memory.
112 In short this commands are denied on low memory conditions. */
113 #define REDIS_CMD_DENYOOM 4
116 #define REDIS_STRING 0
122 /* Objects encoding. Some kind of objects like Strings and Hashes can be
123 * internally represented in multiple ways. The 'encoding' field of the object
124 * is set to one of this fields for this object. */
125 #define REDIS_ENCODING_RAW 0 /* Raw representation */
126 #define REDIS_ENCODING_INT 1 /* Encoded as integer */
127 #define REDIS_ENCODING_ZIPMAP 2 /* Encoded as zipmap */
128 #define REDIS_ENCODING_HT 3 /* Encoded as an hash table */
130 static char* strencoding
[] = {
131 "raw", "int", "zipmap", "hashtable"
134 /* Object types only used for dumping to disk */
135 #define REDIS_EXPIRETIME 253
136 #define REDIS_SELECTDB 254
137 #define REDIS_EOF 255
139 /* Defines related to the dump file format. To store 32 bits lengths for short
140 * keys requires a lot of space, so we check the most significant 2 bits of
141 * the first byte to interpreter the length:
143 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
144 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
145 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
146 * 11|000000 this means: specially encoded object will follow. The six bits
147 * number specify the kind of object that follows.
148 * See the REDIS_RDB_ENC_* defines.
150 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
151 * values, will fit inside. */
152 #define REDIS_RDB_6BITLEN 0
153 #define REDIS_RDB_14BITLEN 1
154 #define REDIS_RDB_32BITLEN 2
155 #define REDIS_RDB_ENCVAL 3
156 #define REDIS_RDB_LENERR UINT_MAX
158 /* When a length of a string object stored on disk has the first two bits
159 * set, the remaining two bits specify a special encoding for the object
160 * accordingly to the following defines: */
161 #define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
162 #define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
163 #define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
164 #define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
166 /* Virtual memory object->where field. */
167 #define REDIS_VM_MEMORY 0 /* The object is on memory */
168 #define REDIS_VM_SWAPPED 1 /* The object is on disk */
169 #define REDIS_VM_SWAPPING 2 /* Redis is swapping this object on disk */
170 #define REDIS_VM_LOADING 3 /* Redis is loading this object from disk */
172 /* Virtual memory static configuration stuff.
173 * Check vmFindContiguousPages() to know more about this magic numbers. */
174 #define REDIS_VM_MAX_NEAR_PAGES 65536
175 #define REDIS_VM_MAX_RANDOM_JUMP 4096
176 #define REDIS_VM_MAX_THREADS 32
177 #define REDIS_THREAD_STACK_SIZE (1024*1024*4)
178 /* The following is the *percentage* of completed I/O jobs to process when the
179 * handelr is called. While Virtual Memory I/O operations are performed by
180 * threads, this operations must be processed by the main thread when completed
181 * in order to take effect. */
182 #define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
185 #define REDIS_SLAVE 1 /* This client is a slave server */
186 #define REDIS_MASTER 2 /* This client is a master server */
187 #define REDIS_MONITOR 4 /* This client is a slave monitor, see MONITOR */
188 #define REDIS_MULTI 8 /* This client is in a MULTI context */
189 #define REDIS_BLOCKED 16 /* The client is waiting in a blocking operation */
190 #define REDIS_IO_WAIT 32 /* The client is waiting for Virtual Memory I/O */
192 /* Slave replication state - slave side */
193 #define REDIS_REPL_NONE 0 /* No active replication */
194 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
195 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
197 /* Slave replication state - from the point of view of master
198 * Note that in SEND_BULK and ONLINE state the slave receives new updates
199 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
200 * to start the next background saving in order to send updates to it. */
201 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
202 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
203 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
204 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
206 /* List related stuff */
210 /* Sort operations */
211 #define REDIS_SORT_GET 0
212 #define REDIS_SORT_ASC 1
213 #define REDIS_SORT_DESC 2
214 #define REDIS_SORTKEY_MAX 1024
217 #define REDIS_DEBUG 0
218 #define REDIS_VERBOSE 1
219 #define REDIS_NOTICE 2
220 #define REDIS_WARNING 3
222 /* Anti-warning macro... */
223 #define REDIS_NOTUSED(V) ((void) V)
225 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
226 #define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
228 /* Append only defines */
229 #define APPENDFSYNC_NO 0
230 #define APPENDFSYNC_ALWAYS 1
231 #define APPENDFSYNC_EVERYSEC 2
233 /* Hashes related defaults */
234 #define REDIS_HASH_MAX_ZIPMAP_ENTRIES 64
235 #define REDIS_HASH_MAX_ZIPMAP_VALUE 512
237 /* We can print the stacktrace, so our assert is defined this way: */
238 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),_exit(1)))
239 static void _redisAssert(char *estr
, char *file
, int line
);
241 /*================================= Data types ============================== */
243 /* A redis object, that is a type able to hold a string / list / set */
245 /* The VM object structure */
246 struct redisObjectVM
{
247 off_t page
; /* the page at witch the object is stored on disk */
248 off_t usedpages
; /* number of pages used on disk */
249 time_t atime
; /* Last access time */
252 /* The actual Redis Object */
253 typedef struct redisObject
{
256 unsigned char encoding
;
257 unsigned char storage
; /* If this object is a key, where is the value?
258 * REDIS_VM_MEMORY, REDIS_VM_SWAPPED, ... */
259 unsigned char vtype
; /* If this object is a key, and value is swapped out,
260 * this is the type of the swapped out object. */
262 /* VM fields, this are only allocated if VM is active, otherwise the
263 * object allocation function will just allocate
264 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
265 * Redis without VM active will not have any overhead. */
266 struct redisObjectVM vm
;
269 /* Macro used to initalize a Redis object allocated on the stack.
270 * Note that this macro is taken near the structure definition to make sure
271 * we'll update it when the structure is changed, to avoid bugs like
272 * bug #85 introduced exactly in this way. */
273 #define initStaticStringObject(_var,_ptr) do { \
275 _var.type = REDIS_STRING; \
276 _var.encoding = REDIS_ENCODING_RAW; \
278 if (server.vm_enabled) _var.storage = REDIS_VM_MEMORY; \
281 typedef struct redisDb
{
282 dict
*dict
; /* The keyspace for this DB */
283 dict
*expires
; /* Timeout of keys with a timeout set */
284 dict
*blockingkeys
; /* Keys with clients waiting for data (BLPOP) */
285 dict
*io_keys
; /* Keys with clients waiting for VM I/O */
289 /* Client MULTI/EXEC state */
290 typedef struct multiCmd
{
293 struct redisCommand
*cmd
;
296 typedef struct multiState
{
297 multiCmd
*commands
; /* Array of MULTI commands */
298 int count
; /* Total number of MULTI commands */
301 /* With multiplexing we need to take per-clinet state.
302 * Clients are taken in a liked list. */
303 typedef struct redisClient
{
308 robj
**argv
, **mbargv
;
310 int bulklen
; /* bulk read len. -1 if not in bulk read mode */
311 int multibulk
; /* multi bulk command format active */
314 time_t lastinteraction
; /* time of the last interaction, used for timeout */
315 int flags
; /* REDIS_SLAVE | REDIS_MONITOR | REDIS_MULTI ... */
316 int slaveseldb
; /* slave selected db, if this client is a slave */
317 int authenticated
; /* when requirepass is non-NULL */
318 int replstate
; /* replication state if this is a slave */
319 int repldbfd
; /* replication DB file descriptor */
320 long repldboff
; /* replication DB file offset */
321 off_t repldbsize
; /* replication DB file size */
322 multiState mstate
; /* MULTI/EXEC state */
323 robj
**blockingkeys
; /* The key we are waiting to terminate a blocking
324 * operation such as BLPOP. Otherwise NULL. */
325 int blockingkeysnum
; /* Number of blocking keys */
326 time_t blockingto
; /* Blocking operation timeout. If UNIX current time
327 * is >= blockingto then the operation timed out. */
328 list
*io_keys
; /* Keys this client is waiting to be loaded from the
329 * swap file in order to continue. */
337 /* Global server state structure */
342 dict
*sharingpool
; /* Poll used for object sharing */
343 unsigned int sharingpoolsize
;
344 long long dirty
; /* changes to DB from the last save */
346 list
*slaves
, *monitors
;
347 char neterr
[ANET_ERR_LEN
];
349 int cronloops
; /* number of times the cron function run */
350 list
*objfreelist
; /* A list of freed objects to avoid malloc() */
351 time_t lastsave
; /* Unix time of last save succeeede */
352 /* Fields used only for stats */
353 time_t stat_starttime
; /* server start time */
354 long long stat_numcommands
; /* number of processed commands */
355 long long stat_numconnections
; /* number of connections received */
368 pid_t bgsavechildpid
;
369 pid_t bgrewritechildpid
;
370 sds bgrewritebuf
; /* buffer taken by parent during oppend only rewrite */
371 struct saveparam
*saveparams
;
376 char *appendfilename
;
380 /* Replication related */
385 redisClient
*master
; /* client that is master for this slave */
387 unsigned int maxclients
;
388 unsigned long long maxmemory
;
389 unsigned int blpop_blocked_clients
;
390 unsigned int vm_blocked_clients
;
391 /* Sort parameters - qsort_r() is only available under BSD so we
392 * have to take this state global, in order to pass it to sortCompare() */
396 /* Virtual memory configuration */
401 unsigned long long vm_max_memory
;
403 size_t hash_max_zipmap_entries
;
404 size_t hash_max_zipmap_value
;
405 /* Virtual memory state */
408 off_t vm_next_page
; /* Next probably empty page */
409 off_t vm_near_pages
; /* Number of pages allocated sequentially */
410 unsigned char *vm_bitmap
; /* Bitmap of free/used pages */
411 time_t unixtime
; /* Unix time sampled every second. */
412 /* Virtual memory I/O threads stuff */
413 /* An I/O thread process an element taken from the io_jobs queue and
414 * put the result of the operation in the io_done list. While the
415 * job is being processed, it's put on io_processing queue. */
416 list
*io_newjobs
; /* List of VM I/O jobs yet to be processed */
417 list
*io_processing
; /* List of VM I/O jobs being processed */
418 list
*io_processed
; /* List of VM I/O jobs already processed */
419 list
*io_ready_clients
; /* Clients ready to be unblocked. All keys loaded */
420 pthread_mutex_t io_mutex
; /* lock to access io_jobs/io_done/io_thread_job */
421 pthread_mutex_t obj_freelist_mutex
; /* safe redis objects creation/free */
422 pthread_mutex_t io_swapfile_mutex
; /* So we can lseek + write */
423 pthread_attr_t io_threads_attr
; /* attributes for threads creation */
424 int io_active_threads
; /* Number of running I/O threads */
425 int vm_max_threads
; /* Max number of I/O threads running at the same time */
426 /* Our main thread is blocked on the event loop, locking for sockets ready
427 * to be read or written, so when a threaded I/O operation is ready to be
428 * processed by the main thread, the I/O thread will use a unix pipe to
429 * awake the main thread. The followings are the two pipe FDs. */
430 int io_ready_pipe_read
;
431 int io_ready_pipe_write
;
432 /* Virtual memory stats */
433 unsigned long long vm_stats_used_pages
;
434 unsigned long long vm_stats_swapped_objects
;
435 unsigned long long vm_stats_swapouts
;
436 unsigned long long vm_stats_swapins
;
440 typedef void redisCommandProc(redisClient
*c
);
441 struct redisCommand
{
443 redisCommandProc
*proc
;
446 /* What keys should be loaded in background when calling this command? */
447 int vm_firstkey
; /* The first argument that's a key (0 = no keys) */
448 int vm_lastkey
; /* THe last argument that's a key */
449 int vm_keystep
; /* The step between first and last key */
452 struct redisFunctionSym
{
454 unsigned long pointer
;
457 typedef struct _redisSortObject
{
465 typedef struct _redisSortOperation
{
468 } redisSortOperation
;
470 /* ZSETs use a specialized version of Skiplists */
472 typedef struct zskiplistNode
{
473 struct zskiplistNode
**forward
;
474 struct zskiplistNode
*backward
;
480 typedef struct zskiplist
{
481 struct zskiplistNode
*header
, *tail
;
482 unsigned long length
;
486 typedef struct zset
{
491 /* Our shared "common" objects */
493 struct sharedObjectsStruct
{
494 robj
*crlf
, *ok
, *err
, *emptybulk
, *czero
, *cone
, *pong
, *space
,
495 *colon
, *nullbulk
, *nullmultibulk
, *queued
,
496 *emptymultibulk
, *wrongtypeerr
, *nokeyerr
, *syntaxerr
, *sameobjecterr
,
497 *outofrangeerr
, *plus
,
498 *select0
, *select1
, *select2
, *select3
, *select4
,
499 *select5
, *select6
, *select7
, *select8
, *select9
;
502 /* Global vars that are actally used as constants. The following double
503 * values are used for double on-disk serialization, and are initialized
504 * at runtime to avoid strange compiler optimizations. */
506 static double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
;
508 /* VM threaded I/O request message */
509 #define REDIS_IOJOB_LOAD 0 /* Load from disk to memory */
510 #define REDIS_IOJOB_PREPARE_SWAP 1 /* Compute needed pages */
511 #define REDIS_IOJOB_DO_SWAP 2 /* Swap from memory to disk */
512 typedef struct iojob
{
513 int type
; /* Request type, REDIS_IOJOB_* */
514 redisDb
*db
;/* Redis database */
515 robj
*key
; /* This I/O request is about swapping this key */
516 robj
*val
; /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
517 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
518 off_t page
; /* Swap page where to read/write the object */
519 off_t pages
; /* Swap pages needed to safe object. PREPARE_SWAP return val */
520 int canceled
; /* True if this command was canceled by blocking side of VM */
521 pthread_t thread
; /* ID of the thread processing this entry */
524 /*================================ Prototypes =============================== */
526 static void freeStringObject(robj
*o
);
527 static void freeListObject(robj
*o
);
528 static void freeSetObject(robj
*o
);
529 static void decrRefCount(void *o
);
530 static robj
*createObject(int type
, void *ptr
);
531 static void freeClient(redisClient
*c
);
532 static int rdbLoad(char *filename
);
533 static void addReply(redisClient
*c
, robj
*obj
);
534 static void addReplySds(redisClient
*c
, sds s
);
535 static void incrRefCount(robj
*o
);
536 static int rdbSaveBackground(char *filename
);
537 static robj
*createStringObject(char *ptr
, size_t len
);
538 static robj
*dupStringObject(robj
*o
);
539 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
540 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
541 static int syncWithMaster(void);
542 static robj
*tryObjectSharing(robj
*o
);
543 static int tryObjectEncoding(robj
*o
);
544 static robj
*getDecodedObject(robj
*o
);
545 static int removeExpire(redisDb
*db
, robj
*key
);
546 static int expireIfNeeded(redisDb
*db
, robj
*key
);
547 static int deleteIfVolatile(redisDb
*db
, robj
*key
);
548 static int deleteIfSwapped(redisDb
*db
, robj
*key
);
549 static int deleteKey(redisDb
*db
, robj
*key
);
550 static time_t getExpire(redisDb
*db
, robj
*key
);
551 static int setExpire(redisDb
*db
, robj
*key
, time_t when
);
552 static void updateSlavesWaitingBgsave(int bgsaveerr
);
553 static void freeMemoryIfNeeded(void);
554 static int processCommand(redisClient
*c
);
555 static void setupSigSegvAction(void);
556 static void rdbRemoveTempFile(pid_t childpid
);
557 static void aofRemoveTempFile(pid_t childpid
);
558 static size_t stringObjectLen(robj
*o
);
559 static void processInputBuffer(redisClient
*c
);
560 static zskiplist
*zslCreate(void);
561 static void zslFree(zskiplist
*zsl
);
562 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
);
563 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
564 static void initClientMultiState(redisClient
*c
);
565 static void freeClientMultiState(redisClient
*c
);
566 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
);
567 static void unblockClientWaitingData(redisClient
*c
);
568 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
);
569 static void vmInit(void);
570 static void vmMarkPagesFree(off_t page
, off_t count
);
571 static robj
*vmLoadObject(robj
*key
);
572 static robj
*vmPreviewObject(robj
*key
);
573 static int vmSwapOneObjectBlocking(void);
574 static int vmSwapOneObjectThreaded(void);
575 static int vmCanSwapOut(void);
576 static int tryFreeOneObjectFromFreelist(void);
577 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
578 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
579 static void vmCancelThreadedIOJob(robj
*o
);
580 static void lockThreadedIO(void);
581 static void unlockThreadedIO(void);
582 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
);
583 static void freeIOJob(iojob
*j
);
584 static void queueIOJob(iojob
*j
);
585 static int vmWriteObjectOnSwap(robj
*o
, off_t page
);
586 static robj
*vmReadObjectFromSwap(off_t page
, int type
);
587 static void waitEmptyIOJobsQueue(void);
588 static void vmReopenSwapFile(void);
589 static int vmFreePage(off_t page
);
590 static int blockClientOnSwappedKeys(struct redisCommand
*cmd
, redisClient
*c
);
591 static int dontWaitForSwappedKey(redisClient
*c
, robj
*key
);
592 static void handleClientsBlockedOnSwappedKey(redisDb
*db
, robj
*key
);
593 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
594 static struct redisCommand
*lookupCommand(char *name
);
595 static void call(redisClient
*c
, struct redisCommand
*cmd
);
596 static void resetClient(redisClient
*c
);
597 static void convertToRealHash(robj
*o
);
599 static void authCommand(redisClient
*c
);
600 static void pingCommand(redisClient
*c
);
601 static void echoCommand(redisClient
*c
);
602 static void setCommand(redisClient
*c
);
603 static void setnxCommand(redisClient
*c
);
604 static void getCommand(redisClient
*c
);
605 static void delCommand(redisClient
*c
);
606 static void existsCommand(redisClient
*c
);
607 static void incrCommand(redisClient
*c
);
608 static void decrCommand(redisClient
*c
);
609 static void incrbyCommand(redisClient
*c
);
610 static void decrbyCommand(redisClient
*c
);
611 static void selectCommand(redisClient
*c
);
612 static void randomkeyCommand(redisClient
*c
);
613 static void keysCommand(redisClient
*c
);
614 static void dbsizeCommand(redisClient
*c
);
615 static void lastsaveCommand(redisClient
*c
);
616 static void saveCommand(redisClient
*c
);
617 static void bgsaveCommand(redisClient
*c
);
618 static void bgrewriteaofCommand(redisClient
*c
);
619 static void shutdownCommand(redisClient
*c
);
620 static void moveCommand(redisClient
*c
);
621 static void renameCommand(redisClient
*c
);
622 static void renamenxCommand(redisClient
*c
);
623 static void lpushCommand(redisClient
*c
);
624 static void rpushCommand(redisClient
*c
);
625 static void lpopCommand(redisClient
*c
);
626 static void rpopCommand(redisClient
*c
);
627 static void llenCommand(redisClient
*c
);
628 static void lindexCommand(redisClient
*c
);
629 static void lrangeCommand(redisClient
*c
);
630 static void ltrimCommand(redisClient
*c
);
631 static void typeCommand(redisClient
*c
);
632 static void lsetCommand(redisClient
*c
);
633 static void saddCommand(redisClient
*c
);
634 static void sremCommand(redisClient
*c
);
635 static void smoveCommand(redisClient
*c
);
636 static void sismemberCommand(redisClient
*c
);
637 static void scardCommand(redisClient
*c
);
638 static void spopCommand(redisClient
*c
);
639 static void srandmemberCommand(redisClient
*c
);
640 static void sinterCommand(redisClient
*c
);
641 static void sinterstoreCommand(redisClient
*c
);
642 static void sunionCommand(redisClient
*c
);
643 static void sunionstoreCommand(redisClient
*c
);
644 static void sdiffCommand(redisClient
*c
);
645 static void sdiffstoreCommand(redisClient
*c
);
646 static void syncCommand(redisClient
*c
);
647 static void flushdbCommand(redisClient
*c
);
648 static void flushallCommand(redisClient
*c
);
649 static void sortCommand(redisClient
*c
);
650 static void lremCommand(redisClient
*c
);
651 static void rpoplpushcommand(redisClient
*c
);
652 static void infoCommand(redisClient
*c
);
653 static void mgetCommand(redisClient
*c
);
654 static void monitorCommand(redisClient
*c
);
655 static void expireCommand(redisClient
*c
);
656 static void expireatCommand(redisClient
*c
);
657 static void getsetCommand(redisClient
*c
);
658 static void ttlCommand(redisClient
*c
);
659 static void slaveofCommand(redisClient
*c
);
660 static void debugCommand(redisClient
*c
);
661 static void msetCommand(redisClient
*c
);
662 static void msetnxCommand(redisClient
*c
);
663 static void zaddCommand(redisClient
*c
);
664 static void zincrbyCommand(redisClient
*c
);
665 static void zrangeCommand(redisClient
*c
);
666 static void zrangebyscoreCommand(redisClient
*c
);
667 static void zcountCommand(redisClient
*c
);
668 static void zrevrangeCommand(redisClient
*c
);
669 static void zcardCommand(redisClient
*c
);
670 static void zremCommand(redisClient
*c
);
671 static void zscoreCommand(redisClient
*c
);
672 static void zremrangebyscoreCommand(redisClient
*c
);
673 static void multiCommand(redisClient
*c
);
674 static void execCommand(redisClient
*c
);
675 static void discardCommand(redisClient
*c
);
676 static void blpopCommand(redisClient
*c
);
677 static void brpopCommand(redisClient
*c
);
678 static void appendCommand(redisClient
*c
);
679 static void substrCommand(redisClient
*c
);
680 static void zrankCommand(redisClient
*c
);
681 static void zrevrankCommand(redisClient
*c
);
682 static void hsetCommand(redisClient
*c
);
683 static void hgetCommand(redisClient
*c
);
684 static void hdelCommand(redisClient
*c
);
685 static void zremrangebyrankCommand(redisClient
*c
);
686 static void zunionCommand(redisClient
*c
);
687 static void zinterCommand(redisClient
*c
);
689 /*================================= Globals ================================= */
692 static struct redisServer server
; /* server global state */
693 static struct redisCommand cmdTable
[] = {
694 {"get",getCommand
,2,REDIS_CMD_INLINE
,1,1,1},
695 {"set",setCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,0,0,0},
696 {"setnx",setnxCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,0,0,0},
697 {"append",appendCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1},
698 {"substr",substrCommand
,4,REDIS_CMD_INLINE
,1,1,1},
699 {"del",delCommand
,-2,REDIS_CMD_INLINE
,0,0,0},
700 {"exists",existsCommand
,2,REDIS_CMD_INLINE
,1,1,1},
701 {"incr",incrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,1,1},
702 {"decr",decrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,1,1},
703 {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
,1,-1,1},
704 {"rpush",rpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1},
705 {"lpush",lpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1},
706 {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
,1,1,1},
707 {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
,1,1,1},
708 {"brpop",brpopCommand
,-3,REDIS_CMD_INLINE
,1,1,1},
709 {"blpop",blpopCommand
,-3,REDIS_CMD_INLINE
,1,1,1},
710 {"llen",llenCommand
,2,REDIS_CMD_INLINE
,1,1,1},
711 {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
,1,1,1},
712 {"lset",lsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1},
713 {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
,1,1,1},
714 {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
,1,1,1},
715 {"lrem",lremCommand
,4,REDIS_CMD_BULK
,1,1,1},
716 {"rpoplpush",rpoplpushcommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,2,1},
717 {"sadd",saddCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1},
718 {"srem",sremCommand
,3,REDIS_CMD_BULK
,1,1,1},
719 {"smove",smoveCommand
,4,REDIS_CMD_BULK
,1,2,1},
720 {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
,1,1,1},
721 {"scard",scardCommand
,2,REDIS_CMD_INLINE
,1,1,1},
722 {"spop",spopCommand
,2,REDIS_CMD_INLINE
,1,1,1},
723 {"srandmember",srandmemberCommand
,2,REDIS_CMD_INLINE
,1,1,1},
724 {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,-1,1},
725 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,2,-1,1},
726 {"sunion",sunionCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,-1,1},
727 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,2,-1,1},
728 {"sdiff",sdiffCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,-1,1},
729 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,2,-1,1},
730 {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
,1,1,1},
731 {"zadd",zaddCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1},
732 {"zincrby",zincrbyCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1},
733 {"zrem",zremCommand
,3,REDIS_CMD_BULK
,1,1,1},
734 {"zremrangebyscore",zremrangebyscoreCommand
,4,REDIS_CMD_INLINE
,1,1,1},
735 {"zremrangebyrank",zremrangebyrankCommand
,4,REDIS_CMD_INLINE
,1,1,1},
736 {"zunion",zunionCommand
,-4,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,0,0,0},
737 {"zinter",zinterCommand
,-4,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,0,0,0},
738 {"zrange",zrangeCommand
,-4,REDIS_CMD_INLINE
,1,1,1},
739 {"zrangebyscore",zrangebyscoreCommand
,-4,REDIS_CMD_INLINE
,1,1,1},
740 {"zcount",zcountCommand
,4,REDIS_CMD_INLINE
,1,1,1},
741 {"zrevrange",zrevrangeCommand
,-4,REDIS_CMD_INLINE
,1,1,1},
742 {"zcard",zcardCommand
,2,REDIS_CMD_INLINE
,1,1,1},
743 {"zscore",zscoreCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1},
744 {"zrank",zrankCommand
,3,REDIS_CMD_INLINE
,1,1,1},
745 {"zrevrank",zrevrankCommand
,3,REDIS_CMD_INLINE
,1,1,1},
746 {"hset",hsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1},
747 {"hget",hgetCommand
,3,REDIS_CMD_BULK
,1,1,1},
748 {"hdel",hdelCommand
,3,REDIS_CMD_BULK
,1,1,1},
749 {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,1,1},
750 {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,1,1},
751 {"getset",getsetCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1},
752 {"mset",msetCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,-1,2},
753 {"msetnx",msetnxCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,-1,2},
754 {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
,0,0,0},
755 {"select",selectCommand
,2,REDIS_CMD_INLINE
,0,0,0},
756 {"move",moveCommand
,3,REDIS_CMD_INLINE
,1,1,1},
757 {"rename",renameCommand
,3,REDIS_CMD_INLINE
,1,1,1},
758 {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
,1,1,1},
759 {"expire",expireCommand
,3,REDIS_CMD_INLINE
,0,0,0},
760 {"expireat",expireatCommand
,3,REDIS_CMD_INLINE
,0,0,0},
761 {"keys",keysCommand
,2,REDIS_CMD_INLINE
,0,0,0},
762 {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
,0,0,0},
763 {"auth",authCommand
,2,REDIS_CMD_INLINE
,0,0,0},
764 {"ping",pingCommand
,1,REDIS_CMD_INLINE
,0,0,0},
765 {"echo",echoCommand
,2,REDIS_CMD_BULK
,0,0,0},
766 {"save",saveCommand
,1,REDIS_CMD_INLINE
,0,0,0},
767 {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
,0,0,0},
768 {"bgrewriteaof",bgrewriteaofCommand
,1,REDIS_CMD_INLINE
,0,0,0},
769 {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
,0,0,0},
770 {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
,0,0,0},
771 {"type",typeCommand
,2,REDIS_CMD_INLINE
,1,1,1},
772 {"multi",multiCommand
,1,REDIS_CMD_INLINE
,0,0,0},
773 {"exec",execCommand
,1,REDIS_CMD_INLINE
,0,0,0},
774 {"discard",discardCommand
,1,REDIS_CMD_INLINE
,0,0,0},
775 {"sync",syncCommand
,1,REDIS_CMD_INLINE
,0,0,0},
776 {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
,0,0,0},
777 {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
,0,0,0},
778 {"sort",sortCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,1,1},
779 {"info",infoCommand
,1,REDIS_CMD_INLINE
,0,0,0},
780 {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
,0,0,0},
781 {"ttl",ttlCommand
,2,REDIS_CMD_INLINE
,1,1,1},
782 {"slaveof",slaveofCommand
,3,REDIS_CMD_INLINE
,0,0,0},
783 {"debug",debugCommand
,-2,REDIS_CMD_INLINE
,0,0,0},
784 {NULL
,NULL
,0,0,0,0,0}
787 /*============================ Utility functions ============================ */
789 /* Glob-style pattern matching. */
790 int stringmatchlen(const char *pattern
, int patternLen
,
791 const char *string
, int stringLen
, int nocase
)
796 while (pattern
[1] == '*') {
801 return 1; /* match */
803 if (stringmatchlen(pattern
+1, patternLen
-1,
804 string
, stringLen
, nocase
))
805 return 1; /* match */
809 return 0; /* no match */
813 return 0; /* no match */
823 not = pattern
[0] == '^';
830 if (pattern
[0] == '\\') {
833 if (pattern
[0] == string
[0])
835 } else if (pattern
[0] == ']') {
837 } else if (patternLen
== 0) {
841 } else if (pattern
[1] == '-' && patternLen
>= 3) {
842 int start
= pattern
[0];
843 int end
= pattern
[2];
851 start
= tolower(start
);
857 if (c
>= start
&& c
<= end
)
861 if (pattern
[0] == string
[0])
864 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
874 return 0; /* no match */
880 if (patternLen
>= 2) {
887 if (pattern
[0] != string
[0])
888 return 0; /* no match */
890 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
891 return 0; /* no match */
899 if (stringLen
== 0) {
900 while(*pattern
== '*') {
907 if (patternLen
== 0 && stringLen
== 0)
912 static void redisLog(int level
, const char *fmt
, ...) {
916 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
920 if (level
>= server
.verbosity
) {
926 strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
));
927 fprintf(fp
,"[%d] %s %c ",(int)getpid(),buf
,c
[level
]);
928 vfprintf(fp
, fmt
, ap
);
934 if (server
.logfile
) fclose(fp
);
937 /*====================== Hash table type implementation ==================== */
939 /* This is an hash table type that uses the SDS dynamic strings libary as
940 * keys and radis objects as values (objects can hold SDS strings,
943 static void dictVanillaFree(void *privdata
, void *val
)
945 DICT_NOTUSED(privdata
);
949 static void dictListDestructor(void *privdata
, void *val
)
951 DICT_NOTUSED(privdata
);
952 listRelease((list
*)val
);
955 static int sdsDictKeyCompare(void *privdata
, const void *key1
,
959 DICT_NOTUSED(privdata
);
961 l1
= sdslen((sds
)key1
);
962 l2
= sdslen((sds
)key2
);
963 if (l1
!= l2
) return 0;
964 return memcmp(key1
, key2
, l1
) == 0;
967 static void dictRedisObjectDestructor(void *privdata
, void *val
)
969 DICT_NOTUSED(privdata
);
971 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
975 static int dictObjKeyCompare(void *privdata
, const void *key1
,
978 const robj
*o1
= key1
, *o2
= key2
;
979 return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
982 static unsigned int dictObjHash(const void *key
) {
984 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
987 static int dictEncObjKeyCompare(void *privdata
, const void *key1
,
990 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
993 o1
= getDecodedObject(o1
);
994 o2
= getDecodedObject(o2
);
995 cmp
= sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
1001 static unsigned int dictEncObjHash(const void *key
) {
1002 robj
*o
= (robj
*) key
;
1004 if (o
->encoding
== REDIS_ENCODING_RAW
) {
1005 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
1007 if (o
->encoding
== REDIS_ENCODING_INT
) {
1011 len
= snprintf(buf
,32,"%ld",(long)o
->ptr
);
1012 return dictGenHashFunction((unsigned char*)buf
, len
);
1016 o
= getDecodedObject(o
);
1017 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
1024 /* Sets type and expires */
1025 static dictType setDictType
= {
1026 dictEncObjHash
, /* hash function */
1029 dictEncObjKeyCompare
, /* key compare */
1030 dictRedisObjectDestructor
, /* key destructor */
1031 NULL
/* val destructor */
1034 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
1035 static dictType zsetDictType
= {
1036 dictEncObjHash
, /* hash function */
1039 dictEncObjKeyCompare
, /* key compare */
1040 dictRedisObjectDestructor
, /* key destructor */
1041 dictVanillaFree
/* val destructor of malloc(sizeof(double)) */
1045 static dictType dbDictType
= {
1046 dictObjHash
, /* hash function */
1049 dictObjKeyCompare
, /* key compare */
1050 dictRedisObjectDestructor
, /* key destructor */
1051 dictRedisObjectDestructor
/* val destructor */
1055 static dictType keyptrDictType
= {
1056 dictObjHash
, /* hash function */
1059 dictObjKeyCompare
, /* key compare */
1060 dictRedisObjectDestructor
, /* key destructor */
1061 NULL
/* val destructor */
1064 /* Hash type hash table (note that small hashes are represented with zimpaps) */
1065 static dictType hashDictType
= {
1066 dictEncObjHash
, /* hash function */
1069 dictEncObjKeyCompare
, /* key compare */
1070 dictRedisObjectDestructor
, /* key destructor */
1071 dictRedisObjectDestructor
/* val destructor */
1074 /* Keylist hash table type has unencoded redis objects as keys and
1075 * lists as values. It's used for blocking operations (BLPOP) and to
1076 * map swapped keys to a list of clients waiting for this keys to be loaded. */
1077 static dictType keylistDictType
= {
1078 dictObjHash
, /* hash function */
1081 dictObjKeyCompare
, /* key compare */
1082 dictRedisObjectDestructor
, /* key destructor */
1083 dictListDestructor
/* val destructor */
1086 /* ========================= Random utility functions ======================= */
1088 /* Redis generally does not try to recover from out of memory conditions
1089 * when allocating objects or strings, it is not clear if it will be possible
1090 * to report this condition to the client since the networking layer itself
1091 * is based on heap allocation for send buffers, so we simply abort.
1092 * At least the code will be simpler to read... */
1093 static void oom(const char *msg
) {
1094 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
1099 /* ====================== Redis server networking stuff ===================== */
1100 static void closeTimedoutClients(void) {
1103 time_t now
= time(NULL
);
1106 listRewind(server
.clients
,&li
);
1107 while ((ln
= listNext(&li
)) != NULL
) {
1108 c
= listNodeValue(ln
);
1109 if (server
.maxidletime
&&
1110 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
1111 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
1112 (now
- c
->lastinteraction
> server
.maxidletime
))
1114 redisLog(REDIS_VERBOSE
,"Closing idle client");
1116 } else if (c
->flags
& REDIS_BLOCKED
) {
1117 if (c
->blockingto
!= 0 && c
->blockingto
< now
) {
1118 addReply(c
,shared
.nullmultibulk
);
1119 unblockClientWaitingData(c
);
1125 static int htNeedsResize(dict
*dict
) {
1126 long long size
, used
;
1128 size
= dictSlots(dict
);
1129 used
= dictSize(dict
);
1130 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
1131 (used
*100/size
< REDIS_HT_MINFILL
));
1134 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
1135 * we resize the hash table to save memory */
1136 static void tryResizeHashTables(void) {
1139 for (j
= 0; j
< server
.dbnum
; j
++) {
1140 if (htNeedsResize(server
.db
[j
].dict
)) {
1141 redisLog(REDIS_VERBOSE
,"The hash table %d is too sparse, resize it...",j
);
1142 dictResize(server
.db
[j
].dict
);
1143 redisLog(REDIS_VERBOSE
,"Hash table %d resized.",j
);
1145 if (htNeedsResize(server
.db
[j
].expires
))
1146 dictResize(server
.db
[j
].expires
);
1150 /* A background saving child (BGSAVE) terminated its work. Handle this. */
1151 void backgroundSaveDoneHandler(int statloc
) {
1152 int exitcode
= WEXITSTATUS(statloc
);
1153 int bysignal
= WIFSIGNALED(statloc
);
1155 if (!bysignal
&& exitcode
== 0) {
1156 redisLog(REDIS_NOTICE
,
1157 "Background saving terminated with success");
1159 server
.lastsave
= time(NULL
);
1160 } else if (!bysignal
&& exitcode
!= 0) {
1161 redisLog(REDIS_WARNING
, "Background saving error");
1163 redisLog(REDIS_WARNING
,
1164 "Background saving terminated by signal");
1165 rdbRemoveTempFile(server
.bgsavechildpid
);
1167 server
.bgsavechildpid
= -1;
1168 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1169 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1170 updateSlavesWaitingBgsave(exitcode
== 0 ? REDIS_OK
: REDIS_ERR
);
1173 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1175 void backgroundRewriteDoneHandler(int statloc
) {
1176 int exitcode
= WEXITSTATUS(statloc
);
1177 int bysignal
= WIFSIGNALED(statloc
);
1179 if (!bysignal
&& exitcode
== 0) {
1183 redisLog(REDIS_NOTICE
,
1184 "Background append only file rewriting terminated with success");
1185 /* Now it's time to flush the differences accumulated by the parent */
1186 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) server
.bgrewritechildpid
);
1187 fd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
1189 redisLog(REDIS_WARNING
, "Not able to open the temp append only file produced by the child: %s", strerror(errno
));
1192 /* Flush our data... */
1193 if (write(fd
,server
.bgrewritebuf
,sdslen(server
.bgrewritebuf
)) !=
1194 (signed) sdslen(server
.bgrewritebuf
)) {
1195 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
));
1199 redisLog(REDIS_NOTICE
,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server
.bgrewritebuf
));
1200 /* Now our work is to rename the temp file into the stable file. And
1201 * switch the file descriptor used by the server for append only. */
1202 if (rename(tmpfile
,server
.appendfilename
) == -1) {
1203 redisLog(REDIS_WARNING
,"Can't rename the temp append only file into the stable one: %s", strerror(errno
));
1207 /* Mission completed... almost */
1208 redisLog(REDIS_NOTICE
,"Append only file successfully rewritten.");
1209 if (server
.appendfd
!= -1) {
1210 /* If append only is actually enabled... */
1211 close(server
.appendfd
);
1212 server
.appendfd
= fd
;
1214 server
.appendseldb
= -1; /* Make sure it will issue SELECT */
1215 redisLog(REDIS_NOTICE
,"The new append only file was selected for future appends.");
1217 /* If append only is disabled we just generate a dump in this
1218 * format. Why not? */
1221 } else if (!bysignal
&& exitcode
!= 0) {
1222 redisLog(REDIS_WARNING
, "Background append only file rewriting error");
1224 redisLog(REDIS_WARNING
,
1225 "Background append only file rewriting terminated by signal");
1228 sdsfree(server
.bgrewritebuf
);
1229 server
.bgrewritebuf
= sdsempty();
1230 aofRemoveTempFile(server
.bgrewritechildpid
);
1231 server
.bgrewritechildpid
= -1;
1234 static int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
1235 int j
, loops
= server
.cronloops
++;
1236 REDIS_NOTUSED(eventLoop
);
1238 REDIS_NOTUSED(clientData
);
1240 /* We take a cached value of the unix time in the global state because
1241 * with virtual memory and aging there is to store the current time
1242 * in objects at every object access, and accuracy is not needed.
1243 * To access a global var is faster than calling time(NULL) */
1244 server
.unixtime
= time(NULL
);
1246 /* Show some info about non-empty databases */
1247 for (j
= 0; j
< server
.dbnum
; j
++) {
1248 long long size
, used
, vkeys
;
1250 size
= dictSlots(server
.db
[j
].dict
);
1251 used
= dictSize(server
.db
[j
].dict
);
1252 vkeys
= dictSize(server
.db
[j
].expires
);
1253 if (!(loops
% 5) && (used
|| vkeys
)) {
1254 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
1255 /* dictPrintStats(server.dict); */
1259 /* We don't want to resize the hash tables while a bacground saving
1260 * is in progress: the saving child is created using fork() that is
1261 * implemented with a copy-on-write semantic in most modern systems, so
1262 * if we resize the HT while there is the saving child at work actually
1263 * a lot of memory movements in the parent will cause a lot of pages
1265 if (server
.bgsavechildpid
== -1) tryResizeHashTables();
1267 /* Show information about connected clients */
1269 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use, %d shared objects",
1270 listLength(server
.clients
)-listLength(server
.slaves
),
1271 listLength(server
.slaves
),
1272 zmalloc_used_memory(),
1273 dictSize(server
.sharingpool
));
1276 /* Close connections of timedout clients */
1277 if ((server
.maxidletime
&& !(loops
% 10)) || server
.blpop_blocked_clients
)
1278 closeTimedoutClients();
1280 /* Check if a background saving or AOF rewrite in progress terminated */
1281 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
1285 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
1286 if (pid
== server
.bgsavechildpid
) {
1287 backgroundSaveDoneHandler(statloc
);
1289 backgroundRewriteDoneHandler(statloc
);
1293 /* If there is not a background saving in progress check if
1294 * we have to save now */
1295 time_t now
= time(NULL
);
1296 for (j
= 0; j
< server
.saveparamslen
; j
++) {
1297 struct saveparam
*sp
= server
.saveparams
+j
;
1299 if (server
.dirty
>= sp
->changes
&&
1300 now
-server
.lastsave
> sp
->seconds
) {
1301 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
1302 sp
->changes
, sp
->seconds
);
1303 rdbSaveBackground(server
.dbfilename
);
1309 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1310 * will use few CPU cycles if there are few expiring keys, otherwise
1311 * it will get more aggressive to avoid that too much memory is used by
1312 * keys that can be removed from the keyspace. */
1313 for (j
= 0; j
< server
.dbnum
; j
++) {
1315 redisDb
*db
= server
.db
+j
;
1317 /* Continue to expire if at the end of the cycle more than 25%
1318 * of the keys were expired. */
1320 long num
= dictSize(db
->expires
);
1321 time_t now
= time(NULL
);
1324 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
1325 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
1330 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
1331 t
= (time_t) dictGetEntryVal(de
);
1333 deleteKey(db
,dictGetEntryKey(de
));
1337 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
1340 /* Swap a few keys on disk if we are over the memory limit and VM
1341 * is enbled. Try to free objects from the free list first. */
1342 if (vmCanSwapOut()) {
1343 while (server
.vm_enabled
&& zmalloc_used_memory() >
1344 server
.vm_max_memory
)
1348 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
1349 retval
= (server
.vm_max_threads
== 0) ?
1350 vmSwapOneObjectBlocking() :
1351 vmSwapOneObjectThreaded();
1352 if (retval
== REDIS_ERR
&& (loops
% 30) == 0 &&
1353 zmalloc_used_memory() >
1354 (server
.vm_max_memory
+server
.vm_max_memory
/10))
1356 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
1358 /* Note that when using threade I/O we free just one object,
1359 * because anyway when the I/O thread in charge to swap this
1360 * object out will finish, the handler of completed jobs
1361 * will try to swap more objects if we are still out of memory. */
1362 if (retval
== REDIS_ERR
|| server
.vm_max_threads
> 0) break;
1366 /* Check if we should connect to a MASTER */
1367 if (server
.replstate
== REDIS_REPL_CONNECT
) {
1368 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
1369 if (syncWithMaster() == REDIS_OK
) {
1370 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
1376 /* This function gets called every time Redis is entering the
1377 * main loop of the event driven library, that is, before to sleep
1378 * for ready file descriptors. */
1379 static void beforeSleep(struct aeEventLoop
*eventLoop
) {
1380 REDIS_NOTUSED(eventLoop
);
1382 if (server
.vm_enabled
&& listLength(server
.io_ready_clients
)) {
1386 listRewind(server
.io_ready_clients
,&li
);
1387 while((ln
= listNext(&li
))) {
1388 redisClient
*c
= ln
->value
;
1389 struct redisCommand
*cmd
;
1391 /* Resume the client. */
1392 listDelNode(server
.io_ready_clients
,ln
);
1393 c
->flags
&= (~REDIS_IO_WAIT
);
1394 server
.vm_blocked_clients
--;
1395 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
1396 readQueryFromClient
, c
);
1397 cmd
= lookupCommand(c
->argv
[0]->ptr
);
1398 assert(cmd
!= NULL
);
1401 /* There may be more data to process in the input buffer. */
1402 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
1403 processInputBuffer(c
);
1408 static void createSharedObjects(void) {
1409 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
1410 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
1411 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
1412 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
1413 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
1414 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
1415 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
1416 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
1417 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
1418 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
1419 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
1420 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
1421 "-ERR Operation against a key holding the wrong kind of value\r\n"));
1422 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
1423 "-ERR no such key\r\n"));
1424 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
1425 "-ERR syntax error\r\n"));
1426 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
1427 "-ERR source and destination objects are the same\r\n"));
1428 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
1429 "-ERR index out of range\r\n"));
1430 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
1431 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
1432 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
1433 shared
.select0
= createStringObject("select 0\r\n",10);
1434 shared
.select1
= createStringObject("select 1\r\n",10);
1435 shared
.select2
= createStringObject("select 2\r\n",10);
1436 shared
.select3
= createStringObject("select 3\r\n",10);
1437 shared
.select4
= createStringObject("select 4\r\n",10);
1438 shared
.select5
= createStringObject("select 5\r\n",10);
1439 shared
.select6
= createStringObject("select 6\r\n",10);
1440 shared
.select7
= createStringObject("select 7\r\n",10);
1441 shared
.select8
= createStringObject("select 8\r\n",10);
1442 shared
.select9
= createStringObject("select 9\r\n",10);
1445 static void appendServerSaveParams(time_t seconds
, int changes
) {
1446 server
.saveparams
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1));
1447 server
.saveparams
[server
.saveparamslen
].seconds
= seconds
;
1448 server
.saveparams
[server
.saveparamslen
].changes
= changes
;
1449 server
.saveparamslen
++;
1452 static void resetServerSaveParams() {
1453 zfree(server
.saveparams
);
1454 server
.saveparams
= NULL
;
1455 server
.saveparamslen
= 0;
1458 static void initServerConfig() {
1459 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
1460 server
.port
= REDIS_SERVERPORT
;
1461 server
.verbosity
= REDIS_VERBOSE
;
1462 server
.maxidletime
= REDIS_MAXIDLETIME
;
1463 server
.saveparams
= NULL
;
1464 server
.logfile
= NULL
; /* NULL = log on standard output */
1465 server
.bindaddr
= NULL
;
1466 server
.glueoutputbuf
= 1;
1467 server
.daemonize
= 0;
1468 server
.appendonly
= 0;
1469 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1470 server
.lastfsync
= time(NULL
);
1471 server
.appendfd
= -1;
1472 server
.appendseldb
= -1; /* Make sure the first time will not match */
1473 server
.pidfile
= "/var/run/redis.pid";
1474 server
.dbfilename
= "dump.rdb";
1475 server
.appendfilename
= "appendonly.aof";
1476 server
.requirepass
= NULL
;
1477 server
.shareobjects
= 0;
1478 server
.rdbcompression
= 1;
1479 server
.sharingpoolsize
= 1024;
1480 server
.maxclients
= 0;
1481 server
.blpop_blocked_clients
= 0;
1482 server
.maxmemory
= 0;
1483 server
.vm_enabled
= 0;
1484 server
.vm_swap_file
= zstrdup("/tmp/redis-%p.vm");
1485 server
.vm_page_size
= 256; /* 256 bytes per page */
1486 server
.vm_pages
= 1024*1024*100; /* 104 millions of pages */
1487 server
.vm_max_memory
= 1024LL*1024*1024*1; /* 1 GB of RAM */
1488 server
.vm_max_threads
= 4;
1489 server
.vm_blocked_clients
= 0;
1490 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
1491 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
1493 resetServerSaveParams();
1495 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1496 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1497 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1498 /* Replication related */
1500 server
.masterauth
= NULL
;
1501 server
.masterhost
= NULL
;
1502 server
.masterport
= 6379;
1503 server
.master
= NULL
;
1504 server
.replstate
= REDIS_REPL_NONE
;
1506 /* Double constants initialization */
1508 R_PosInf
= 1.0/R_Zero
;
1509 R_NegInf
= -1.0/R_Zero
;
1510 R_Nan
= R_Zero
/R_Zero
;
1513 static void initServer() {
1516 signal(SIGHUP
, SIG_IGN
);
1517 signal(SIGPIPE
, SIG_IGN
);
1518 setupSigSegvAction();
1520 server
.devnull
= fopen("/dev/null","w");
1521 if (server
.devnull
== NULL
) {
1522 redisLog(REDIS_WARNING
, "Can't open /dev/null: %s", server
.neterr
);
1525 server
.clients
= listCreate();
1526 server
.slaves
= listCreate();
1527 server
.monitors
= listCreate();
1528 server
.objfreelist
= listCreate();
1529 createSharedObjects();
1530 server
.el
= aeCreateEventLoop();
1531 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
1532 server
.sharingpool
= dictCreate(&setDictType
,NULL
);
1533 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
1534 if (server
.fd
== -1) {
1535 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
1538 for (j
= 0; j
< server
.dbnum
; j
++) {
1539 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
1540 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
1541 server
.db
[j
].blockingkeys
= dictCreate(&keylistDictType
,NULL
);
1542 if (server
.vm_enabled
)
1543 server
.db
[j
].io_keys
= dictCreate(&keylistDictType
,NULL
);
1544 server
.db
[j
].id
= j
;
1546 server
.cronloops
= 0;
1547 server
.bgsavechildpid
= -1;
1548 server
.bgrewritechildpid
= -1;
1549 server
.bgrewritebuf
= sdsempty();
1550 server
.lastsave
= time(NULL
);
1552 server
.stat_numcommands
= 0;
1553 server
.stat_numconnections
= 0;
1554 server
.stat_starttime
= time(NULL
);
1555 server
.unixtime
= time(NULL
);
1556 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
1557 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
1558 acceptHandler
, NULL
) == AE_ERR
) oom("creating file event");
1560 if (server
.appendonly
) {
1561 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
1562 if (server
.appendfd
== -1) {
1563 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
1569 if (server
.vm_enabled
) vmInit();
1572 /* Empty the whole database */
1573 static long long emptyDb() {
1575 long long removed
= 0;
1577 for (j
= 0; j
< server
.dbnum
; j
++) {
1578 removed
+= dictSize(server
.db
[j
].dict
);
1579 dictEmpty(server
.db
[j
].dict
);
1580 dictEmpty(server
.db
[j
].expires
);
1585 static int yesnotoi(char *s
) {
1586 if (!strcasecmp(s
,"yes")) return 1;
1587 else if (!strcasecmp(s
,"no")) return 0;
1591 /* I agree, this is a very rudimental way to load a configuration...
1592 will improve later if the config gets more complex */
1593 static void loadServerConfig(char *filename
) {
1595 char buf
[REDIS_CONFIGLINE_MAX
+1], *err
= NULL
;
1599 if (filename
[0] == '-' && filename
[1] == '\0')
1602 if ((fp
= fopen(filename
,"r")) == NULL
) {
1603 redisLog(REDIS_WARNING
,"Fatal error, can't open config file");
1608 while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) {
1614 line
= sdstrim(line
," \t\r\n");
1616 /* Skip comments and blank lines*/
1617 if (line
[0] == '#' || line
[0] == '\0') {
1622 /* Split into arguments */
1623 argv
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
);
1624 sdstolower(argv
[0]);
1626 /* Execute config directives */
1627 if (!strcasecmp(argv
[0],"timeout") && argc
== 2) {
1628 server
.maxidletime
= atoi(argv
[1]);
1629 if (server
.maxidletime
< 0) {
1630 err
= "Invalid timeout value"; goto loaderr
;
1632 } else if (!strcasecmp(argv
[0],"port") && argc
== 2) {
1633 server
.port
= atoi(argv
[1]);
1634 if (server
.port
< 1 || server
.port
> 65535) {
1635 err
= "Invalid port"; goto loaderr
;
1637 } else if (!strcasecmp(argv
[0],"bind") && argc
== 2) {
1638 server
.bindaddr
= zstrdup(argv
[1]);
1639 } else if (!strcasecmp(argv
[0],"save") && argc
== 3) {
1640 int seconds
= atoi(argv
[1]);
1641 int changes
= atoi(argv
[2]);
1642 if (seconds
< 1 || changes
< 0) {
1643 err
= "Invalid save parameters"; goto loaderr
;
1645 appendServerSaveParams(seconds
,changes
);
1646 } else if (!strcasecmp(argv
[0],"dir") && argc
== 2) {
1647 if (chdir(argv
[1]) == -1) {
1648 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s",
1649 argv
[1], strerror(errno
));
1652 } else if (!strcasecmp(argv
[0],"loglevel") && argc
== 2) {
1653 if (!strcasecmp(argv
[1],"debug")) server
.verbosity
= REDIS_DEBUG
;
1654 else if (!strcasecmp(argv
[1],"verbose")) server
.verbosity
= REDIS_VERBOSE
;
1655 else if (!strcasecmp(argv
[1],"notice")) server
.verbosity
= REDIS_NOTICE
;
1656 else if (!strcasecmp(argv
[1],"warning")) server
.verbosity
= REDIS_WARNING
;
1658 err
= "Invalid log level. Must be one of debug, notice, warning";
1661 } else if (!strcasecmp(argv
[0],"logfile") && argc
== 2) {
1664 server
.logfile
= zstrdup(argv
[1]);
1665 if (!strcasecmp(server
.logfile
,"stdout")) {
1666 zfree(server
.logfile
);
1667 server
.logfile
= NULL
;
1669 if (server
.logfile
) {
1670 /* Test if we are able to open the file. The server will not
1671 * be able to abort just for this problem later... */
1672 logfp
= fopen(server
.logfile
,"a");
1673 if (logfp
== NULL
) {
1674 err
= sdscatprintf(sdsempty(),
1675 "Can't open the log file: %s", strerror(errno
));
1680 } else if (!strcasecmp(argv
[0],"databases") && argc
== 2) {
1681 server
.dbnum
= atoi(argv
[1]);
1682 if (server
.dbnum
< 1) {
1683 err
= "Invalid number of databases"; goto loaderr
;
1685 } else if (!strcasecmp(argv
[0],"maxclients") && argc
== 2) {
1686 server
.maxclients
= atoi(argv
[1]);
1687 } else if (!strcasecmp(argv
[0],"maxmemory") && argc
== 2) {
1688 server
.maxmemory
= strtoll(argv
[1], NULL
, 10);
1689 } else if (!strcasecmp(argv
[0],"slaveof") && argc
== 3) {
1690 server
.masterhost
= sdsnew(argv
[1]);
1691 server
.masterport
= atoi(argv
[2]);
1692 server
.replstate
= REDIS_REPL_CONNECT
;
1693 } else if (!strcasecmp(argv
[0],"masterauth") && argc
== 2) {
1694 server
.masterauth
= zstrdup(argv
[1]);
1695 } else if (!strcasecmp(argv
[0],"glueoutputbuf") && argc
== 2) {
1696 if ((server
.glueoutputbuf
= yesnotoi(argv
[1])) == -1) {
1697 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1699 } else if (!strcasecmp(argv
[0],"shareobjects") && argc
== 2) {
1700 if ((server
.shareobjects
= yesnotoi(argv
[1])) == -1) {
1701 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1703 } else if (!strcasecmp(argv
[0],"rdbcompression") && argc
== 2) {
1704 if ((server
.rdbcompression
= yesnotoi(argv
[1])) == -1) {
1705 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1707 } else if (!strcasecmp(argv
[0],"shareobjectspoolsize") && argc
== 2) {
1708 server
.sharingpoolsize
= atoi(argv
[1]);
1709 if (server
.sharingpoolsize
< 1) {
1710 err
= "invalid object sharing pool size"; goto loaderr
;
1712 } else if (!strcasecmp(argv
[0],"daemonize") && argc
== 2) {
1713 if ((server
.daemonize
= yesnotoi(argv
[1])) == -1) {
1714 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1716 } else if (!strcasecmp(argv
[0],"appendonly") && argc
== 2) {
1717 if ((server
.appendonly
= yesnotoi(argv
[1])) == -1) {
1718 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1720 } else if (!strcasecmp(argv
[0],"appendfsync") && argc
== 2) {
1721 if (!strcasecmp(argv
[1],"no")) {
1722 server
.appendfsync
= APPENDFSYNC_NO
;
1723 } else if (!strcasecmp(argv
[1],"always")) {
1724 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1725 } else if (!strcasecmp(argv
[1],"everysec")) {
1726 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
1728 err
= "argument must be 'no', 'always' or 'everysec'";
1731 } else if (!strcasecmp(argv
[0],"requirepass") && argc
== 2) {
1732 server
.requirepass
= zstrdup(argv
[1]);
1733 } else if (!strcasecmp(argv
[0],"pidfile") && argc
== 2) {
1734 server
.pidfile
= zstrdup(argv
[1]);
1735 } else if (!strcasecmp(argv
[0],"dbfilename") && argc
== 2) {
1736 server
.dbfilename
= zstrdup(argv
[1]);
1737 } else if (!strcasecmp(argv
[0],"vm-enabled") && argc
== 2) {
1738 if ((server
.vm_enabled
= yesnotoi(argv
[1])) == -1) {
1739 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1741 } else if (!strcasecmp(argv
[0],"vm-swap-file") && argc
== 2) {
1742 zfree(server
.vm_swap_file
);
1743 server
.vm_swap_file
= zstrdup(argv
[1]);
1744 } else if (!strcasecmp(argv
[0],"vm-max-memory") && argc
== 2) {
1745 server
.vm_max_memory
= strtoll(argv
[1], NULL
, 10);
1746 } else if (!strcasecmp(argv
[0],"vm-page-size") && argc
== 2) {
1747 server
.vm_page_size
= strtoll(argv
[1], NULL
, 10);
1748 } else if (!strcasecmp(argv
[0],"vm-pages") && argc
== 2) {
1749 server
.vm_pages
= strtoll(argv
[1], NULL
, 10);
1750 } else if (!strcasecmp(argv
[0],"vm-max-threads") && argc
== 2) {
1751 server
.vm_max_threads
= strtoll(argv
[1], NULL
, 10);
1752 } else if (!strcasecmp(argv
[0],"hash-max-zipmap-entries") && argc
== 2){
1753 server
.hash_max_zipmap_entries
= strtol(argv
[1], NULL
, 10);
1754 } else if (!strcasecmp(argv
[0],"hash-max-zipmap-value") && argc
== 2){
1755 server
.hash_max_zipmap_value
= strtol(argv
[1], NULL
, 10);
1756 } else if (!strcasecmp(argv
[0],"vm-max-threads") && argc
== 2) {
1757 server
.vm_max_threads
= strtoll(argv
[1], NULL
, 10);
1759 err
= "Bad directive or wrong number of arguments"; goto loaderr
;
1761 for (j
= 0; j
< argc
; j
++)
1766 if (fp
!= stdin
) fclose(fp
);
1770 fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n");
1771 fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
);
1772 fprintf(stderr
, ">>> '%s'\n", line
);
1773 fprintf(stderr
, "%s\n", err
);
1777 static void freeClientArgv(redisClient
*c
) {
1780 for (j
= 0; j
< c
->argc
; j
++)
1781 decrRefCount(c
->argv
[j
]);
1782 for (j
= 0; j
< c
->mbargc
; j
++)
1783 decrRefCount(c
->mbargv
[j
]);
1788 static void freeClient(redisClient
*c
) {
1791 /* Note that if the client we are freeing is blocked into a blocking
1792 * call, we have to set querybuf to NULL *before* to call
1793 * unblockClientWaitingData() to avoid processInputBuffer() will get
1794 * called. Also it is important to remove the file events after
1795 * this, because this call adds the READABLE event. */
1796 sdsfree(c
->querybuf
);
1798 if (c
->flags
& REDIS_BLOCKED
)
1799 unblockClientWaitingData(c
);
1801 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
1802 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1803 listRelease(c
->reply
);
1806 /* Remove from the list of clients */
1807 ln
= listSearchKey(server
.clients
,c
);
1808 redisAssert(ln
!= NULL
);
1809 listDelNode(server
.clients
,ln
);
1810 /* Remove from the list of clients waiting for swapped keys */
1811 if (c
->flags
& REDIS_IO_WAIT
&& listLength(c
->io_keys
) == 0) {
1812 ln
= listSearchKey(server
.io_ready_clients
,c
);
1814 listDelNode(server
.io_ready_clients
,ln
);
1815 server
.vm_blocked_clients
--;
1818 while (server
.vm_enabled
&& listLength(c
->io_keys
)) {
1819 ln
= listFirst(c
->io_keys
);
1820 dontWaitForSwappedKey(c
,ln
->value
);
1822 listRelease(c
->io_keys
);
1824 if (c
->flags
& REDIS_SLAVE
) {
1825 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
1827 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
1828 ln
= listSearchKey(l
,c
);
1829 redisAssert(ln
!= NULL
);
1832 if (c
->flags
& REDIS_MASTER
) {
1833 server
.master
= NULL
;
1834 server
.replstate
= REDIS_REPL_CONNECT
;
1838 freeClientMultiState(c
);
1842 #define GLUEREPLY_UP_TO (1024)
1843 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
1845 char buf
[GLUEREPLY_UP_TO
];
1850 listRewind(c
->reply
,&li
);
1851 while((ln
= listNext(&li
))) {
1855 objlen
= sdslen(o
->ptr
);
1856 if (copylen
+ objlen
<= GLUEREPLY_UP_TO
) {
1857 memcpy(buf
+copylen
,o
->ptr
,objlen
);
1859 listDelNode(c
->reply
,ln
);
1861 if (copylen
== 0) return;
1865 /* Now the output buffer is empty, add the new single element */
1866 o
= createObject(REDIS_STRING
,sdsnewlen(buf
,copylen
));
1867 listAddNodeHead(c
->reply
,o
);
1870 static void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1871 redisClient
*c
= privdata
;
1872 int nwritten
= 0, totwritten
= 0, objlen
;
1875 REDIS_NOTUSED(mask
);
1877 /* Use writev() if we have enough buffers to send */
1878 if (!server
.glueoutputbuf
&&
1879 listLength(c
->reply
) > REDIS_WRITEV_THRESHOLD
&&
1880 !(c
->flags
& REDIS_MASTER
))
1882 sendReplyToClientWritev(el
, fd
, privdata
, mask
);
1886 while(listLength(c
->reply
)) {
1887 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
1888 glueReplyBuffersIfNeeded(c
);
1890 o
= listNodeValue(listFirst(c
->reply
));
1891 objlen
= sdslen(o
->ptr
);
1894 listDelNode(c
->reply
,listFirst(c
->reply
));
1898 if (c
->flags
& REDIS_MASTER
) {
1899 /* Don't reply to a master */
1900 nwritten
= objlen
- c
->sentlen
;
1902 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen
- c
->sentlen
);
1903 if (nwritten
<= 0) break;
1905 c
->sentlen
+= nwritten
;
1906 totwritten
+= nwritten
;
1907 /* If we fully sent the object on head go to the next one */
1908 if (c
->sentlen
== objlen
) {
1909 listDelNode(c
->reply
,listFirst(c
->reply
));
1912 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
1913 * bytes, in a single threaded server it's a good idea to serve
1914 * other clients as well, even if a very large request comes from
1915 * super fast link that is always able to accept data (in real world
1916 * scenario think about 'KEYS *' against the loopback interfae) */
1917 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
) break;
1919 if (nwritten
== -1) {
1920 if (errno
== EAGAIN
) {
1923 redisLog(REDIS_VERBOSE
,
1924 "Error writing to client: %s", strerror(errno
));
1929 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
1930 if (listLength(c
->reply
) == 0) {
1932 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1936 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
)
1938 redisClient
*c
= privdata
;
1939 int nwritten
= 0, totwritten
= 0, objlen
, willwrite
;
1941 struct iovec iov
[REDIS_WRITEV_IOVEC_COUNT
];
1942 int offset
, ion
= 0;
1944 REDIS_NOTUSED(mask
);
1947 while (listLength(c
->reply
)) {
1948 offset
= c
->sentlen
;
1952 /* fill-in the iov[] array */
1953 for(node
= listFirst(c
->reply
); node
; node
= listNextNode(node
)) {
1954 o
= listNodeValue(node
);
1955 objlen
= sdslen(o
->ptr
);
1957 if (totwritten
+ objlen
- offset
> REDIS_MAX_WRITE_PER_EVENT
)
1960 if(ion
== REDIS_WRITEV_IOVEC_COUNT
)
1961 break; /* no more iovecs */
1963 iov
[ion
].iov_base
= ((char*)o
->ptr
) + offset
;
1964 iov
[ion
].iov_len
= objlen
- offset
;
1965 willwrite
+= objlen
- offset
;
1966 offset
= 0; /* just for the first item */
1973 /* write all collected blocks at once */
1974 if((nwritten
= writev(fd
, iov
, ion
)) < 0) {
1975 if (errno
!= EAGAIN
) {
1976 redisLog(REDIS_VERBOSE
,
1977 "Error writing to client: %s", strerror(errno
));
1984 totwritten
+= nwritten
;
1985 offset
= c
->sentlen
;
1987 /* remove written robjs from c->reply */
1988 while (nwritten
&& listLength(c
->reply
)) {
1989 o
= listNodeValue(listFirst(c
->reply
));
1990 objlen
= sdslen(o
->ptr
);
1992 if(nwritten
>= objlen
- offset
) {
1993 listDelNode(c
->reply
, listFirst(c
->reply
));
1994 nwritten
-= objlen
- offset
;
1998 c
->sentlen
+= nwritten
;
2006 c
->lastinteraction
= time(NULL
);
2008 if (listLength(c
->reply
) == 0) {
2010 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
2014 static struct redisCommand
*lookupCommand(char *name
) {
2016 while(cmdTable
[j
].name
!= NULL
) {
2017 if (!strcasecmp(name
,cmdTable
[j
].name
)) return &cmdTable
[j
];
2023 /* resetClient prepare the client to process the next command */
2024 static void resetClient(redisClient
*c
) {
2030 /* Call() is the core of Redis execution of a command */
2031 static void call(redisClient
*c
, struct redisCommand
*cmd
) {
2034 dirty
= server
.dirty
;
2036 if (server
.appendonly
&& server
.dirty
-dirty
)
2037 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
2038 if (server
.dirty
-dirty
&& listLength(server
.slaves
))
2039 replicationFeedSlaves(server
.slaves
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
2040 if (listLength(server
.monitors
))
2041 replicationFeedSlaves(server
.monitors
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
2042 server
.stat_numcommands
++;
2045 /* If this function gets called we already read a whole
2046 * command, argments are in the client argv/argc fields.
2047 * processCommand() execute the command or prepare the
2048 * server for a bulk read from the client.
2050 * If 1 is returned the client is still alive and valid and
2051 * and other operations can be performed by the caller. Otherwise
2052 * if 0 is returned the client was destroied (i.e. after QUIT). */
2053 static int processCommand(redisClient
*c
) {
2054 struct redisCommand
*cmd
;
2056 /* Free some memory if needed (maxmemory setting) */
2057 if (server
.maxmemory
) freeMemoryIfNeeded();
2059 /* Handle the multi bulk command type. This is an alternative protocol
2060 * supported by Redis in order to receive commands that are composed of
2061 * multiple binary-safe "bulk" arguments. The latency of processing is
2062 * a bit higher but this allows things like multi-sets, so if this
2063 * protocol is used only for MSET and similar commands this is a big win. */
2064 if (c
->multibulk
== 0 && c
->argc
== 1 && ((char*)(c
->argv
[0]->ptr
))[0] == '*') {
2065 c
->multibulk
= atoi(((char*)c
->argv
[0]->ptr
)+1);
2066 if (c
->multibulk
<= 0) {
2070 decrRefCount(c
->argv
[c
->argc
-1]);
2074 } else if (c
->multibulk
) {
2075 if (c
->bulklen
== -1) {
2076 if (((char*)c
->argv
[0]->ptr
)[0] != '$') {
2077 addReplySds(c
,sdsnew("-ERR multi bulk protocol error\r\n"));
2081 int bulklen
= atoi(((char*)c
->argv
[0]->ptr
)+1);
2082 decrRefCount(c
->argv
[0]);
2083 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
2085 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
2090 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
2094 c
->mbargv
= zrealloc(c
->mbargv
,(sizeof(robj
*))*(c
->mbargc
+1));
2095 c
->mbargv
[c
->mbargc
] = c
->argv
[0];
2099 if (c
->multibulk
== 0) {
2103 /* Here we need to swap the multi-bulk argc/argv with the
2104 * normal argc/argv of the client structure. */
2106 c
->argv
= c
->mbargv
;
2107 c
->mbargv
= auxargv
;
2110 c
->argc
= c
->mbargc
;
2111 c
->mbargc
= auxargc
;
2113 /* We need to set bulklen to something different than -1
2114 * in order for the code below to process the command without
2115 * to try to read the last argument of a bulk command as
2116 * a special argument. */
2118 /* continue below and process the command */
2125 /* -- end of multi bulk commands processing -- */
2127 /* The QUIT command is handled as a special case. Normal command
2128 * procs are unable to close the client connection safely */
2129 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
2134 /* Now lookup the command and check ASAP about trivial error conditions
2135 * such wrong arity, bad command name and so forth. */
2136 cmd
= lookupCommand(c
->argv
[0]->ptr
);
2139 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
2140 (char*)c
->argv
[0]->ptr
));
2143 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
2144 (c
->argc
< -cmd
->arity
)) {
2146 sdscatprintf(sdsempty(),
2147 "-ERR wrong number of arguments for '%s' command\r\n",
2151 } else if (server
.maxmemory
&& cmd
->flags
& REDIS_CMD_DENYOOM
&& zmalloc_used_memory() > server
.maxmemory
) {
2152 addReplySds(c
,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
2155 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
2156 /* This is a bulk command, we have to read the last argument yet. */
2157 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
2159 decrRefCount(c
->argv
[c
->argc
-1]);
2160 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
2162 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
2167 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
2168 /* It is possible that the bulk read is already in the
2169 * buffer. Check this condition and handle it accordingly.
2170 * This is just a fast path, alternative to call processInputBuffer().
2171 * It's a good idea since the code is small and this condition
2172 * happens most of the times. */
2173 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
2174 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2176 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2178 /* Otherwise return... there is to read the last argument
2179 * from the socket. */
2183 /* Let's try to share objects on the command arguments vector */
2184 if (server
.shareobjects
) {
2186 for(j
= 1; j
< c
->argc
; j
++)
2187 c
->argv
[j
] = tryObjectSharing(c
->argv
[j
]);
2189 /* Let's try to encode the bulk object to save space. */
2190 if (cmd
->flags
& REDIS_CMD_BULK
)
2191 tryObjectEncoding(c
->argv
[c
->argc
-1]);
2193 /* Check if the user is authenticated */
2194 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
2195 addReplySds(c
,sdsnew("-ERR operation not permitted\r\n"));
2200 /* Exec the command */
2201 if (c
->flags
& REDIS_MULTI
&& cmd
->proc
!= execCommand
&& cmd
->proc
!= discardCommand
) {
2202 queueMultiCommand(c
,cmd
);
2203 addReply(c
,shared
.queued
);
2205 if (server
.vm_enabled
&& server
.vm_max_threads
> 0 &&
2206 blockClientOnSwappedKeys(cmd
,c
)) return 1;
2210 /* Prepare the client for the next command */
2215 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
2220 /* (args*2)+1 is enough room for args, spaces, newlines */
2221 robj
*static_outv
[REDIS_STATIC_ARGS
*2+1];
2223 if (argc
<= REDIS_STATIC_ARGS
) {
2226 outv
= zmalloc(sizeof(robj
*)*(argc
*2+1));
2229 for (j
= 0; j
< argc
; j
++) {
2230 if (j
!= 0) outv
[outc
++] = shared
.space
;
2231 if ((cmd
->flags
& REDIS_CMD_BULK
) && j
== argc
-1) {
2234 lenobj
= createObject(REDIS_STRING
,
2235 sdscatprintf(sdsempty(),"%lu\r\n",
2236 (unsigned long) stringObjectLen(argv
[j
])));
2237 lenobj
->refcount
= 0;
2238 outv
[outc
++] = lenobj
;
2240 outv
[outc
++] = argv
[j
];
2242 outv
[outc
++] = shared
.crlf
;
2244 /* Increment all the refcounts at start and decrement at end in order to
2245 * be sure to free objects if there is no slave in a replication state
2246 * able to be feed with commands */
2247 for (j
= 0; j
< outc
; j
++) incrRefCount(outv
[j
]);
2248 listRewind(slaves
,&li
);
2249 while((ln
= listNext(&li
))) {
2250 redisClient
*slave
= ln
->value
;
2252 /* Don't feed slaves that are still waiting for BGSAVE to start */
2253 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) continue;
2255 /* Feed all the other slaves, MONITORs and so on */
2256 if (slave
->slaveseldb
!= dictid
) {
2260 case 0: selectcmd
= shared
.select0
; break;
2261 case 1: selectcmd
= shared
.select1
; break;
2262 case 2: selectcmd
= shared
.select2
; break;
2263 case 3: selectcmd
= shared
.select3
; break;
2264 case 4: selectcmd
= shared
.select4
; break;
2265 case 5: selectcmd
= shared
.select5
; break;
2266 case 6: selectcmd
= shared
.select6
; break;
2267 case 7: selectcmd
= shared
.select7
; break;
2268 case 8: selectcmd
= shared
.select8
; break;
2269 case 9: selectcmd
= shared
.select9
; break;
2271 selectcmd
= createObject(REDIS_STRING
,
2272 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
2273 selectcmd
->refcount
= 0;
2276 addReply(slave
,selectcmd
);
2277 slave
->slaveseldb
= dictid
;
2279 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
2281 for (j
= 0; j
< outc
; j
++) decrRefCount(outv
[j
]);
2282 if (outv
!= static_outv
) zfree(outv
);
2285 static void processInputBuffer(redisClient
*c
) {
2287 /* Before to process the input buffer, make sure the client is not
2288 * waitig for a blocking operation such as BLPOP. Note that the first
2289 * iteration the client is never blocked, otherwise the processInputBuffer
2290 * would not be called at all, but after the execution of the first commands
2291 * in the input buffer the client may be blocked, and the "goto again"
2292 * will try to reiterate. The following line will make it return asap. */
2293 if (c
->flags
& REDIS_BLOCKED
|| c
->flags
& REDIS_IO_WAIT
) return;
2294 if (c
->bulklen
== -1) {
2295 /* Read the first line of the query */
2296 char *p
= strchr(c
->querybuf
,'\n');
2303 query
= c
->querybuf
;
2304 c
->querybuf
= sdsempty();
2305 querylen
= 1+(p
-(query
));
2306 if (sdslen(query
) > querylen
) {
2307 /* leave data after the first line of the query in the buffer */
2308 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
2310 *p
= '\0'; /* remove "\n" */
2311 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
2312 sdsupdatelen(query
);
2314 /* Now we can split the query in arguments */
2315 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
2318 if (c
->argv
) zfree(c
->argv
);
2319 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
2321 for (j
= 0; j
< argc
; j
++) {
2322 if (sdslen(argv
[j
])) {
2323 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
2331 /* Execute the command. If the client is still valid
2332 * after processCommand() return and there is something
2333 * on the query buffer try to process the next command. */
2334 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2336 /* Nothing to process, argc == 0. Just process the query
2337 * buffer if it's not empty or return to the caller */
2338 if (sdslen(c
->querybuf
)) goto again
;
2341 } else if (sdslen(c
->querybuf
) >= REDIS_REQUEST_MAX_SIZE
) {
2342 redisLog(REDIS_VERBOSE
, "Client protocol error");
2347 /* Bulk read handling. Note that if we are at this point
2348 the client already sent a command terminated with a newline,
2349 we are reading the bulk data that is actually the last
2350 argument of the command. */
2351 int qbl
= sdslen(c
->querybuf
);
2353 if (c
->bulklen
<= qbl
) {
2354 /* Copy everything but the final CRLF as final argument */
2355 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2357 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2358 /* Process the command. If the client is still valid after
2359 * the processing and there is more data in the buffer
2360 * try to parse it. */
2361 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2367 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2368 redisClient
*c
= (redisClient
*) privdata
;
2369 char buf
[REDIS_IOBUF_LEN
];
2372 REDIS_NOTUSED(mask
);
2374 nread
= read(fd
, buf
, REDIS_IOBUF_LEN
);
2376 if (errno
== EAGAIN
) {
2379 redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
));
2383 } else if (nread
== 0) {
2384 redisLog(REDIS_VERBOSE
, "Client closed connection");
2389 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
2390 c
->lastinteraction
= time(NULL
);
2394 if (!(c
->flags
& REDIS_BLOCKED
))
2395 processInputBuffer(c
);
2398 static int selectDb(redisClient
*c
, int id
) {
2399 if (id
< 0 || id
>= server
.dbnum
)
2401 c
->db
= &server
.db
[id
];
2405 static void *dupClientReplyValue(void *o
) {
2406 incrRefCount((robj
*)o
);
2410 static redisClient
*createClient(int fd
) {
2411 redisClient
*c
= zmalloc(sizeof(*c
));
2413 anetNonBlock(NULL
,fd
);
2414 anetTcpNoDelay(NULL
,fd
);
2415 if (!c
) return NULL
;
2418 c
->querybuf
= sdsempty();
2427 c
->lastinteraction
= time(NULL
);
2428 c
->authenticated
= 0;
2429 c
->replstate
= REDIS_REPL_NONE
;
2430 c
->reply
= listCreate();
2431 listSetFreeMethod(c
->reply
,decrRefCount
);
2432 listSetDupMethod(c
->reply
,dupClientReplyValue
);
2433 c
->blockingkeys
= NULL
;
2434 c
->blockingkeysnum
= 0;
2435 c
->io_keys
= listCreate();
2436 listSetFreeMethod(c
->io_keys
,decrRefCount
);
2437 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
2438 readQueryFromClient
, c
) == AE_ERR
) {
2442 listAddNodeTail(server
.clients
,c
);
2443 initClientMultiState(c
);
2447 static void addReply(redisClient
*c
, robj
*obj
) {
2448 if (listLength(c
->reply
) == 0 &&
2449 (c
->replstate
== REDIS_REPL_NONE
||
2450 c
->replstate
== REDIS_REPL_ONLINE
) &&
2451 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
2452 sendReplyToClient
, c
) == AE_ERR
) return;
2454 if (server
.vm_enabled
&& obj
->storage
!= REDIS_VM_MEMORY
) {
2455 obj
= dupStringObject(obj
);
2456 obj
->refcount
= 0; /* getDecodedObject() will increment the refcount */
2458 listAddNodeTail(c
->reply
,getDecodedObject(obj
));
2461 static void addReplySds(redisClient
*c
, sds s
) {
2462 robj
*o
= createObject(REDIS_STRING
,s
);
2467 static void addReplyDouble(redisClient
*c
, double d
) {
2470 snprintf(buf
,sizeof(buf
),"%.17g",d
);
2471 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
2472 (unsigned long) strlen(buf
),buf
));
2475 static void addReplyLong(redisClient
*c
, long l
) {
2479 len
= snprintf(buf
,sizeof(buf
),":%ld\r\n",l
);
2480 addReplySds(c
,sdsnewlen(buf
,len
));
2483 static void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
2486 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
2487 len
= sdslen(obj
->ptr
);
2489 long n
= (long)obj
->ptr
;
2491 /* Compute how many bytes will take this integer as a radix 10 string */
2497 while((n
= n
/10) != 0) {
2501 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",(unsigned long)len
));
2504 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2509 REDIS_NOTUSED(mask
);
2510 REDIS_NOTUSED(privdata
);
2512 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
2513 if (cfd
== AE_ERR
) {
2514 redisLog(REDIS_VERBOSE
,"Accepting client connection: %s", server
.neterr
);
2517 redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
);
2518 if ((c
= createClient(cfd
)) == NULL
) {
2519 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
2520 close(cfd
); /* May be already closed, just ingore errors */
2523 /* If maxclient directive is set and this is one client more... close the
2524 * connection. Note that we create the client instead to check before
2525 * for this condition, since now the socket is already set in nonblocking
2526 * mode and we can send an error for free using the Kernel I/O */
2527 if (server
.maxclients
&& listLength(server
.clients
) > server
.maxclients
) {
2528 char *err
= "-ERR max number of clients reached\r\n";
2530 /* That's a best effort error message, don't check write errors */
2531 if (write(c
->fd
,err
,strlen(err
)) == -1) {
2532 /* Nothing to do, Just to avoid the warning... */
2537 server
.stat_numconnections
++;
2540 /* ======================= Redis objects implementation ===================== */
2542 static robj
*createObject(int type
, void *ptr
) {
2545 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
2546 if (listLength(server
.objfreelist
)) {
2547 listNode
*head
= listFirst(server
.objfreelist
);
2548 o
= listNodeValue(head
);
2549 listDelNode(server
.objfreelist
,head
);
2550 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2552 if (server
.vm_enabled
) {
2553 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2554 o
= zmalloc(sizeof(*o
));
2556 o
= zmalloc(sizeof(*o
)-sizeof(struct redisObjectVM
));
2560 o
->encoding
= REDIS_ENCODING_RAW
;
2563 if (server
.vm_enabled
) {
2564 /* Note that this code may run in the context of an I/O thread
2565 * and accessing to server.unixtime in theory is an error
2566 * (no locks). But in practice this is safe, and even if we read
2567 * garbage Redis will not fail, as it's just a statistical info */
2568 o
->vm
.atime
= server
.unixtime
;
2569 o
->storage
= REDIS_VM_MEMORY
;
2574 static robj
*createStringObject(char *ptr
, size_t len
) {
2575 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
2578 static robj
*dupStringObject(robj
*o
) {
2579 assert(o
->encoding
== REDIS_ENCODING_RAW
);
2580 return createStringObject(o
->ptr
,sdslen(o
->ptr
));
2583 static robj
*createListObject(void) {
2584 list
*l
= listCreate();
2586 listSetFreeMethod(l
,decrRefCount
);
2587 return createObject(REDIS_LIST
,l
);
2590 static robj
*createSetObject(void) {
2591 dict
*d
= dictCreate(&setDictType
,NULL
);
2592 return createObject(REDIS_SET
,d
);
2595 static robj
*createHashObject(void) {
2596 /* All the Hashes start as zipmaps. Will be automatically converted
2597 * into hash tables if there are enough elements or big elements
2599 unsigned char *zm
= zipmapNew();
2600 robj
*o
= createObject(REDIS_HASH
,zm
);
2601 o
->encoding
= REDIS_ENCODING_ZIPMAP
;
2605 static robj
*createZsetObject(void) {
2606 zset
*zs
= zmalloc(sizeof(*zs
));
2608 zs
->dict
= dictCreate(&zsetDictType
,NULL
);
2609 zs
->zsl
= zslCreate();
2610 return createObject(REDIS_ZSET
,zs
);
2613 static void freeStringObject(robj
*o
) {
2614 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2619 static void freeListObject(robj
*o
) {
2620 listRelease((list
*) o
->ptr
);
2623 static void freeSetObject(robj
*o
) {
2624 dictRelease((dict
*) o
->ptr
);
2627 static void freeZsetObject(robj
*o
) {
2630 dictRelease(zs
->dict
);
2635 static void freeHashObject(robj
*o
) {
2636 switch (o
->encoding
) {
2637 case REDIS_ENCODING_HT
:
2638 dictRelease((dict
*) o
->ptr
);
2640 case REDIS_ENCODING_ZIPMAP
:
2649 static void incrRefCount(robj
*o
) {
2650 redisAssert(!server
.vm_enabled
|| o
->storage
== REDIS_VM_MEMORY
);
2654 static void decrRefCount(void *obj
) {
2657 /* Object is a key of a swapped out value, or in the process of being
2659 if (server
.vm_enabled
&&
2660 (o
->storage
== REDIS_VM_SWAPPED
|| o
->storage
== REDIS_VM_LOADING
))
2662 if (o
->storage
== REDIS_VM_SWAPPED
|| o
->storage
== REDIS_VM_LOADING
) {
2663 redisAssert(o
->refcount
== 1);
2665 if (o
->storage
== REDIS_VM_LOADING
) vmCancelThreadedIOJob(obj
);
2666 redisAssert(o
->type
== REDIS_STRING
);
2667 freeStringObject(o
);
2668 vmMarkPagesFree(o
->vm
.page
,o
->vm
.usedpages
);
2669 pthread_mutex_lock(&server
.obj_freelist_mutex
);
2670 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2671 !listAddNodeHead(server
.objfreelist
,o
))
2673 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2674 server
.vm_stats_swapped_objects
--;
2677 /* Object is in memory, or in the process of being swapped out. */
2678 if (--(o
->refcount
) == 0) {
2679 if (server
.vm_enabled
&& o
->storage
== REDIS_VM_SWAPPING
)
2680 vmCancelThreadedIOJob(obj
);
2682 case REDIS_STRING
: freeStringObject(o
); break;
2683 case REDIS_LIST
: freeListObject(o
); break;
2684 case REDIS_SET
: freeSetObject(o
); break;
2685 case REDIS_ZSET
: freeZsetObject(o
); break;
2686 case REDIS_HASH
: freeHashObject(o
); break;
2687 default: redisAssert(0 != 0); break;
2689 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
2690 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2691 !listAddNodeHead(server
.objfreelist
,o
))
2693 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2697 static robj
*lookupKey(redisDb
*db
, robj
*key
) {
2698 dictEntry
*de
= dictFind(db
->dict
,key
);
2700 robj
*key
= dictGetEntryKey(de
);
2701 robj
*val
= dictGetEntryVal(de
);
2703 if (server
.vm_enabled
) {
2704 if (key
->storage
== REDIS_VM_MEMORY
||
2705 key
->storage
== REDIS_VM_SWAPPING
)
2707 /* If we were swapping the object out, stop it, this key
2709 if (key
->storage
== REDIS_VM_SWAPPING
)
2710 vmCancelThreadedIOJob(key
);
2711 /* Update the access time of the key for the aging algorithm. */
2712 key
->vm
.atime
= server
.unixtime
;
2714 int notify
= (key
->storage
== REDIS_VM_LOADING
);
2716 /* Our value was swapped on disk. Bring it at home. */
2717 redisAssert(val
== NULL
);
2718 val
= vmLoadObject(key
);
2719 dictGetEntryVal(de
) = val
;
2721 /* Clients blocked by the VM subsystem may be waiting for
2723 if (notify
) handleClientsBlockedOnSwappedKey(db
,key
);
2732 static robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
2733 expireIfNeeded(db
,key
);
2734 return lookupKey(db
,key
);
2737 static robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
2738 deleteIfVolatile(db
,key
);
2739 return lookupKey(db
,key
);
2742 static int deleteKey(redisDb
*db
, robj
*key
) {
2745 /* We need to protect key from destruction: after the first dictDelete()
2746 * it may happen that 'key' is no longer valid if we don't increment
2747 * it's count. This may happen when we get the object reference directly
2748 * from the hash table with dictRandomKey() or dict iterators */
2750 if (dictSize(db
->expires
)) dictDelete(db
->expires
,key
);
2751 retval
= dictDelete(db
->dict
,key
);
2754 return retval
== DICT_OK
;
2757 /* Try to share an object against the shared objects pool */
2758 static robj
*tryObjectSharing(robj
*o
) {
2759 struct dictEntry
*de
;
2762 if (o
== NULL
|| server
.shareobjects
== 0) return o
;
2764 redisAssert(o
->type
== REDIS_STRING
);
2765 de
= dictFind(server
.sharingpool
,o
);
2767 robj
*shared
= dictGetEntryKey(de
);
2769 c
= ((unsigned long) dictGetEntryVal(de
))+1;
2770 dictGetEntryVal(de
) = (void*) c
;
2771 incrRefCount(shared
);
2775 /* Here we are using a stream algorihtm: Every time an object is
2776 * shared we increment its count, everytime there is a miss we
2777 * recrement the counter of a random object. If this object reaches
2778 * zero we remove the object and put the current object instead. */
2779 if (dictSize(server
.sharingpool
) >=
2780 server
.sharingpoolsize
) {
2781 de
= dictGetRandomKey(server
.sharingpool
);
2782 redisAssert(de
!= NULL
);
2783 c
= ((unsigned long) dictGetEntryVal(de
))-1;
2784 dictGetEntryVal(de
) = (void*) c
;
2786 dictDelete(server
.sharingpool
,de
->key
);
2789 c
= 0; /* If the pool is empty we want to add this object */
2794 retval
= dictAdd(server
.sharingpool
,o
,(void*)1);
2795 redisAssert(retval
== DICT_OK
);
2802 /* Check if the nul-terminated string 's' can be represented by a long
2803 * (that is, is a number that fits into long without any other space or
2804 * character before or after the digits).
2806 * If so, the function returns REDIS_OK and *longval is set to the value
2807 * of the number. Otherwise REDIS_ERR is returned */
2808 static int isStringRepresentableAsLong(sds s
, long *longval
) {
2809 char buf
[32], *endptr
;
2813 value
= strtol(s
, &endptr
, 10);
2814 if (endptr
[0] != '\0') return REDIS_ERR
;
2815 slen
= snprintf(buf
,32,"%ld",value
);
2817 /* If the number converted back into a string is not identical
2818 * then it's not possible to encode the string as integer */
2819 if (sdslen(s
) != (unsigned)slen
|| memcmp(buf
,s
,slen
)) return REDIS_ERR
;
2820 if (longval
) *longval
= value
;
2824 /* Try to encode a string object in order to save space */
2825 static int tryObjectEncoding(robj
*o
) {
2829 if (o
->encoding
!= REDIS_ENCODING_RAW
)
2830 return REDIS_ERR
; /* Already encoded */
2832 /* It's not save to encode shared objects: shared objects can be shared
2833 * everywhere in the "object space" of Redis. Encoded objects can only
2834 * appear as "values" (and not, for instance, as keys) */
2835 if (o
->refcount
> 1) return REDIS_ERR
;
2837 /* Currently we try to encode only strings */
2838 redisAssert(o
->type
== REDIS_STRING
);
2840 /* Check if we can represent this string as a long integer */
2841 if (isStringRepresentableAsLong(s
,&value
) == REDIS_ERR
) return REDIS_ERR
;
2843 /* Ok, this object can be encoded */
2844 o
->encoding
= REDIS_ENCODING_INT
;
2846 o
->ptr
= (void*) value
;
2850 /* Get a decoded version of an encoded object (returned as a new object).
2851 * If the object is already raw-encoded just increment the ref count. */
2852 static robj
*getDecodedObject(robj
*o
) {
2855 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2859 if (o
->type
== REDIS_STRING
&& o
->encoding
== REDIS_ENCODING_INT
) {
2862 snprintf(buf
,32,"%ld",(long)o
->ptr
);
2863 dec
= createStringObject(buf
,strlen(buf
));
2866 redisAssert(1 != 1);
2870 /* Compare two string objects via strcmp() or alike.
2871 * Note that the objects may be integer-encoded. In such a case we
2872 * use snprintf() to get a string representation of the numbers on the stack
2873 * and compare the strings, it's much faster than calling getDecodedObject().
2875 * Important note: if objects are not integer encoded, but binary-safe strings,
2876 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
2878 static int compareStringObjects(robj
*a
, robj
*b
) {
2879 redisAssert(a
->type
== REDIS_STRING
&& b
->type
== REDIS_STRING
);
2880 char bufa
[128], bufb
[128], *astr
, *bstr
;
2883 if (a
== b
) return 0;
2884 if (a
->encoding
!= REDIS_ENCODING_RAW
) {
2885 snprintf(bufa
,sizeof(bufa
),"%ld",(long) a
->ptr
);
2891 if (b
->encoding
!= REDIS_ENCODING_RAW
) {
2892 snprintf(bufb
,sizeof(bufb
),"%ld",(long) b
->ptr
);
2898 return bothsds
? sdscmp(astr
,bstr
) : strcmp(astr
,bstr
);
2901 static size_t stringObjectLen(robj
*o
) {
2902 redisAssert(o
->type
== REDIS_STRING
);
2903 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2904 return sdslen(o
->ptr
);
2908 return snprintf(buf
,32,"%ld",(long)o
->ptr
);
2912 /*============================ RDB saving/loading =========================== */
2914 static int rdbSaveType(FILE *fp
, unsigned char type
) {
2915 if (fwrite(&type
,1,1,fp
) == 0) return -1;
2919 static int rdbSaveTime(FILE *fp
, time_t t
) {
2920 int32_t t32
= (int32_t) t
;
2921 if (fwrite(&t32
,4,1,fp
) == 0) return -1;
2925 /* check rdbLoadLen() comments for more info */
2926 static int rdbSaveLen(FILE *fp
, uint32_t len
) {
2927 unsigned char buf
[2];
2930 /* Save a 6 bit len */
2931 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
2932 if (fwrite(buf
,1,1,fp
) == 0) return -1;
2933 } else if (len
< (1<<14)) {
2934 /* Save a 14 bit len */
2935 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
2937 if (fwrite(buf
,2,1,fp
) == 0) return -1;
2939 /* Save a 32 bit len */
2940 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
2941 if (fwrite(buf
,1,1,fp
) == 0) return -1;
2943 if (fwrite(&len
,4,1,fp
) == 0) return -1;
2948 /* String objects in the form "2391" "-100" without any space and with a
2949 * range of values that can fit in an 8, 16 or 32 bit signed value can be
2950 * encoded as integers to save space */
2951 static int rdbTryIntegerEncoding(char *s
, size_t len
, unsigned char *enc
) {
2953 char *endptr
, buf
[32];
2955 /* Check if it's possible to encode this value as a number */
2956 value
= strtoll(s
, &endptr
, 10);
2957 if (endptr
[0] != '\0') return 0;
2958 snprintf(buf
,32,"%lld",value
);
2960 /* If the number converted back into a string is not identical
2961 * then it's not possible to encode the string as integer */
2962 if (strlen(buf
) != len
|| memcmp(buf
,s
,len
)) return 0;
2964 /* Finally check if it fits in our ranges */
2965 if (value
>= -(1<<7) && value
<= (1<<7)-1) {
2966 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT8
;
2967 enc
[1] = value
&0xFF;
2969 } else if (value
>= -(1<<15) && value
<= (1<<15)-1) {
2970 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
;
2971 enc
[1] = value
&0xFF;
2972 enc
[2] = (value
>>8)&0xFF;
2974 } else if (value
>= -((long long)1<<31) && value
<= ((long long)1<<31)-1) {
2975 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT32
;
2976 enc
[1] = value
&0xFF;
2977 enc
[2] = (value
>>8)&0xFF;
2978 enc
[3] = (value
>>16)&0xFF;
2979 enc
[4] = (value
>>24)&0xFF;
2986 static int rdbSaveLzfStringObject(FILE *fp
, unsigned char *s
, size_t len
) {
2987 size_t comprlen
, outlen
;
2991 /* We require at least four bytes compression for this to be worth it */
2992 if (len
<= 4) return 0;
2994 if ((out
= zmalloc(outlen
+1)) == NULL
) return 0;
2995 comprlen
= lzf_compress(s
, len
, out
, outlen
);
2996 if (comprlen
== 0) {
3000 /* Data compressed! Let's save it on disk */
3001 byte
= (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_LZF
;
3002 if (fwrite(&byte
,1,1,fp
) == 0) goto writeerr
;
3003 if (rdbSaveLen(fp
,comprlen
) == -1) goto writeerr
;
3004 if (rdbSaveLen(fp
,len
) == -1) goto writeerr
;
3005 if (fwrite(out
,comprlen
,1,fp
) == 0) goto writeerr
;
3014 /* Save a string objet as [len][data] on disk. If the object is a string
3015 * representation of an integer value we try to safe it in a special form */
3016 static int rdbSaveRawString(FILE *fp
, unsigned char *s
, size_t len
) {
3019 /* Try integer encoding */
3021 unsigned char buf
[5];
3022 if ((enclen
= rdbTryIntegerEncoding((char*)s
,len
,buf
)) > 0) {
3023 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
3028 /* Try LZF compression - under 20 bytes it's unable to compress even
3029 * aaaaaaaaaaaaaaaaaa so skip it */
3030 if (server
.rdbcompression
&& len
> 20) {
3033 retval
= rdbSaveLzfStringObject(fp
,s
,len
);
3034 if (retval
== -1) return -1;
3035 if (retval
> 0) return 0;
3036 /* retval == 0 means data can't be compressed, save the old way */
3039 /* Store verbatim */
3040 if (rdbSaveLen(fp
,len
) == -1) return -1;
3041 if (len
&& fwrite(s
,len
,1,fp
) == 0) return -1;
3045 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
3046 static int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
3049 /* Avoid incr/decr ref count business when possible.
3050 * This plays well with copy-on-write given that we are probably
3051 * in a child process (BGSAVE). Also this makes sure key objects
3052 * of swapped objects are not incRefCount-ed (an assert does not allow
3053 * this in order to avoid bugs) */
3054 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
3055 obj
= getDecodedObject(obj
);
3056 retval
= rdbSaveRawString(fp
,obj
->ptr
,sdslen(obj
->ptr
));
3059 retval
= rdbSaveRawString(fp
,obj
->ptr
,sdslen(obj
->ptr
));
3064 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
3065 * 8 bit integer specifing the length of the representation.
3066 * This 8 bit integer has special values in order to specify the following
3072 static int rdbSaveDoubleValue(FILE *fp
, double val
) {
3073 unsigned char buf
[128];
3079 } else if (!isfinite(val
)) {
3081 buf
[0] = (val
< 0) ? 255 : 254;
3083 snprintf((char*)buf
+1,sizeof(buf
)-1,"%.17g",val
);
3084 buf
[0] = strlen((char*)buf
+1);
3087 if (fwrite(buf
,len
,1,fp
) == 0) return -1;
3091 /* Save a Redis object. */
3092 static int rdbSaveObject(FILE *fp
, robj
*o
) {
3093 if (o
->type
== REDIS_STRING
) {
3094 /* Save a string value */
3095 if (rdbSaveStringObject(fp
,o
) == -1) return -1;
3096 } else if (o
->type
== REDIS_LIST
) {
3097 /* Save a list value */
3098 list
*list
= o
->ptr
;
3102 if (rdbSaveLen(fp
,listLength(list
)) == -1) return -1;
3103 listRewind(list
,&li
);
3104 while((ln
= listNext(&li
))) {
3105 robj
*eleobj
= listNodeValue(ln
);
3107 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
3109 } else if (o
->type
== REDIS_SET
) {
3110 /* Save a set value */
3112 dictIterator
*di
= dictGetIterator(set
);
3115 if (rdbSaveLen(fp
,dictSize(set
)) == -1) return -1;
3116 while((de
= dictNext(di
)) != NULL
) {
3117 robj
*eleobj
= dictGetEntryKey(de
);
3119 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
3121 dictReleaseIterator(di
);
3122 } else if (o
->type
== REDIS_ZSET
) {
3123 /* Save a set value */
3125 dictIterator
*di
= dictGetIterator(zs
->dict
);
3128 if (rdbSaveLen(fp
,dictSize(zs
->dict
)) == -1) return -1;
3129 while((de
= dictNext(di
)) != NULL
) {
3130 robj
*eleobj
= dictGetEntryKey(de
);
3131 double *score
= dictGetEntryVal(de
);
3133 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
3134 if (rdbSaveDoubleValue(fp
,*score
) == -1) return -1;
3136 dictReleaseIterator(di
);
3137 } else if (o
->type
== REDIS_HASH
) {
3138 /* Save a hash value */
3139 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
3140 unsigned char *p
= zipmapRewind(o
->ptr
);
3141 unsigned int count
= zipmapLen(o
->ptr
);
3142 unsigned char *key
, *val
;
3143 unsigned int klen
, vlen
;
3145 if (rdbSaveLen(fp
,count
) == -1) return -1;
3146 while((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) != NULL
) {
3147 if (rdbSaveRawString(fp
,key
,klen
) == -1) return -1;
3148 if (rdbSaveRawString(fp
,val
,vlen
) == -1) return -1;
3151 dictIterator
*di
= dictGetIterator(o
->ptr
);
3154 if (rdbSaveLen(fp
,dictSize((dict
*)o
->ptr
)) == -1) return -1;
3155 while((de
= dictNext(di
)) != NULL
) {
3156 robj
*key
= dictGetEntryKey(de
);
3157 robj
*val
= dictGetEntryVal(de
);
3159 if (rdbSaveStringObject(fp
,key
) == -1) return -1;
3160 if (rdbSaveStringObject(fp
,val
) == -1) return -1;
3162 dictReleaseIterator(di
);
3165 redisAssert(0 != 0);
3170 /* Return the length the object will have on disk if saved with
3171 * the rdbSaveObject() function. Currently we use a trick to get
3172 * this length with very little changes to the code. In the future
3173 * we could switch to a faster solution. */
3174 static off_t
rdbSavedObjectLen(robj
*o
, FILE *fp
) {
3175 if (fp
== NULL
) fp
= server
.devnull
;
3177 assert(rdbSaveObject(fp
,o
) != 1);
3181 /* Return the number of pages required to save this object in the swap file */
3182 static off_t
rdbSavedObjectPages(robj
*o
, FILE *fp
) {
3183 off_t bytes
= rdbSavedObjectLen(o
,fp
);
3185 return (bytes
+(server
.vm_page_size
-1))/server
.vm_page_size
;
3188 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
3189 static int rdbSave(char *filename
) {
3190 dictIterator
*di
= NULL
;
3195 time_t now
= time(NULL
);
3197 /* Wait for I/O therads to terminate, just in case this is a
3198 * foreground-saving, to avoid seeking the swap file descriptor at the
3200 if (server
.vm_enabled
)
3201 waitEmptyIOJobsQueue();
3203 snprintf(tmpfile
,256,"temp-%d.rdb", (int) getpid());
3204 fp
= fopen(tmpfile
,"w");
3206 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
3209 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
3210 for (j
= 0; j
< server
.dbnum
; j
++) {
3211 redisDb
*db
= server
.db
+j
;
3213 if (dictSize(d
) == 0) continue;
3214 di
= dictGetIterator(d
);
3220 /* Write the SELECT DB opcode */
3221 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
3222 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
3224 /* Iterate this DB writing every entry */
3225 while((de
= dictNext(di
)) != NULL
) {
3226 robj
*key
= dictGetEntryKey(de
);
3227 robj
*o
= dictGetEntryVal(de
);
3228 time_t expiretime
= getExpire(db
,key
);
3230 /* Save the expire time */
3231 if (expiretime
!= -1) {
3232 /* If this key is already expired skip it */
3233 if (expiretime
< now
) continue;
3234 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
;
3235 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
;
3237 /* Save the key and associated value. This requires special
3238 * handling if the value is swapped out. */
3239 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
3240 key
->storage
== REDIS_VM_SWAPPING
) {
3241 /* Save type, key, value */
3242 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
3243 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3244 if (rdbSaveObject(fp
,o
) == -1) goto werr
;
3246 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
3248 /* Get a preview of the object in memory */
3249 po
= vmPreviewObject(key
);
3250 /* Save type, key, value */
3251 if (rdbSaveType(fp
,key
->vtype
) == -1) goto werr
;
3252 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3253 if (rdbSaveObject(fp
,po
) == -1) goto werr
;
3254 /* Remove the loaded object from memory */
3258 dictReleaseIterator(di
);
3261 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
3263 /* Make sure data will not remain on the OS's output buffers */
3268 /* Use RENAME to make sure the DB file is changed atomically only
3269 * if the generate DB file is ok. */
3270 if (rename(tmpfile
,filename
) == -1) {
3271 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destination: %s", strerror(errno
));
3275 redisLog(REDIS_NOTICE
,"DB saved on disk");
3277 server
.lastsave
= time(NULL
);
3283 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
3284 if (di
) dictReleaseIterator(di
);
3288 static int rdbSaveBackground(char *filename
) {
3291 if (server
.bgsavechildpid
!= -1) return REDIS_ERR
;
3292 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
3293 if ((childpid
= fork()) == 0) {
3295 if (server
.vm_enabled
) vmReopenSwapFile();
3297 if (rdbSave(filename
) == REDIS_OK
) {
3304 if (childpid
== -1) {
3305 redisLog(REDIS_WARNING
,"Can't save in background: fork: %s",
3309 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
3310 server
.bgsavechildpid
= childpid
;
3313 return REDIS_OK
; /* unreached */
3316 static void rdbRemoveTempFile(pid_t childpid
) {
3319 snprintf(tmpfile
,256,"temp-%d.rdb", (int) childpid
);
3323 static int rdbLoadType(FILE *fp
) {
3325 if (fread(&type
,1,1,fp
) == 0) return -1;
3329 static time_t rdbLoadTime(FILE *fp
) {
3331 if (fread(&t32
,4,1,fp
) == 0) return -1;
3332 return (time_t) t32
;
3335 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
3336 * of this file for a description of how this are stored on disk.
3338 * isencoded is set to 1 if the readed length is not actually a length but
3339 * an "encoding type", check the above comments for more info */
3340 static uint32_t rdbLoadLen(FILE *fp
, int *isencoded
) {
3341 unsigned char buf
[2];
3345 if (isencoded
) *isencoded
= 0;
3346 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3347 type
= (buf
[0]&0xC0)>>6;
3348 if (type
== REDIS_RDB_6BITLEN
) {
3349 /* Read a 6 bit len */
3351 } else if (type
== REDIS_RDB_ENCVAL
) {
3352 /* Read a 6 bit len encoding type */
3353 if (isencoded
) *isencoded
= 1;
3355 } else if (type
== REDIS_RDB_14BITLEN
) {
3356 /* Read a 14 bit len */
3357 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3358 return ((buf
[0]&0x3F)<<8)|buf
[1];
3360 /* Read a 32 bit len */
3361 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
3366 static robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
) {
3367 unsigned char enc
[4];
3370 if (enctype
== REDIS_RDB_ENC_INT8
) {
3371 if (fread(enc
,1,1,fp
) == 0) return NULL
;
3372 val
= (signed char)enc
[0];
3373 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
3375 if (fread(enc
,2,1,fp
) == 0) return NULL
;
3376 v
= enc
[0]|(enc
[1]<<8);
3378 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
3380 if (fread(enc
,4,1,fp
) == 0) return NULL
;
3381 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
3384 val
= 0; /* anti-warning */
3387 return createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",val
));
3390 static robj
*rdbLoadLzfStringObject(FILE*fp
) {
3391 unsigned int len
, clen
;
3392 unsigned char *c
= NULL
;
3395 if ((clen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3396 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3397 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
3398 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
3399 if (fread(c
,clen
,1,fp
) == 0) goto err
;
3400 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
3402 return createObject(REDIS_STRING
,val
);
3409 static robj
*rdbLoadStringObject(FILE*fp
) {
3414 len
= rdbLoadLen(fp
,&isencoded
);
3417 case REDIS_RDB_ENC_INT8
:
3418 case REDIS_RDB_ENC_INT16
:
3419 case REDIS_RDB_ENC_INT32
:
3420 return tryObjectSharing(rdbLoadIntegerObject(fp
,len
));
3421 case REDIS_RDB_ENC_LZF
:
3422 return tryObjectSharing(rdbLoadLzfStringObject(fp
));
3428 if (len
== REDIS_RDB_LENERR
) return NULL
;
3429 val
= sdsnewlen(NULL
,len
);
3430 if (len
&& fread(val
,len
,1,fp
) == 0) {
3434 return tryObjectSharing(createObject(REDIS_STRING
,val
));
3437 /* For information about double serialization check rdbSaveDoubleValue() */
3438 static int rdbLoadDoubleValue(FILE *fp
, double *val
) {
3442 if (fread(&len
,1,1,fp
) == 0) return -1;
3444 case 255: *val
= R_NegInf
; return 0;
3445 case 254: *val
= R_PosInf
; return 0;
3446 case 253: *val
= R_Nan
; return 0;
3448 if (fread(buf
,len
,1,fp
) == 0) return -1;
3450 sscanf(buf
, "%lg", val
);
3455 /* Load a Redis object of the specified type from the specified file.
3456 * On success a newly allocated object is returned, otherwise NULL. */
3457 static robj
*rdbLoadObject(int type
, FILE *fp
) {
3460 redisLog(REDIS_DEBUG
,"LOADING OBJECT %d (at %d)\n",type
,ftell(fp
));
3461 if (type
== REDIS_STRING
) {
3462 /* Read string value */
3463 if ((o
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3464 tryObjectEncoding(o
);
3465 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
3466 /* Read list/set value */
3469 if ((listlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3470 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
3471 /* It's faster to expand the dict to the right size asap in order
3472 * to avoid rehashing */
3473 if (type
== REDIS_SET
&& listlen
> DICT_HT_INITIAL_SIZE
)
3474 dictExpand(o
->ptr
,listlen
);
3475 /* Load every single element of the list/set */
3479 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3480 tryObjectEncoding(ele
);
3481 if (type
== REDIS_LIST
) {
3482 listAddNodeTail((list
*)o
->ptr
,ele
);
3484 dictAdd((dict
*)o
->ptr
,ele
,NULL
);
3487 } else if (type
== REDIS_ZSET
) {
3488 /* Read list/set value */
3492 if ((zsetlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3493 o
= createZsetObject();
3495 /* Load every single element of the list/set */
3498 double *score
= zmalloc(sizeof(double));
3500 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3501 tryObjectEncoding(ele
);
3502 if (rdbLoadDoubleValue(fp
,score
) == -1) return NULL
;
3503 dictAdd(zs
->dict
,ele
,score
);
3504 zslInsert(zs
->zsl
,*score
,ele
);
3505 incrRefCount(ele
); /* added to skiplist */
3507 } else if (type
== REDIS_HASH
) {
3510 if ((hashlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3511 o
= createHashObject();
3512 /* Too many entries? Use an hash table. */
3513 if (hashlen
> server
.hash_max_zipmap_entries
)
3514 convertToRealHash(o
);
3515 /* Load every key/value, then set it into the zipmap or hash
3516 * table, as needed. */
3520 if ((key
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3521 if ((val
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3522 /* If we are using a zipmap and there are too big values
3523 * the object is converted to real hash table encoding. */
3524 if (o
->encoding
!= REDIS_ENCODING_HT
&&
3525 (sdslen(key
->ptr
) > server
.hash_max_zipmap_value
||
3526 sdslen(val
->ptr
) > server
.hash_max_zipmap_value
))
3528 convertToRealHash(o
);
3531 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
3532 unsigned char *zm
= o
->ptr
;
3534 zm
= zipmapSet(zm
,key
->ptr
,sdslen(key
->ptr
),
3535 val
->ptr
,sdslen(val
->ptr
),NULL
);
3540 tryObjectEncoding(key
);
3541 tryObjectEncoding(val
);
3542 dictAdd((dict
*)o
->ptr
,key
,val
);
3548 redisAssert(0 != 0);
3553 static int rdbLoad(char *filename
) {
3555 robj
*keyobj
= NULL
;
3557 int type
, retval
, rdbver
;
3558 dict
*d
= server
.db
[0].dict
;
3559 redisDb
*db
= server
.db
+0;
3561 time_t expiretime
= -1, now
= time(NULL
);
3562 long long loadedkeys
= 0;
3564 fp
= fopen(filename
,"r");
3565 if (!fp
) return REDIS_ERR
;
3566 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
3568 if (memcmp(buf
,"REDIS",5) != 0) {
3570 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
3573 rdbver
= atoi(buf
+5);
3576 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
3583 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3584 if (type
== REDIS_EXPIRETIME
) {
3585 if ((expiretime
= rdbLoadTime(fp
)) == -1) goto eoferr
;
3586 /* We read the time so we need to read the object type again */
3587 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3589 if (type
== REDIS_EOF
) break;
3590 /* Handle SELECT DB opcode as a special case */
3591 if (type
== REDIS_SELECTDB
) {
3592 if ((dbid
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
)
3594 if (dbid
>= (unsigned)server
.dbnum
) {
3595 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
3598 db
= server
.db
+dbid
;
3603 if ((keyobj
= rdbLoadStringObject(fp
)) == NULL
) goto eoferr
;
3605 if ((o
= rdbLoadObject(type
,fp
)) == NULL
) goto eoferr
;
3606 /* Add the new object in the hash table */
3607 retval
= dictAdd(d
,keyobj
,o
);
3608 if (retval
== DICT_ERR
) {
3609 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj
->ptr
);
3612 /* Set the expire time if needed */
3613 if (expiretime
!= -1) {
3614 setExpire(db
,keyobj
,expiretime
);
3615 /* Delete this key if already expired */
3616 if (expiretime
< now
) deleteKey(db
,keyobj
);
3620 /* Handle swapping while loading big datasets when VM is on */
3622 if (server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
3623 while (zmalloc_used_memory() > server
.vm_max_memory
) {
3624 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
3631 eoferr
: /* unexpected end of file is handled here with a fatal exit */
3632 if (keyobj
) decrRefCount(keyobj
);
3633 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
3635 return REDIS_ERR
; /* Just to avoid warning */
3638 /*================================== Commands =============================== */
3640 static void authCommand(redisClient
*c
) {
3641 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
3642 c
->authenticated
= 1;
3643 addReply(c
,shared
.ok
);
3645 c
->authenticated
= 0;
3646 addReplySds(c
,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
3650 static void pingCommand(redisClient
*c
) {
3651 addReply(c
,shared
.pong
);
3654 static void echoCommand(redisClient
*c
) {
3655 addReplyBulkLen(c
,c
->argv
[1]);
3656 addReply(c
,c
->argv
[1]);
3657 addReply(c
,shared
.crlf
);
3660 /*=================================== Strings =============================== */
3662 static void setGenericCommand(redisClient
*c
, int nx
) {
3665 if (nx
) deleteIfVolatile(c
->db
,c
->argv
[1]);
3666 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3667 if (retval
== DICT_ERR
) {
3669 /* If the key is about a swapped value, we want a new key object
3670 * to overwrite the old. So we delete the old key in the database.
3671 * This will also make sure that swap pages about the old object
3672 * will be marked as free. */
3673 if (server
.vm_enabled
&& deleteIfSwapped(c
->db
,c
->argv
[1]))
3674 incrRefCount(c
->argv
[1]);
3675 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3676 incrRefCount(c
->argv
[2]);
3678 addReply(c
,shared
.czero
);
3682 incrRefCount(c
->argv
[1]);
3683 incrRefCount(c
->argv
[2]);
3686 removeExpire(c
->db
,c
->argv
[1]);
3687 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3690 static void setCommand(redisClient
*c
) {
3691 setGenericCommand(c
,0);
3694 static void setnxCommand(redisClient
*c
) {
3695 setGenericCommand(c
,1);
3698 static int getGenericCommand(redisClient
*c
) {
3699 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3702 addReply(c
,shared
.nullbulk
);
3705 if (o
->type
!= REDIS_STRING
) {
3706 addReply(c
,shared
.wrongtypeerr
);
3709 addReplyBulkLen(c
,o
);
3711 addReply(c
,shared
.crlf
);
3717 static void getCommand(redisClient
*c
) {
3718 getGenericCommand(c
);
3721 static void getsetCommand(redisClient
*c
) {
3722 if (getGenericCommand(c
) == REDIS_ERR
) return;
3723 if (dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]) == DICT_ERR
) {
3724 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3726 incrRefCount(c
->argv
[1]);
3728 incrRefCount(c
->argv
[2]);
3730 removeExpire(c
->db
,c
->argv
[1]);
3733 static void mgetCommand(redisClient
*c
) {
3736 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
3737 for (j
= 1; j
< c
->argc
; j
++) {
3738 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[j
]);
3740 addReply(c
,shared
.nullbulk
);
3742 if (o
->type
!= REDIS_STRING
) {
3743 addReply(c
,shared
.nullbulk
);
3745 addReplyBulkLen(c
,o
);
3747 addReply(c
,shared
.crlf
);
3753 static void msetGenericCommand(redisClient
*c
, int nx
) {
3754 int j
, busykeys
= 0;
3756 if ((c
->argc
% 2) == 0) {
3757 addReplySds(c
,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
3760 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
3761 * set nothing at all if at least one already key exists. */
3763 for (j
= 1; j
< c
->argc
; j
+= 2) {
3764 if (lookupKeyWrite(c
->db
,c
->argv
[j
]) != NULL
) {
3770 addReply(c
, shared
.czero
);
3774 for (j
= 1; j
< c
->argc
; j
+= 2) {
3777 tryObjectEncoding(c
->argv
[j
+1]);
3778 retval
= dictAdd(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3779 if (retval
== DICT_ERR
) {
3780 dictReplace(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3781 incrRefCount(c
->argv
[j
+1]);
3783 incrRefCount(c
->argv
[j
]);
3784 incrRefCount(c
->argv
[j
+1]);
3786 removeExpire(c
->db
,c
->argv
[j
]);
3788 server
.dirty
+= (c
->argc
-1)/2;
3789 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3792 static void msetCommand(redisClient
*c
) {
3793 msetGenericCommand(c
,0);
3796 static void msetnxCommand(redisClient
*c
) {
3797 msetGenericCommand(c
,1);
3800 static void incrDecrCommand(redisClient
*c
, long long incr
) {
3805 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3809 if (o
->type
!= REDIS_STRING
) {
3814 if (o
->encoding
== REDIS_ENCODING_RAW
)
3815 value
= strtoll(o
->ptr
, &eptr
, 10);
3816 else if (o
->encoding
== REDIS_ENCODING_INT
)
3817 value
= (long)o
->ptr
;
3819 redisAssert(1 != 1);
3824 o
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
));
3825 tryObjectEncoding(o
);
3826 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],o
);
3827 if (retval
== DICT_ERR
) {
3828 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
3829 removeExpire(c
->db
,c
->argv
[1]);
3831 incrRefCount(c
->argv
[1]);
3834 addReply(c
,shared
.colon
);
3836 addReply(c
,shared
.crlf
);
3839 static void incrCommand(redisClient
*c
) {
3840 incrDecrCommand(c
,1);
3843 static void decrCommand(redisClient
*c
) {
3844 incrDecrCommand(c
,-1);
3847 static void incrbyCommand(redisClient
*c
) {
3848 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3849 incrDecrCommand(c
,incr
);
3852 static void decrbyCommand(redisClient
*c
) {
3853 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3854 incrDecrCommand(c
,-incr
);
3857 static void appendCommand(redisClient
*c
) {
3862 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3864 /* Create the key */
3865 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3866 incrRefCount(c
->argv
[1]);
3867 incrRefCount(c
->argv
[2]);
3868 totlen
= stringObjectLen(c
->argv
[2]);
3872 de
= dictFind(c
->db
->dict
,c
->argv
[1]);
3875 o
= dictGetEntryVal(de
);
3876 if (o
->type
!= REDIS_STRING
) {
3877 addReply(c
,shared
.wrongtypeerr
);
3880 /* If the object is specially encoded or shared we have to make
3882 if (o
->refcount
!= 1 || o
->encoding
!= REDIS_ENCODING_RAW
) {
3883 robj
*decoded
= getDecodedObject(o
);
3885 o
= createStringObject(decoded
->ptr
, sdslen(decoded
->ptr
));
3886 decrRefCount(decoded
);
3887 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
3890 if (c
->argv
[2]->encoding
== REDIS_ENCODING_RAW
) {
3891 o
->ptr
= sdscatlen(o
->ptr
,
3892 c
->argv
[2]->ptr
, sdslen(c
->argv
[2]->ptr
));
3894 o
->ptr
= sdscatprintf(o
->ptr
, "%ld",
3895 (unsigned long) c
->argv
[2]->ptr
);
3897 totlen
= sdslen(o
->ptr
);
3900 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",(unsigned long)totlen
));
3903 static void substrCommand(redisClient
*c
) {
3905 long start
= atoi(c
->argv
[2]->ptr
);
3906 long end
= atoi(c
->argv
[3]->ptr
);
3908 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3910 addReply(c
,shared
.nullbulk
);
3912 if (o
->type
!= REDIS_STRING
) {
3913 addReply(c
,shared
.wrongtypeerr
);
3915 size_t rangelen
, strlen
;
3918 o
= getDecodedObject(o
);
3919 strlen
= sdslen(o
->ptr
);
3921 /* convert negative indexes */
3922 if (start
< 0) start
= strlen
+start
;
3923 if (end
< 0) end
= strlen
+end
;
3924 if (start
< 0) start
= 0;
3925 if (end
< 0) end
= 0;
3927 /* indexes sanity checks */
3928 if (start
> end
|| (size_t)start
>= strlen
) {
3929 /* Out of range start or start > end result in null reply */
3930 addReply(c
,shared
.nullbulk
);
3934 if ((size_t)end
>= strlen
) end
= strlen
-1;
3935 rangelen
= (end
-start
)+1;
3937 /* Return the result */
3938 addReplySds(c
,sdscatprintf(sdsempty(),"$%zu\r\n",rangelen
));
3939 range
= sdsnewlen((char*)o
->ptr
+start
,rangelen
);
3940 addReplySds(c
,range
);
3941 addReply(c
,shared
.crlf
);
3947 /* ========================= Type agnostic commands ========================= */
3949 static void delCommand(redisClient
*c
) {
3952 for (j
= 1; j
< c
->argc
; j
++) {
3953 if (deleteKey(c
->db
,c
->argv
[j
])) {
3960 addReply(c
,shared
.czero
);
3963 addReply(c
,shared
.cone
);
3966 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",deleted
));
3971 static void existsCommand(redisClient
*c
) {
3972 addReply(c
,lookupKeyRead(c
->db
,c
->argv
[1]) ? shared
.cone
: shared
.czero
);
3975 static void selectCommand(redisClient
*c
) {
3976 int id
= atoi(c
->argv
[1]->ptr
);
3978 if (selectDb(c
,id
) == REDIS_ERR
) {
3979 addReplySds(c
,sdsnew("-ERR invalid DB index\r\n"));
3981 addReply(c
,shared
.ok
);
3985 static void randomkeyCommand(redisClient
*c
) {
3989 de
= dictGetRandomKey(c
->db
->dict
);
3990 if (!de
|| expireIfNeeded(c
->db
,dictGetEntryKey(de
)) == 0) break;
3993 addReply(c
,shared
.plus
);
3994 addReply(c
,shared
.crlf
);
3996 addReply(c
,shared
.plus
);
3997 addReply(c
,dictGetEntryKey(de
));
3998 addReply(c
,shared
.crlf
);
4002 static void keysCommand(redisClient
*c
) {
4005 sds pattern
= c
->argv
[1]->ptr
;
4006 int plen
= sdslen(pattern
);
4007 unsigned long numkeys
= 0;
4008 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
4010 di
= dictGetIterator(c
->db
->dict
);
4012 decrRefCount(lenobj
);
4013 while((de
= dictNext(di
)) != NULL
) {
4014 robj
*keyobj
= dictGetEntryKey(de
);
4016 sds key
= keyobj
->ptr
;
4017 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
4018 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
4019 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
4020 addReplyBulkLen(c
,keyobj
);
4022 addReply(c
,shared
.crlf
);
4027 dictReleaseIterator(di
);
4028 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",numkeys
);
4031 static void dbsizeCommand(redisClient
*c
) {
4033 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c
->db
->dict
)));
4036 static void lastsaveCommand(redisClient
*c
) {
4038 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
4041 static void typeCommand(redisClient
*c
) {
4045 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4050 case REDIS_STRING
: type
= "+string"; break;
4051 case REDIS_LIST
: type
= "+list"; break;
4052 case REDIS_SET
: type
= "+set"; break;
4053 case REDIS_ZSET
: type
= "+zset"; break;
4054 case REDIS_HASH
: type
= "+hash"; break;
4055 default: type
= "+unknown"; break;
4058 addReplySds(c
,sdsnew(type
));
4059 addReply(c
,shared
.crlf
);
4062 static void saveCommand(redisClient
*c
) {
4063 if (server
.bgsavechildpid
!= -1) {
4064 addReplySds(c
,sdsnew("-ERR background save in progress\r\n"));
4067 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
4068 addReply(c
,shared
.ok
);
4070 addReply(c
,shared
.err
);
4074 static void bgsaveCommand(redisClient
*c
) {
4075 if (server
.bgsavechildpid
!= -1) {
4076 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
4079 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
4080 char *status
= "+Background saving started\r\n";
4081 addReplySds(c
,sdsnew(status
));
4083 addReply(c
,shared
.err
);
4087 static void shutdownCommand(redisClient
*c
) {
4088 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
4089 /* Kill the saving child if there is a background saving in progress.
4090 We want to avoid race conditions, for instance our saving child may
4091 overwrite the synchronous saving did by SHUTDOWN. */
4092 if (server
.bgsavechildpid
!= -1) {
4093 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
4094 kill(server
.bgsavechildpid
,SIGKILL
);
4095 rdbRemoveTempFile(server
.bgsavechildpid
);
4097 if (server
.appendonly
) {
4098 /* Append only file: fsync() the AOF and exit */
4099 fsync(server
.appendfd
);
4100 if (server
.vm_enabled
) unlink(server
.vm_swap_file
);
4103 /* Snapshotting. Perform a SYNC SAVE and exit */
4104 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
4105 if (server
.daemonize
)
4106 unlink(server
.pidfile
);
4107 redisLog(REDIS_WARNING
,"%zu bytes used at exit",zmalloc_used_memory());
4108 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
4109 if (server
.vm_enabled
) unlink(server
.vm_swap_file
);
4112 /* Ooops.. error saving! The best we can do is to continue operating.
4113 * Note that if there was a background saving process, in the next
4114 * cron() Redis will be notified that the background saving aborted,
4115 * handling special stuff like slaves pending for synchronization... */
4116 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
4117 addReplySds(c
,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
4122 static void renameGenericCommand(redisClient
*c
, int nx
) {
4125 /* To use the same key as src and dst is probably an error */
4126 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
4127 addReply(c
,shared
.sameobjecterr
);
4131 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4133 addReply(c
,shared
.nokeyerr
);
4137 deleteIfVolatile(c
->db
,c
->argv
[2]);
4138 if (dictAdd(c
->db
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
4141 addReply(c
,shared
.czero
);
4144 dictReplace(c
->db
->dict
,c
->argv
[2],o
);
4146 incrRefCount(c
->argv
[2]);
4148 deleteKey(c
->db
,c
->argv
[1]);
4150 addReply(c
,nx
? shared
.cone
: shared
.ok
);
4153 static void renameCommand(redisClient
*c
) {
4154 renameGenericCommand(c
,0);
4157 static void renamenxCommand(redisClient
*c
) {
4158 renameGenericCommand(c
,1);
4161 static void moveCommand(redisClient
*c
) {
4166 /* Obtain source and target DB pointers */
4169 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
4170 addReply(c
,shared
.outofrangeerr
);
4174 selectDb(c
,srcid
); /* Back to the source DB */
4176 /* If the user is moving using as target the same
4177 * DB as the source DB it is probably an error. */
4179 addReply(c
,shared
.sameobjecterr
);
4183 /* Check if the element exists and get a reference */
4184 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4186 addReply(c
,shared
.czero
);
4190 /* Try to add the element to the target DB */
4191 deleteIfVolatile(dst
,c
->argv
[1]);
4192 if (dictAdd(dst
->dict
,c
->argv
[1],o
) == DICT_ERR
) {
4193 addReply(c
,shared
.czero
);
4196 incrRefCount(c
->argv
[1]);
4199 /* OK! key moved, free the entry in the source DB */
4200 deleteKey(src
,c
->argv
[1]);
4202 addReply(c
,shared
.cone
);
4205 /* =================================== Lists ================================ */
4206 static void pushGenericCommand(redisClient
*c
, int where
) {
4210 lobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4212 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
4213 addReply(c
,shared
.cone
);
4216 lobj
= createListObject();
4218 if (where
== REDIS_HEAD
) {
4219 listAddNodeHead(list
,c
->argv
[2]);
4221 listAddNodeTail(list
,c
->argv
[2]);
4223 dictAdd(c
->db
->dict
,c
->argv
[1],lobj
);
4224 incrRefCount(c
->argv
[1]);
4225 incrRefCount(c
->argv
[2]);
4227 if (lobj
->type
!= REDIS_LIST
) {
4228 addReply(c
,shared
.wrongtypeerr
);
4231 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
4232 addReply(c
,shared
.cone
);
4236 if (where
== REDIS_HEAD
) {
4237 listAddNodeHead(list
,c
->argv
[2]);
4239 listAddNodeTail(list
,c
->argv
[2]);
4241 incrRefCount(c
->argv
[2]);
4244 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(list
)));
4247 static void lpushCommand(redisClient
*c
) {
4248 pushGenericCommand(c
,REDIS_HEAD
);
4251 static void rpushCommand(redisClient
*c
) {
4252 pushGenericCommand(c
,REDIS_TAIL
);
4255 static void llenCommand(redisClient
*c
) {
4259 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4261 addReply(c
,shared
.czero
);
4264 if (o
->type
!= REDIS_LIST
) {
4265 addReply(c
,shared
.wrongtypeerr
);
4268 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(l
)));
4273 static void lindexCommand(redisClient
*c
) {
4275 int index
= atoi(c
->argv
[2]->ptr
);
4277 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4279 addReply(c
,shared
.nullbulk
);
4281 if (o
->type
!= REDIS_LIST
) {
4282 addReply(c
,shared
.wrongtypeerr
);
4284 list
*list
= o
->ptr
;
4287 ln
= listIndex(list
, index
);
4289 addReply(c
,shared
.nullbulk
);
4291 robj
*ele
= listNodeValue(ln
);
4292 addReplyBulkLen(c
,ele
);
4294 addReply(c
,shared
.crlf
);
4300 static void lsetCommand(redisClient
*c
) {
4302 int index
= atoi(c
->argv
[2]->ptr
);
4304 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4306 addReply(c
,shared
.nokeyerr
);
4308 if (o
->type
!= REDIS_LIST
) {
4309 addReply(c
,shared
.wrongtypeerr
);
4311 list
*list
= o
->ptr
;
4314 ln
= listIndex(list
, index
);
4316 addReply(c
,shared
.outofrangeerr
);
4318 robj
*ele
= listNodeValue(ln
);
4321 listNodeValue(ln
) = c
->argv
[3];
4322 incrRefCount(c
->argv
[3]);
4323 addReply(c
,shared
.ok
);
4330 static void popGenericCommand(redisClient
*c
, int where
) {
4333 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4335 addReply(c
,shared
.nullbulk
);
4337 if (o
->type
!= REDIS_LIST
) {
4338 addReply(c
,shared
.wrongtypeerr
);
4340 list
*list
= o
->ptr
;
4343 if (where
== REDIS_HEAD
)
4344 ln
= listFirst(list
);
4346 ln
= listLast(list
);
4349 addReply(c
,shared
.nullbulk
);
4351 robj
*ele
= listNodeValue(ln
);
4352 addReplyBulkLen(c
,ele
);
4354 addReply(c
,shared
.crlf
);
4355 listDelNode(list
,ln
);
4362 static void lpopCommand(redisClient
*c
) {
4363 popGenericCommand(c
,REDIS_HEAD
);
4366 static void rpopCommand(redisClient
*c
) {
4367 popGenericCommand(c
,REDIS_TAIL
);
4370 static void lrangeCommand(redisClient
*c
) {
4372 int start
= atoi(c
->argv
[2]->ptr
);
4373 int end
= atoi(c
->argv
[3]->ptr
);
4375 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4377 addReply(c
,shared
.nullmultibulk
);
4379 if (o
->type
!= REDIS_LIST
) {
4380 addReply(c
,shared
.wrongtypeerr
);
4382 list
*list
= o
->ptr
;
4384 int llen
= listLength(list
);
4388 /* convert negative indexes */
4389 if (start
< 0) start
= llen
+start
;
4390 if (end
< 0) end
= llen
+end
;
4391 if (start
< 0) start
= 0;
4392 if (end
< 0) end
= 0;
4394 /* indexes sanity checks */
4395 if (start
> end
|| start
>= llen
) {
4396 /* Out of range start or start > end result in empty list */
4397 addReply(c
,shared
.emptymultibulk
);
4400 if (end
>= llen
) end
= llen
-1;
4401 rangelen
= (end
-start
)+1;
4403 /* Return the result in form of a multi-bulk reply */
4404 ln
= listIndex(list
, start
);
4405 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
4406 for (j
= 0; j
< rangelen
; j
++) {
4407 ele
= listNodeValue(ln
);
4408 addReplyBulkLen(c
,ele
);
4410 addReply(c
,shared
.crlf
);
4417 static void ltrimCommand(redisClient
*c
) {
4419 int start
= atoi(c
->argv
[2]->ptr
);
4420 int end
= atoi(c
->argv
[3]->ptr
);
4422 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4424 addReply(c
,shared
.ok
);
4426 if (o
->type
!= REDIS_LIST
) {
4427 addReply(c
,shared
.wrongtypeerr
);
4429 list
*list
= o
->ptr
;
4431 int llen
= listLength(list
);
4432 int j
, ltrim
, rtrim
;
4434 /* convert negative indexes */
4435 if (start
< 0) start
= llen
+start
;
4436 if (end
< 0) end
= llen
+end
;
4437 if (start
< 0) start
= 0;
4438 if (end
< 0) end
= 0;
4440 /* indexes sanity checks */
4441 if (start
> end
|| start
>= llen
) {
4442 /* Out of range start or start > end result in empty list */
4446 if (end
>= llen
) end
= llen
-1;
4451 /* Remove list elements to perform the trim */
4452 for (j
= 0; j
< ltrim
; j
++) {
4453 ln
= listFirst(list
);
4454 listDelNode(list
,ln
);
4456 for (j
= 0; j
< rtrim
; j
++) {
4457 ln
= listLast(list
);
4458 listDelNode(list
,ln
);
4461 addReply(c
,shared
.ok
);
4466 static void lremCommand(redisClient
*c
) {
4469 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4471 addReply(c
,shared
.czero
);
4473 if (o
->type
!= REDIS_LIST
) {
4474 addReply(c
,shared
.wrongtypeerr
);
4476 list
*list
= o
->ptr
;
4477 listNode
*ln
, *next
;
4478 int toremove
= atoi(c
->argv
[2]->ptr
);
4483 toremove
= -toremove
;
4486 ln
= fromtail
? list
->tail
: list
->head
;
4488 robj
*ele
= listNodeValue(ln
);
4490 next
= fromtail
? ln
->prev
: ln
->next
;
4491 if (compareStringObjects(ele
,c
->argv
[3]) == 0) {
4492 listDelNode(list
,ln
);
4495 if (toremove
&& removed
== toremove
) break;
4499 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
4504 /* This is the semantic of this command:
4505 * RPOPLPUSH srclist dstlist:
4506 * IF LLEN(srclist) > 0
4507 * element = RPOP srclist
4508 * LPUSH dstlist element
4515 * The idea is to be able to get an element from a list in a reliable way
4516 * since the element is not just returned but pushed against another list
4517 * as well. This command was originally proposed by Ezra Zygmuntowicz.
4519 static void rpoplpushcommand(redisClient
*c
) {
4522 sobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4524 addReply(c
,shared
.nullbulk
);
4526 if (sobj
->type
!= REDIS_LIST
) {
4527 addReply(c
,shared
.wrongtypeerr
);
4529 list
*srclist
= sobj
->ptr
;
4530 listNode
*ln
= listLast(srclist
);
4533 addReply(c
,shared
.nullbulk
);
4535 robj
*dobj
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4536 robj
*ele
= listNodeValue(ln
);
4539 if (dobj
&& dobj
->type
!= REDIS_LIST
) {
4540 addReply(c
,shared
.wrongtypeerr
);
4544 /* Add the element to the target list (unless it's directly
4545 * passed to some BLPOP-ing client */
4546 if (!handleClientsWaitingListPush(c
,c
->argv
[2],ele
)) {
4548 /* Create the list if the key does not exist */
4549 dobj
= createListObject();
4550 dictAdd(c
->db
->dict
,c
->argv
[2],dobj
);
4551 incrRefCount(c
->argv
[2]);
4553 dstlist
= dobj
->ptr
;
4554 listAddNodeHead(dstlist
,ele
);
4558 /* Send the element to the client as reply as well */
4559 addReplyBulkLen(c
,ele
);
4561 addReply(c
,shared
.crlf
);
4563 /* Finally remove the element from the source list */
4564 listDelNode(srclist
,ln
);
4572 /* ==================================== Sets ================================ */
4574 static void saddCommand(redisClient
*c
) {
4577 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4579 set
= createSetObject();
4580 dictAdd(c
->db
->dict
,c
->argv
[1],set
);
4581 incrRefCount(c
->argv
[1]);
4583 if (set
->type
!= REDIS_SET
) {
4584 addReply(c
,shared
.wrongtypeerr
);
4588 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
4589 incrRefCount(c
->argv
[2]);
4591 addReply(c
,shared
.cone
);
4593 addReply(c
,shared
.czero
);
4597 static void sremCommand(redisClient
*c
) {
4600 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4602 addReply(c
,shared
.czero
);
4604 if (set
->type
!= REDIS_SET
) {
4605 addReply(c
,shared
.wrongtypeerr
);
4608 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
4610 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4611 addReply(c
,shared
.cone
);
4613 addReply(c
,shared
.czero
);
4618 static void smoveCommand(redisClient
*c
) {
4619 robj
*srcset
, *dstset
;
4621 srcset
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4622 dstset
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4624 /* If the source key does not exist return 0, if it's of the wrong type
4626 if (srcset
== NULL
|| srcset
->type
!= REDIS_SET
) {
4627 addReply(c
, srcset
? shared
.wrongtypeerr
: shared
.czero
);
4630 /* Error if the destination key is not a set as well */
4631 if (dstset
&& dstset
->type
!= REDIS_SET
) {
4632 addReply(c
,shared
.wrongtypeerr
);
4635 /* Remove the element from the source set */
4636 if (dictDelete(srcset
->ptr
,c
->argv
[3]) == DICT_ERR
) {
4637 /* Key not found in the src set! return zero */
4638 addReply(c
,shared
.czero
);
4642 /* Add the element to the destination set */
4644 dstset
= createSetObject();
4645 dictAdd(c
->db
->dict
,c
->argv
[2],dstset
);
4646 incrRefCount(c
->argv
[2]);
4648 if (dictAdd(dstset
->ptr
,c
->argv
[3],NULL
) == DICT_OK
)
4649 incrRefCount(c
->argv
[3]);
4650 addReply(c
,shared
.cone
);
4653 static void sismemberCommand(redisClient
*c
) {
4656 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
4658 addReply(c
,shared
.czero
);
4660 if (set
->type
!= REDIS_SET
) {
4661 addReply(c
,shared
.wrongtypeerr
);
4664 if (dictFind(set
->ptr
,c
->argv
[2]))
4665 addReply(c
,shared
.cone
);
4667 addReply(c
,shared
.czero
);
4671 static void scardCommand(redisClient
*c
) {
4675 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4677 addReply(c
,shared
.czero
);
4680 if (o
->type
!= REDIS_SET
) {
4681 addReply(c
,shared
.wrongtypeerr
);
4684 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4690 static void spopCommand(redisClient
*c
) {
4694 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4696 addReply(c
,shared
.nullbulk
);
4698 if (set
->type
!= REDIS_SET
) {
4699 addReply(c
,shared
.wrongtypeerr
);
4702 de
= dictGetRandomKey(set
->ptr
);
4704 addReply(c
,shared
.nullbulk
);
4706 robj
*ele
= dictGetEntryKey(de
);
4708 addReplyBulkLen(c
,ele
);
4710 addReply(c
,shared
.crlf
);
4711 dictDelete(set
->ptr
,ele
);
4712 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4718 static void srandmemberCommand(redisClient
*c
) {
4722 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
4724 addReply(c
,shared
.nullbulk
);
4726 if (set
->type
!= REDIS_SET
) {
4727 addReply(c
,shared
.wrongtypeerr
);
4730 de
= dictGetRandomKey(set
->ptr
);
4732 addReply(c
,shared
.nullbulk
);
4734 robj
*ele
= dictGetEntryKey(de
);
4736 addReplyBulkLen(c
,ele
);
4738 addReply(c
,shared
.crlf
);
4743 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
4744 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
4746 return dictSize(*d1
)-dictSize(*d2
);
4749 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, unsigned long setsnum
, robj
*dstkey
) {
4750 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4753 robj
*lenobj
= NULL
, *dstset
= NULL
;
4754 unsigned long j
, cardinality
= 0;
4756 for (j
= 0; j
< setsnum
; j
++) {
4760 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4761 lookupKeyRead(c
->db
,setskeys
[j
]);
4765 if (deleteKey(c
->db
,dstkey
))
4767 addReply(c
,shared
.czero
);
4769 addReply(c
,shared
.nullmultibulk
);
4773 if (setobj
->type
!= REDIS_SET
) {
4775 addReply(c
,shared
.wrongtypeerr
);
4778 dv
[j
] = setobj
->ptr
;
4780 /* Sort sets from the smallest to largest, this will improve our
4781 * algorithm's performace */
4782 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
4784 /* The first thing we should output is the total number of elements...
4785 * since this is a multi-bulk write, but at this stage we don't know
4786 * the intersection set size, so we use a trick, append an empty object
4787 * to the output list and save the pointer to later modify it with the
4790 lenobj
= createObject(REDIS_STRING
,NULL
);
4792 decrRefCount(lenobj
);
4794 /* If we have a target key where to store the resulting set
4795 * create this key with an empty set inside */
4796 dstset
= createSetObject();
4799 /* Iterate all the elements of the first (smallest) set, and test
4800 * the element against all the other sets, if at least one set does
4801 * not include the element it is discarded */
4802 di
= dictGetIterator(dv
[0]);
4804 while((de
= dictNext(di
)) != NULL
) {
4807 for (j
= 1; j
< setsnum
; j
++)
4808 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
4810 continue; /* at least one set does not contain the member */
4811 ele
= dictGetEntryKey(de
);
4813 addReplyBulkLen(c
,ele
);
4815 addReply(c
,shared
.crlf
);
4818 dictAdd(dstset
->ptr
,ele
,NULL
);
4822 dictReleaseIterator(di
);
4825 /* Store the resulting set into the target */
4826 deleteKey(c
->db
,dstkey
);
4827 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4828 incrRefCount(dstkey
);
4832 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",cardinality
);
4834 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4835 dictSize((dict
*)dstset
->ptr
)));
4841 static void sinterCommand(redisClient
*c
) {
4842 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
4845 static void sinterstoreCommand(redisClient
*c
) {
4846 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
4849 #define REDIS_OP_UNION 0
4850 #define REDIS_OP_DIFF 1
4851 #define REDIS_OP_INTER 2
4853 static void sunionDiffGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
, int op
) {
4854 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4857 robj
*dstset
= NULL
;
4858 int j
, cardinality
= 0;
4860 for (j
= 0; j
< setsnum
; j
++) {
4864 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4865 lookupKeyRead(c
->db
,setskeys
[j
]);
4870 if (setobj
->type
!= REDIS_SET
) {
4872 addReply(c
,shared
.wrongtypeerr
);
4875 dv
[j
] = setobj
->ptr
;
4878 /* We need a temp set object to store our union. If the dstkey
4879 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
4880 * this set object will be the resulting object to set into the target key*/
4881 dstset
= createSetObject();
4883 /* Iterate all the elements of all the sets, add every element a single
4884 * time to the result set */
4885 for (j
= 0; j
< setsnum
; j
++) {
4886 if (op
== REDIS_OP_DIFF
&& j
== 0 && !dv
[j
]) break; /* result set is empty */
4887 if (!dv
[j
]) continue; /* non existing keys are like empty sets */
4889 di
= dictGetIterator(dv
[j
]);
4891 while((de
= dictNext(di
)) != NULL
) {
4894 /* dictAdd will not add the same element multiple times */
4895 ele
= dictGetEntryKey(de
);
4896 if (op
== REDIS_OP_UNION
|| j
== 0) {
4897 if (dictAdd(dstset
->ptr
,ele
,NULL
) == DICT_OK
) {
4901 } else if (op
== REDIS_OP_DIFF
) {
4902 if (dictDelete(dstset
->ptr
,ele
) == DICT_OK
) {
4907 dictReleaseIterator(di
);
4909 if (op
== REDIS_OP_DIFF
&& cardinality
== 0) break; /* result set is empty */
4912 /* Output the content of the resulting set, if not in STORE mode */
4914 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",cardinality
));
4915 di
= dictGetIterator(dstset
->ptr
);
4916 while((de
= dictNext(di
)) != NULL
) {
4919 ele
= dictGetEntryKey(de
);
4920 addReplyBulkLen(c
,ele
);
4922 addReply(c
,shared
.crlf
);
4924 dictReleaseIterator(di
);
4926 /* If we have a target key where to store the resulting set
4927 * create this key with the result set inside */
4928 deleteKey(c
->db
,dstkey
);
4929 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4930 incrRefCount(dstkey
);
4935 decrRefCount(dstset
);
4937 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4938 dictSize((dict
*)dstset
->ptr
)));
4944 static void sunionCommand(redisClient
*c
) {
4945 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_UNION
);
4948 static void sunionstoreCommand(redisClient
*c
) {
4949 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_UNION
);
4952 static void sdiffCommand(redisClient
*c
) {
4953 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_DIFF
);
4956 static void sdiffstoreCommand(redisClient
*c
) {
4957 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_DIFF
);
4960 /* ==================================== ZSets =============================== */
4962 /* ZSETs are ordered sets using two data structures to hold the same elements
4963 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
4966 * The elements are added to an hash table mapping Redis objects to scores.
4967 * At the same time the elements are added to a skip list mapping scores
4968 * to Redis objects (so objects are sorted by scores in this "view"). */
4970 /* This skiplist implementation is almost a C translation of the original
4971 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
4972 * Alternative to Balanced Trees", modified in three ways:
4973 * a) this implementation allows for repeated values.
4974 * b) the comparison is not just by key (our 'score') but by satellite data.
4975 * c) there is a back pointer, so it's a doubly linked list with the back
4976 * pointers being only at "level 1". This allows to traverse the list
4977 * from tail to head, useful for ZREVRANGE. */
4979 static zskiplistNode
*zslCreateNode(int level
, double score
, robj
*obj
) {
4980 zskiplistNode
*zn
= zmalloc(sizeof(*zn
));
4982 zn
->forward
= zmalloc(sizeof(zskiplistNode
*) * level
);
4984 zn
->span
= zmalloc(sizeof(unsigned int) * (level
- 1));
4990 static zskiplist
*zslCreate(void) {
4994 zsl
= zmalloc(sizeof(*zsl
));
4997 zsl
->header
= zslCreateNode(ZSKIPLIST_MAXLEVEL
,0,NULL
);
4998 for (j
= 0; j
< ZSKIPLIST_MAXLEVEL
; j
++) {
4999 zsl
->header
->forward
[j
] = NULL
;
5001 /* span has space for ZSKIPLIST_MAXLEVEL-1 elements */
5002 if (j
< ZSKIPLIST_MAXLEVEL
-1)
5003 zsl
->header
->span
[j
] = 0;
5005 zsl
->header
->backward
= NULL
;
5010 static void zslFreeNode(zskiplistNode
*node
) {
5011 decrRefCount(node
->obj
);
5012 zfree(node
->forward
);
5017 static void zslFree(zskiplist
*zsl
) {
5018 zskiplistNode
*node
= zsl
->header
->forward
[0], *next
;
5020 zfree(zsl
->header
->forward
);
5021 zfree(zsl
->header
->span
);
5024 next
= node
->forward
[0];
5031 static int zslRandomLevel(void) {
5033 while ((random()&0xFFFF) < (ZSKIPLIST_P
* 0xFFFF))
5038 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
) {
5039 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5040 unsigned int rank
[ZSKIPLIST_MAXLEVEL
];
5044 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5045 /* store rank that is crossed to reach the insert position */
5046 rank
[i
] = i
== (zsl
->level
-1) ? 0 : rank
[i
+1];
5048 while (x
->forward
[i
] &&
5049 (x
->forward
[i
]->score
< score
||
5050 (x
->forward
[i
]->score
== score
&&
5051 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0))) {
5052 rank
[i
] += i
> 0 ? x
->span
[i
-1] : 1;
5057 /* we assume the key is not already inside, since we allow duplicated
5058 * scores, and the re-insertion of score and redis object should never
5059 * happpen since the caller of zslInsert() should test in the hash table
5060 * if the element is already inside or not. */
5061 level
= zslRandomLevel();
5062 if (level
> zsl
->level
) {
5063 for (i
= zsl
->level
; i
< level
; i
++) {
5065 update
[i
] = zsl
->header
;
5066 update
[i
]->span
[i
-1] = zsl
->length
;
5070 x
= zslCreateNode(level
,score
,obj
);
5071 for (i
= 0; i
< level
; i
++) {
5072 x
->forward
[i
] = update
[i
]->forward
[i
];
5073 update
[i
]->forward
[i
] = x
;
5075 /* update span covered by update[i] as x is inserted here */
5077 x
->span
[i
-1] = update
[i
]->span
[i
-1] - (rank
[0] - rank
[i
]);
5078 update
[i
]->span
[i
-1] = (rank
[0] - rank
[i
]) + 1;
5082 /* increment span for untouched levels */
5083 for (i
= level
; i
< zsl
->level
; i
++) {
5084 update
[i
]->span
[i
-1]++;
5087 x
->backward
= (update
[0] == zsl
->header
) ? NULL
: update
[0];
5089 x
->forward
[0]->backward
= x
;
5095 /* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
5096 void zslDeleteNode(zskiplist
*zsl
, zskiplistNode
*x
, zskiplistNode
**update
) {
5098 for (i
= 0; i
< zsl
->level
; i
++) {
5099 if (update
[i
]->forward
[i
] == x
) {
5101 update
[i
]->span
[i
-1] += x
->span
[i
-1] - 1;
5103 update
[i
]->forward
[i
] = x
->forward
[i
];
5105 /* invariant: i > 0, because update[0]->forward[0]
5106 * is always equal to x */
5107 update
[i
]->span
[i
-1] -= 1;
5110 if (x
->forward
[0]) {
5111 x
->forward
[0]->backward
= x
->backward
;
5113 zsl
->tail
= x
->backward
;
5115 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
5120 /* Delete an element with matching score/object from the skiplist. */
5121 static int zslDelete(zskiplist
*zsl
, double score
, robj
*obj
) {
5122 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5126 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5127 while (x
->forward
[i
] &&
5128 (x
->forward
[i
]->score
< score
||
5129 (x
->forward
[i
]->score
== score
&&
5130 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
5134 /* We may have multiple elements with the same score, what we need
5135 * is to find the element with both the right score and object. */
5137 if (x
&& score
== x
->score
&& compareStringObjects(x
->obj
,obj
) == 0) {
5138 zslDeleteNode(zsl
, x
, update
);
5142 return 0; /* not found */
5144 return 0; /* not found */
5147 /* Delete all the elements with score between min and max from the skiplist.
5148 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
5149 * Note that this function takes the reference to the hash table view of the
5150 * sorted set, in order to remove the elements from the hash table too. */
5151 static unsigned long zslDeleteRangeByScore(zskiplist
*zsl
, double min
, double max
, dict
*dict
) {
5152 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5153 unsigned long removed
= 0;
5157 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5158 while (x
->forward
[i
] && x
->forward
[i
]->score
< min
)
5162 /* We may have multiple elements with the same score, what we need
5163 * is to find the element with both the right score and object. */
5165 while (x
&& x
->score
<= max
) {
5166 zskiplistNode
*next
= x
->forward
[0];
5167 zslDeleteNode(zsl
, x
, update
);
5168 dictDelete(dict
,x
->obj
);
5173 return removed
; /* not found */
5176 /* Delete all the elements with rank between start and end from the skiplist.
5177 * Start and end are inclusive. Note that start and end need to be 1-based */
5178 static unsigned long zslDeleteRangeByRank(zskiplist
*zsl
, unsigned int start
, unsigned int end
, dict
*dict
) {
5179 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5180 unsigned long traversed
= 0, removed
= 0;
5184 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5185 while (x
->forward
[i
] && (traversed
+ (i
> 0 ? x
->span
[i
-1] : 1)) < start
) {
5186 traversed
+= i
> 0 ? x
->span
[i
-1] : 1;
5194 while (x
&& traversed
<= end
) {
5195 zskiplistNode
*next
= x
->forward
[0];
5196 zslDeleteNode(zsl
, x
, update
);
5197 dictDelete(dict
,x
->obj
);
5206 /* Find the first node having a score equal or greater than the specified one.
5207 * Returns NULL if there is no match. */
5208 static zskiplistNode
*zslFirstWithScore(zskiplist
*zsl
, double score
) {
5213 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5214 while (x
->forward
[i
] && x
->forward
[i
]->score
< score
)
5217 /* We may have multiple elements with the same score, what we need
5218 * is to find the element with both the right score and object. */
5219 return x
->forward
[0];
5222 /* Find the rank for an element by both score and key.
5223 * Returns 0 when the element cannot be found, rank otherwise.
5224 * Note that the rank is 1-based due to the span of zsl->header to the
5226 static unsigned long zslGetRank(zskiplist
*zsl
, double score
, robj
*o
) {
5228 unsigned long rank
= 0;
5232 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5233 while (x
->forward
[i
] &&
5234 (x
->forward
[i
]->score
< score
||
5235 (x
->forward
[i
]->score
== score
&&
5236 compareStringObjects(x
->forward
[i
]->obj
,o
) <= 0))) {
5237 rank
+= i
> 0 ? x
->span
[i
-1] : 1;
5241 /* x might be equal to zsl->header, so test if obj is non-NULL */
5242 if (x
->obj
&& compareStringObjects(x
->obj
,o
) == 0) {
5249 /* Finds an element by its rank. The rank argument needs to be 1-based. */
5250 zskiplistNode
* zslGetElementByRank(zskiplist
*zsl
, unsigned long rank
) {
5252 unsigned long traversed
= 0;
5256 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5257 while (x
->forward
[i
] && (traversed
+ (i
> 0 ? x
->span
[i
-1] : 1)) <= rank
) {
5258 traversed
+= i
> 0 ? x
->span
[i
-1] : 1;
5262 if (traversed
== rank
) {
5269 /* The actual Z-commands implementations */
5271 /* This generic command implements both ZADD and ZINCRBY.
5272 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
5273 * the increment if the operation is a ZINCRBY (doincrement == 1). */
5274 static void zaddGenericCommand(redisClient
*c
, robj
*key
, robj
*ele
, double scoreval
, int doincrement
) {
5279 zsetobj
= lookupKeyWrite(c
->db
,key
);
5280 if (zsetobj
== NULL
) {
5281 zsetobj
= createZsetObject();
5282 dictAdd(c
->db
->dict
,key
,zsetobj
);
5285 if (zsetobj
->type
!= REDIS_ZSET
) {
5286 addReply(c
,shared
.wrongtypeerr
);
5292 /* Ok now since we implement both ZADD and ZINCRBY here the code
5293 * needs to handle the two different conditions. It's all about setting
5294 * '*score', that is, the new score to set, to the right value. */
5295 score
= zmalloc(sizeof(double));
5299 /* Read the old score. If the element was not present starts from 0 */
5300 de
= dictFind(zs
->dict
,ele
);
5302 double *oldscore
= dictGetEntryVal(de
);
5303 *score
= *oldscore
+ scoreval
;
5311 /* What follows is a simple remove and re-insert operation that is common
5312 * to both ZADD and ZINCRBY... */
5313 if (dictAdd(zs
->dict
,ele
,score
) == DICT_OK
) {
5314 /* case 1: New element */
5315 incrRefCount(ele
); /* added to hash */
5316 zslInsert(zs
->zsl
,*score
,ele
);
5317 incrRefCount(ele
); /* added to skiplist */
5320 addReplyDouble(c
,*score
);
5322 addReply(c
,shared
.cone
);
5327 /* case 2: Score update operation */
5328 de
= dictFind(zs
->dict
,ele
);
5329 redisAssert(de
!= NULL
);
5330 oldscore
= dictGetEntryVal(de
);
5331 if (*score
!= *oldscore
) {
5334 /* Remove and insert the element in the skip list with new score */
5335 deleted
= zslDelete(zs
->zsl
,*oldscore
,ele
);
5336 redisAssert(deleted
!= 0);
5337 zslInsert(zs
->zsl
,*score
,ele
);
5339 /* Update the score in the hash table */
5340 dictReplace(zs
->dict
,ele
,score
);
5346 addReplyDouble(c
,*score
);
5348 addReply(c
,shared
.czero
);
5352 static void zaddCommand(redisClient
*c
) {
5355 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
5356 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,0);
5359 static void zincrbyCommand(redisClient
*c
) {
5362 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
5363 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,1);
5366 static void zremCommand(redisClient
*c
) {
5370 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
5371 if (zsetobj
== NULL
) {
5372 addReply(c
,shared
.czero
);
5378 if (zsetobj
->type
!= REDIS_ZSET
) {
5379 addReply(c
,shared
.wrongtypeerr
);
5383 de
= dictFind(zs
->dict
,c
->argv
[2]);
5385 addReply(c
,shared
.czero
);
5388 /* Delete from the skiplist */
5389 oldscore
= dictGetEntryVal(de
);
5390 deleted
= zslDelete(zs
->zsl
,*oldscore
,c
->argv
[2]);
5391 redisAssert(deleted
!= 0);
5393 /* Delete from the hash table */
5394 dictDelete(zs
->dict
,c
->argv
[2]);
5395 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
5397 addReply(c
,shared
.cone
);
5401 static void zremrangebyscoreCommand(redisClient
*c
) {
5402 double min
= strtod(c
->argv
[2]->ptr
,NULL
);
5403 double max
= strtod(c
->argv
[3]->ptr
,NULL
);
5407 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
5408 if (zsetobj
== NULL
) {
5409 addReply(c
,shared
.czero
);
5413 if (zsetobj
->type
!= REDIS_ZSET
) {
5414 addReply(c
,shared
.wrongtypeerr
);
5418 deleted
= zslDeleteRangeByScore(zs
->zsl
,min
,max
,zs
->dict
);
5419 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
5420 server
.dirty
+= deleted
;
5421 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",deleted
));
5425 static void zremrangebyrankCommand(redisClient
*c
) {
5426 int start
= atoi(c
->argv
[2]->ptr
);
5427 int end
= atoi(c
->argv
[3]->ptr
);
5431 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
5432 if (zsetobj
== NULL
) {
5433 addReply(c
,shared
.czero
);
5435 if (zsetobj
->type
!= REDIS_ZSET
) {
5436 addReply(c
,shared
.wrongtypeerr
);
5441 int llen
= zs
->zsl
->length
;
5444 /* convert negative indexes */
5445 if (start
< 0) start
= llen
+start
;
5446 if (end
< 0) end
= llen
+end
;
5447 if (start
< 0) start
= 0;
5448 if (end
< 0) end
= 0;
5450 /* indexes sanity checks */
5451 if (start
> end
|| start
>= llen
) {
5452 addReply(c
,shared
.czero
);
5455 if (end
>= llen
) end
= llen
-1;
5457 /* increment start and end because zsl*Rank functions
5458 * use 1-based rank */
5459 deleted
= zslDeleteRangeByRank(zs
->zsl
,start
+1,end
+1,zs
->dict
);
5460 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
5461 server
.dirty
+= deleted
;
5462 addReplyLong(c
, deleted
);
5471 static int qsortCompareZsetopsrcByCardinality(const void *s1
, const void *s2
) {
5472 zsetopsrc
*d1
= (void*) s1
, *d2
= (void*) s2
;
5473 unsigned long size1
, size2
;
5474 size1
= d1
->dict
? dictSize(d1
->dict
) : 0;
5475 size2
= d2
->dict
? dictSize(d2
->dict
) : 0;
5476 return size1
- size2
;
5479 static void zunionInterGenericCommand(redisClient
*c
, robj
*dstkey
, int op
) {
5487 /* expect zsetnum input keys to be given */
5488 zsetnum
= atoi(c
->argv
[2]->ptr
);
5490 addReplySds(c
,sdsnew("-ERR at least 1 input key is needed for ZUNION/ZINTER\r\n"));
5494 /* test if the expected number of keys would overflow */
5495 if (3+zsetnum
> c
->argc
) {
5496 addReply(c
,shared
.syntaxerr
);
5500 /* read keys to be used for input */
5501 src
= zmalloc(sizeof(zsetopsrc
) * zsetnum
);
5502 for (i
= 0, j
= 3; i
< zsetnum
; i
++, j
++) {
5503 robj
*zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
5507 if (zsetobj
->type
!= REDIS_ZSET
) {
5509 addReply(c
,shared
.wrongtypeerr
);
5512 src
[i
].dict
= ((zset
*)zsetobj
->ptr
)->dict
;
5515 /* default all weights to 1 */
5516 src
[i
].weight
= 1.0;
5519 /* parse optional extra arguments */
5521 int remaining
= c
->argc
-j
;
5524 if (!strcasecmp(c
->argv
[j
]->ptr
,"weights")) {
5526 if (remaining
< zsetnum
) {
5528 addReplySds(c
,sdsnew("-ERR not enough weights for ZUNION/ZINTER\r\n"));
5531 for (i
= 0; i
< zsetnum
; i
++, j
++, remaining
--) {
5532 src
[i
].weight
= strtod(c
->argv
[j
]->ptr
, NULL
);
5536 addReply(c
,shared
.syntaxerr
);
5542 dstobj
= createZsetObject();
5543 dstzset
= dstobj
->ptr
;
5545 if (op
== REDIS_OP_INTER
) {
5546 /* sort sets from the smallest to largest, this will improve our
5547 * algorithm's performance */
5548 qsort(src
,zsetnum
,sizeof(zsetopsrc
), qsortCompareZsetopsrcByCardinality
);
5550 /* skip going over all entries if the smallest zset is NULL or empty */
5551 if (src
[0].dict
&& dictSize(src
[0].dict
) > 0) {
5552 /* precondition: as src[0].dict is non-empty and the zsets are ordered
5553 * from small to large, all src[i > 0].dict are non-empty too */
5554 di
= dictGetIterator(src
[0].dict
);
5555 while((de
= dictNext(di
)) != NULL
) {
5556 double *score
= zmalloc(sizeof(double));
5559 for (j
= 0; j
< zsetnum
; j
++) {
5560 dictEntry
*other
= (j
== 0) ? de
: dictFind(src
[j
].dict
,dictGetEntryKey(de
));
5562 *score
= *score
+ src
[j
].weight
* (*(double*)dictGetEntryVal(other
));
5568 /* skip entry when not present in every source dict */
5572 robj
*o
= dictGetEntryKey(de
);
5573 dictAdd(dstzset
->dict
,o
,score
);
5574 incrRefCount(o
); /* added to dictionary */
5575 zslInsert(dstzset
->zsl
,*score
,o
);
5576 incrRefCount(o
); /* added to skiplist */
5579 dictReleaseIterator(di
);
5581 } else if (op
== REDIS_OP_UNION
) {
5582 for (i
= 0; i
< zsetnum
; i
++) {
5583 if (!src
[i
].dict
) continue;
5585 di
= dictGetIterator(src
[i
].dict
);
5586 while((de
= dictNext(di
)) != NULL
) {
5587 /* skip key when already processed */
5588 if (dictFind(dstzset
->dict
,dictGetEntryKey(de
)) != NULL
) continue;
5590 double *score
= zmalloc(sizeof(double));
5592 for (j
= 0; j
< zsetnum
; j
++) {
5593 if (!src
[j
].dict
) continue;
5595 dictEntry
*other
= (i
== j
) ? de
: dictFind(src
[j
].dict
,dictGetEntryKey(de
));
5597 *score
= *score
+ src
[j
].weight
* (*(double*)dictGetEntryVal(other
));
5601 robj
*o
= dictGetEntryKey(de
);
5602 dictAdd(dstzset
->dict
,o
,score
);
5603 incrRefCount(o
); /* added to dictionary */
5604 zslInsert(dstzset
->zsl
,*score
,o
);
5605 incrRefCount(o
); /* added to skiplist */
5607 dictReleaseIterator(di
);
5610 /* unknown operator */
5611 redisAssert(op
== REDIS_OP_INTER
|| op
== REDIS_OP_UNION
);
5614 deleteKey(c
->db
,dstkey
);
5615 dictAdd(c
->db
->dict
,dstkey
,dstobj
);
5616 incrRefCount(dstkey
);
5618 addReplyLong(c
, dstzset
->zsl
->length
);
5623 static void zunionCommand(redisClient
*c
) {
5624 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_UNION
);
5627 static void zinterCommand(redisClient
*c
) {
5628 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_INTER
);
5631 static void zrangeGenericCommand(redisClient
*c
, int reverse
) {
5633 int start
= atoi(c
->argv
[2]->ptr
);
5634 int end
= atoi(c
->argv
[3]->ptr
);
5637 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
5639 } else if (c
->argc
>= 5) {
5640 addReply(c
,shared
.syntaxerr
);
5644 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5646 addReply(c
,shared
.nullmultibulk
);
5648 if (o
->type
!= REDIS_ZSET
) {
5649 addReply(c
,shared
.wrongtypeerr
);
5651 zset
*zsetobj
= o
->ptr
;
5652 zskiplist
*zsl
= zsetobj
->zsl
;
5655 int llen
= zsl
->length
;
5659 /* convert negative indexes */
5660 if (start
< 0) start
= llen
+start
;
5661 if (end
< 0) end
= llen
+end
;
5662 if (start
< 0) start
= 0;
5663 if (end
< 0) end
= 0;
5665 /* indexes sanity checks */
5666 if (start
> end
|| start
>= llen
) {
5667 /* Out of range start or start > end result in empty list */
5668 addReply(c
,shared
.emptymultibulk
);
5671 if (end
>= llen
) end
= llen
-1;
5672 rangelen
= (end
-start
)+1;
5674 /* check if starting point is trivial, before searching
5675 * the element in log(N) time */
5677 ln
= start
== 0 ? zsl
->tail
: zslGetElementByRank(zsl
, llen
-start
);
5679 ln
= start
== 0 ? zsl
->header
->forward
[0] : zslGetElementByRank(zsl
, start
+1);
5682 /* Return the result in form of a multi-bulk reply */
5683 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",
5684 withscores
? (rangelen
*2) : rangelen
));
5685 for (j
= 0; j
< rangelen
; j
++) {
5687 addReplyBulkLen(c
,ele
);
5689 addReply(c
,shared
.crlf
);
5691 addReplyDouble(c
,ln
->score
);
5692 ln
= reverse
? ln
->backward
: ln
->forward
[0];
5698 static void zrangeCommand(redisClient
*c
) {
5699 zrangeGenericCommand(c
,0);
5702 static void zrevrangeCommand(redisClient
*c
) {
5703 zrangeGenericCommand(c
,1);
5706 /* This command implements both ZRANGEBYSCORE and ZCOUNT.
5707 * If justcount is non-zero, just the count is returned. */
5708 static void genericZrangebyscoreCommand(redisClient
*c
, int justcount
) {
5711 int minex
= 0, maxex
= 0; /* are min or max exclusive? */
5712 int offset
= 0, limit
= -1;
5716 /* Parse the min-max interval. If one of the values is prefixed
5717 * by the "(" character, it's considered "open". For instance
5718 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
5719 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
5720 if (((char*)c
->argv
[2]->ptr
)[0] == '(') {
5721 min
= strtod((char*)c
->argv
[2]->ptr
+1,NULL
);
5724 min
= strtod(c
->argv
[2]->ptr
,NULL
);
5726 if (((char*)c
->argv
[3]->ptr
)[0] == '(') {
5727 max
= strtod((char*)c
->argv
[3]->ptr
+1,NULL
);
5730 max
= strtod(c
->argv
[3]->ptr
,NULL
);
5733 /* Parse "WITHSCORES": note that if the command was called with
5734 * the name ZCOUNT then we are sure that c->argc == 4, so we'll never
5735 * enter the following paths to parse WITHSCORES and LIMIT. */
5736 if (c
->argc
== 5 || c
->argc
== 8) {
5737 if (strcasecmp(c
->argv
[c
->argc
-1]->ptr
,"withscores") == 0)
5742 if (c
->argc
!= (4 + withscores
) && c
->argc
!= (7 + withscores
))
5746 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
5751 if (c
->argc
== (7 + withscores
) && strcasecmp(c
->argv
[4]->ptr
,"limit")) {
5752 addReply(c
,shared
.syntaxerr
);
5754 } else if (c
->argc
== (7 + withscores
)) {
5755 offset
= atoi(c
->argv
[5]->ptr
);
5756 limit
= atoi(c
->argv
[6]->ptr
);
5757 if (offset
< 0) offset
= 0;
5760 /* Ok, lookup the key and get the range */
5761 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5763 addReply(c
,justcount
? shared
.czero
: shared
.nullmultibulk
);
5765 if (o
->type
!= REDIS_ZSET
) {
5766 addReply(c
,shared
.wrongtypeerr
);
5768 zset
*zsetobj
= o
->ptr
;
5769 zskiplist
*zsl
= zsetobj
->zsl
;
5771 robj
*ele
, *lenobj
= NULL
;
5772 unsigned long rangelen
= 0;
5774 /* Get the first node with the score >= min, or with
5775 * score > min if 'minex' is true. */
5776 ln
= zslFirstWithScore(zsl
,min
);
5777 while (minex
&& ln
&& ln
->score
== min
) ln
= ln
->forward
[0];
5780 /* No element matching the speciifed interval */
5781 addReply(c
,justcount
? shared
.czero
: shared
.emptymultibulk
);
5785 /* We don't know in advance how many matching elements there
5786 * are in the list, so we push this object that will represent
5787 * the multi-bulk length in the output buffer, and will "fix"
5790 lenobj
= createObject(REDIS_STRING
,NULL
);
5792 decrRefCount(lenobj
);
5795 while(ln
&& (maxex
? (ln
->score
< max
) : (ln
->score
<= max
))) {
5798 ln
= ln
->forward
[0];
5801 if (limit
== 0) break;
5804 addReplyBulkLen(c
,ele
);
5806 addReply(c
,shared
.crlf
);
5808 addReplyDouble(c
,ln
->score
);
5810 ln
= ln
->forward
[0];
5812 if (limit
> 0) limit
--;
5815 addReplyLong(c
,(long)rangelen
);
5817 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",
5818 withscores
? (rangelen
*2) : rangelen
);
5824 static void zrangebyscoreCommand(redisClient
*c
) {
5825 genericZrangebyscoreCommand(c
,0);
5828 static void zcountCommand(redisClient
*c
) {
5829 genericZrangebyscoreCommand(c
,1);
5832 static void zcardCommand(redisClient
*c
) {
5836 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5838 addReply(c
,shared
.czero
);
5841 if (o
->type
!= REDIS_ZSET
) {
5842 addReply(c
,shared
.wrongtypeerr
);
5845 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",zs
->zsl
->length
));
5850 static void zscoreCommand(redisClient
*c
) {
5854 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5856 addReply(c
,shared
.nullbulk
);
5859 if (o
->type
!= REDIS_ZSET
) {
5860 addReply(c
,shared
.wrongtypeerr
);
5865 de
= dictFind(zs
->dict
,c
->argv
[2]);
5867 addReply(c
,shared
.nullbulk
);
5869 double *score
= dictGetEntryVal(de
);
5871 addReplyDouble(c
,*score
);
5877 static void zrankGenericCommand(redisClient
*c
, int reverse
) {
5879 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5881 addReply(c
,shared
.nullbulk
);
5884 if (o
->type
!= REDIS_ZSET
) {
5885 addReply(c
,shared
.wrongtypeerr
);
5888 zskiplist
*zsl
= zs
->zsl
;
5892 de
= dictFind(zs
->dict
,c
->argv
[2]);
5894 addReply(c
,shared
.nullbulk
);
5898 double *score
= dictGetEntryVal(de
);
5899 rank
= zslGetRank(zsl
, *score
, c
->argv
[2]);
5902 addReplyLong(c
, zsl
->length
- rank
);
5904 addReplyLong(c
, rank
-1);
5907 addReply(c
,shared
.nullbulk
);
5912 static void zrankCommand(redisClient
*c
) {
5913 zrankGenericCommand(c
, 0);
5916 static void zrevrankCommand(redisClient
*c
) {
5917 zrankGenericCommand(c
, 1);
5920 /* =================================== Hashes =============================== */
5921 static void hsetCommand(redisClient
*c
) {
5923 robj
*o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
5926 o
= createHashObject();
5927 dictAdd(c
->db
->dict
,c
->argv
[1],o
);
5928 incrRefCount(c
->argv
[1]);
5930 if (o
->type
!= REDIS_HASH
) {
5931 addReply(c
,shared
.wrongtypeerr
);
5935 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
5936 unsigned char *zm
= o
->ptr
;
5937 robj
*valobj
= getDecodedObject(c
->argv
[3]);
5939 zm
= zipmapSet(zm
,c
->argv
[2]->ptr
,sdslen(c
->argv
[2]->ptr
),
5940 valobj
->ptr
,sdslen(valobj
->ptr
),&update
);
5941 decrRefCount(valobj
);
5944 if (dictAdd(o
->ptr
,c
->argv
[2],c
->argv
[3]) == DICT_OK
) {
5945 incrRefCount(c
->argv
[2]);
5949 incrRefCount(c
->argv
[3]);
5952 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",update
== 0));
5955 static void hgetCommand(redisClient
*c
) {
5956 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5959 addReply(c
,shared
.nullbulk
);
5962 if (o
->type
!= REDIS_HASH
) {
5963 addReply(c
,shared
.wrongtypeerr
);
5967 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
5968 unsigned char *zm
= o
->ptr
;
5972 if (zipmapGet(zm
,c
->argv
[2]->ptr
,sdslen(c
->argv
[2]->ptr
), &val
,&vlen
)) {
5973 addReplySds(c
,sdscatprintf(sdsempty(),"$%u\r\n", vlen
));
5974 addReplySds(c
,sdsnewlen(val
,vlen
));
5975 addReply(c
,shared
.crlf
);
5978 addReply(c
,shared
.nullbulk
);
5982 struct dictEntry
*de
;
5984 de
= dictFind(o
->ptr
,c
->argv
[2]);
5986 addReply(c
,shared
.nullbulk
);
5988 robj
*e
= dictGetEntryVal(de
);
5990 addReplyBulkLen(c
,e
);
5992 addReply(c
,shared
.crlf
);
5998 static void hdelCommand(redisClient
*c
) {
5999 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[1]);
6002 addReply(c
,shared
.czero
);
6007 if (o
->type
!= REDIS_HASH
) {
6008 addReply(c
,shared
.wrongtypeerr
);
6012 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6013 o
->ptr
= zipmapDel((unsigned char*) o
->ptr
,
6014 (unsigned char*) c
->argv
[2]->ptr
,
6015 sdslen(c
->argv
[2]->ptr
), &deleted
);
6017 deleted
= dictDelete((dict
*)o
->ptr
,c
->argv
[2]) == DICT_OK
;
6019 addReply(c
,deleted
? shared
.cone
: shared
.czero
);
6023 static void convertToRealHash(robj
*o
) {
6024 unsigned char *key
, *val
, *p
, *zm
= o
->ptr
;
6025 unsigned int klen
, vlen
;
6026 dict
*dict
= dictCreate(&hashDictType
,NULL
);
6028 assert(o
->type
== REDIS_HASH
&& o
->encoding
!= REDIS_ENCODING_HT
);
6029 p
= zipmapRewind(zm
);
6030 while((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) != NULL
) {
6031 robj
*keyobj
, *valobj
;
6033 keyobj
= createStringObject((char*)key
,klen
);
6034 valobj
= createStringObject((char*)val
,vlen
);
6035 tryObjectEncoding(keyobj
);
6036 tryObjectEncoding(valobj
);
6037 dictAdd(dict
,keyobj
,valobj
);
6039 o
->encoding
= REDIS_ENCODING_HT
;
6044 /* ========================= Non type-specific commands ==================== */
6046 static void flushdbCommand(redisClient
*c
) {
6047 server
.dirty
+= dictSize(c
->db
->dict
);
6048 dictEmpty(c
->db
->dict
);
6049 dictEmpty(c
->db
->expires
);
6050 addReply(c
,shared
.ok
);
6053 static void flushallCommand(redisClient
*c
) {
6054 server
.dirty
+= emptyDb();
6055 addReply(c
,shared
.ok
);
6056 rdbSave(server
.dbfilename
);
6060 static redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
6061 redisSortOperation
*so
= zmalloc(sizeof(*so
));
6063 so
->pattern
= pattern
;
6067 /* Return the value associated to the key with a name obtained
6068 * substituting the first occurence of '*' in 'pattern' with 'subst' */
6069 static robj
*lookupKeyByPattern(redisDb
*db
, robj
*pattern
, robj
*subst
) {
6073 int prefixlen
, sublen
, postfixlen
;
6074 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
6078 char buf
[REDIS_SORTKEY_MAX
+1];
6081 /* If the pattern is "#" return the substitution object itself in order
6082 * to implement the "SORT ... GET #" feature. */
6083 spat
= pattern
->ptr
;
6084 if (spat
[0] == '#' && spat
[1] == '\0') {
6088 /* The substitution object may be specially encoded. If so we create
6089 * a decoded object on the fly. Otherwise getDecodedObject will just
6090 * increment the ref count, that we'll decrement later. */
6091 subst
= getDecodedObject(subst
);
6094 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
6095 p
= strchr(spat
,'*');
6097 decrRefCount(subst
);
6102 sublen
= sdslen(ssub
);
6103 postfixlen
= sdslen(spat
)-(prefixlen
+1);
6104 memcpy(keyname
.buf
,spat
,prefixlen
);
6105 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
6106 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
6107 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
6108 keyname
.len
= prefixlen
+sublen
+postfixlen
;
6110 initStaticStringObject(keyobj
,((char*)&keyname
)+(sizeof(long)*2))
6111 decrRefCount(subst
);
6113 /* printf("lookup '%s' => %p\n", keyname.buf,de); */
6114 return lookupKeyRead(db
,&keyobj
);
6117 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
6118 * the additional parameter is not standard but a BSD-specific we have to
6119 * pass sorting parameters via the global 'server' structure */
6120 static int sortCompare(const void *s1
, const void *s2
) {
6121 const redisSortObject
*so1
= s1
, *so2
= s2
;
6124 if (!server
.sort_alpha
) {
6125 /* Numeric sorting. Here it's trivial as we precomputed scores */
6126 if (so1
->u
.score
> so2
->u
.score
) {
6128 } else if (so1
->u
.score
< so2
->u
.score
) {
6134 /* Alphanumeric sorting */
6135 if (server
.sort_bypattern
) {
6136 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
6137 /* At least one compare object is NULL */
6138 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
6140 else if (so1
->u
.cmpobj
== NULL
)
6145 /* We have both the objects, use strcoll */
6146 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
6149 /* Compare elements directly */
6152 dec1
= getDecodedObject(so1
->obj
);
6153 dec2
= getDecodedObject(so2
->obj
);
6154 cmp
= strcoll(dec1
->ptr
,dec2
->ptr
);
6159 return server
.sort_desc
? -cmp
: cmp
;
6162 /* The SORT command is the most complex command in Redis. Warning: this code
6163 * is optimized for speed and a bit less for readability */
6164 static void sortCommand(redisClient
*c
) {
6167 int desc
= 0, alpha
= 0;
6168 int limit_start
= 0, limit_count
= -1, start
, end
;
6169 int j
, dontsort
= 0, vectorlen
;
6170 int getop
= 0; /* GET operation counter */
6171 robj
*sortval
, *sortby
= NULL
, *storekey
= NULL
;
6172 redisSortObject
*vector
; /* Resulting vector to sort */
6174 /* Lookup the key to sort. It must be of the right types */
6175 sortval
= lookupKeyRead(c
->db
,c
->argv
[1]);
6176 if (sortval
== NULL
) {
6177 addReply(c
,shared
.nullmultibulk
);
6180 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
&&
6181 sortval
->type
!= REDIS_ZSET
)
6183 addReply(c
,shared
.wrongtypeerr
);
6187 /* Create a list of operations to perform for every sorted element.
6188 * Operations can be GET/DEL/INCR/DECR */
6189 operations
= listCreate();
6190 listSetFreeMethod(operations
,zfree
);
6193 /* Now we need to protect sortval incrementing its count, in the future
6194 * SORT may have options able to overwrite/delete keys during the sorting
6195 * and the sorted key itself may get destroied */
6196 incrRefCount(sortval
);
6198 /* The SORT command has an SQL-alike syntax, parse it */
6199 while(j
< c
->argc
) {
6200 int leftargs
= c
->argc
-j
-1;
6201 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
6203 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
6205 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
6207 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
6208 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
6209 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
6211 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"store") && leftargs
>= 1) {
6212 storekey
= c
->argv
[j
+1];
6214 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
6215 sortby
= c
->argv
[j
+1];
6216 /* If the BY pattern does not contain '*', i.e. it is constant,
6217 * we don't need to sort nor to lookup the weight keys. */
6218 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
6220 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
6221 listAddNodeTail(operations
,createSortOperation(
6222 REDIS_SORT_GET
,c
->argv
[j
+1]));
6226 decrRefCount(sortval
);
6227 listRelease(operations
);
6228 addReply(c
,shared
.syntaxerr
);
6234 /* Load the sorting vector with all the objects to sort */
6235 switch(sortval
->type
) {
6236 case REDIS_LIST
: vectorlen
= listLength((list
*)sortval
->ptr
); break;
6237 case REDIS_SET
: vectorlen
= dictSize((dict
*)sortval
->ptr
); break;
6238 case REDIS_ZSET
: vectorlen
= dictSize(((zset
*)sortval
->ptr
)->dict
); break;
6239 default: vectorlen
= 0; redisAssert(0); /* Avoid GCC warning */
6241 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
6244 if (sortval
->type
== REDIS_LIST
) {
6245 list
*list
= sortval
->ptr
;
6249 listRewind(list
,&li
);
6250 while((ln
= listNext(&li
))) {
6251 robj
*ele
= ln
->value
;
6252 vector
[j
].obj
= ele
;
6253 vector
[j
].u
.score
= 0;
6254 vector
[j
].u
.cmpobj
= NULL
;
6262 if (sortval
->type
== REDIS_SET
) {
6265 zset
*zs
= sortval
->ptr
;
6269 di
= dictGetIterator(set
);
6270 while((setele
= dictNext(di
)) != NULL
) {
6271 vector
[j
].obj
= dictGetEntryKey(setele
);
6272 vector
[j
].u
.score
= 0;
6273 vector
[j
].u
.cmpobj
= NULL
;
6276 dictReleaseIterator(di
);
6278 redisAssert(j
== vectorlen
);
6280 /* Now it's time to load the right scores in the sorting vector */
6281 if (dontsort
== 0) {
6282 for (j
= 0; j
< vectorlen
; j
++) {
6286 byval
= lookupKeyByPattern(c
->db
,sortby
,vector
[j
].obj
);
6287 if (!byval
|| byval
->type
!= REDIS_STRING
) continue;
6289 vector
[j
].u
.cmpobj
= getDecodedObject(byval
);
6291 if (byval
->encoding
== REDIS_ENCODING_RAW
) {
6292 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
6294 /* Don't need to decode the object if it's
6295 * integer-encoded (the only encoding supported) so
6296 * far. We can just cast it */
6297 if (byval
->encoding
== REDIS_ENCODING_INT
) {
6298 vector
[j
].u
.score
= (long)byval
->ptr
;
6300 redisAssert(1 != 1);
6305 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_RAW
)
6306 vector
[j
].u
.score
= strtod(vector
[j
].obj
->ptr
,NULL
);
6308 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_INT
)
6309 vector
[j
].u
.score
= (long) vector
[j
].obj
->ptr
;
6311 redisAssert(1 != 1);
6318 /* We are ready to sort the vector... perform a bit of sanity check
6319 * on the LIMIT option too. We'll use a partial version of quicksort. */
6320 start
= (limit_start
< 0) ? 0 : limit_start
;
6321 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
6322 if (start
>= vectorlen
) {
6323 start
= vectorlen
-1;
6326 if (end
>= vectorlen
) end
= vectorlen
-1;
6328 if (dontsort
== 0) {
6329 server
.sort_desc
= desc
;
6330 server
.sort_alpha
= alpha
;
6331 server
.sort_bypattern
= sortby
? 1 : 0;
6332 if (sortby
&& (start
!= 0 || end
!= vectorlen
-1))
6333 pqsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
, start
,end
);
6335 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
6338 /* Send command output to the output buffer, performing the specified
6339 * GET/DEL/INCR/DECR operations if any. */
6340 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
6341 if (storekey
== NULL
) {
6342 /* STORE option not specified, sent the sorting result to client */
6343 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
6344 for (j
= start
; j
<= end
; j
++) {
6349 addReplyBulkLen(c
,vector
[j
].obj
);
6350 addReply(c
,vector
[j
].obj
);
6351 addReply(c
,shared
.crlf
);
6353 listRewind(operations
,&li
);
6354 while((ln
= listNext(&li
))) {
6355 redisSortOperation
*sop
= ln
->value
;
6356 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
6359 if (sop
->type
== REDIS_SORT_GET
) {
6360 if (!val
|| val
->type
!= REDIS_STRING
) {
6361 addReply(c
,shared
.nullbulk
);
6363 addReplyBulkLen(c
,val
);
6365 addReply(c
,shared
.crlf
);
6368 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
6373 robj
*listObject
= createListObject();
6374 list
*listPtr
= (list
*) listObject
->ptr
;
6376 /* STORE option specified, set the sorting result as a List object */
6377 for (j
= start
; j
<= end
; j
++) {
6382 listAddNodeTail(listPtr
,vector
[j
].obj
);
6383 incrRefCount(vector
[j
].obj
);
6385 listRewind(operations
,&li
);
6386 while((ln
= listNext(&li
))) {
6387 redisSortOperation
*sop
= ln
->value
;
6388 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
6391 if (sop
->type
== REDIS_SORT_GET
) {
6392 if (!val
|| val
->type
!= REDIS_STRING
) {
6393 listAddNodeTail(listPtr
,createStringObject("",0));
6395 listAddNodeTail(listPtr
,val
);
6399 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
6403 if (dictReplace(c
->db
->dict
,storekey
,listObject
)) {
6404 incrRefCount(storekey
);
6406 /* Note: we add 1 because the DB is dirty anyway since even if the
6407 * SORT result is empty a new key is set and maybe the old content
6409 server
.dirty
+= 1+outputlen
;
6410 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",outputlen
));
6414 decrRefCount(sortval
);
6415 listRelease(operations
);
6416 for (j
= 0; j
< vectorlen
; j
++) {
6417 if (sortby
&& alpha
&& vector
[j
].u
.cmpobj
)
6418 decrRefCount(vector
[j
].u
.cmpobj
);
6423 /* Convert an amount of bytes into a human readable string in the form
6424 * of 100B, 2G, 100M, 4K, and so forth. */
6425 static void bytesToHuman(char *s
, unsigned long long n
) {
6430 sprintf(s
,"%lluB",n
);
6432 } else if (n
< (1024*1024)) {
6433 d
= (double)n
/(1024);
6434 sprintf(s
,"%.2fK",d
);
6435 } else if (n
< (1024LL*1024*1024)) {
6436 d
= (double)n
/(1024*1024);
6437 sprintf(s
,"%.2fM",d
);
6438 } else if (n
< (1024LL*1024*1024*1024)) {
6439 d
= (double)n
/(1024LL*1024*1024);
6440 sprintf(s
,"%.2fG",d
);
6444 /* Create the string returned by the INFO command. This is decoupled
6445 * by the INFO command itself as we need to report the same information
6446 * on memory corruption problems. */
6447 static sds
genRedisInfoString(void) {
6449 time_t uptime
= time(NULL
)-server
.stat_starttime
;
6453 bytesToHuman(hmem
,zmalloc_used_memory());
6454 info
= sdscatprintf(sdsempty(),
6455 "redis_version:%s\r\n"
6457 "multiplexing_api:%s\r\n"
6458 "process_id:%ld\r\n"
6459 "uptime_in_seconds:%ld\r\n"
6460 "uptime_in_days:%ld\r\n"
6461 "connected_clients:%d\r\n"
6462 "connected_slaves:%d\r\n"
6463 "blocked_clients:%d\r\n"
6464 "used_memory:%zu\r\n"
6465 "used_memory_human:%s\r\n"
6466 "changes_since_last_save:%lld\r\n"
6467 "bgsave_in_progress:%d\r\n"
6468 "last_save_time:%ld\r\n"
6469 "bgrewriteaof_in_progress:%d\r\n"
6470 "total_connections_received:%lld\r\n"
6471 "total_commands_processed:%lld\r\n"
6475 (sizeof(long) == 8) ? "64" : "32",
6480 listLength(server
.clients
)-listLength(server
.slaves
),
6481 listLength(server
.slaves
),
6482 server
.blpop_blocked_clients
,
6483 zmalloc_used_memory(),
6486 server
.bgsavechildpid
!= -1,
6488 server
.bgrewritechildpid
!= -1,
6489 server
.stat_numconnections
,
6490 server
.stat_numcommands
,
6491 server
.vm_enabled
!= 0,
6492 server
.masterhost
== NULL
? "master" : "slave"
6494 if (server
.masterhost
) {
6495 info
= sdscatprintf(info
,
6496 "master_host:%s\r\n"
6497 "master_port:%d\r\n"
6498 "master_link_status:%s\r\n"
6499 "master_last_io_seconds_ago:%d\r\n"
6502 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
6504 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1
6507 if (server
.vm_enabled
) {
6509 info
= sdscatprintf(info
,
6510 "vm_conf_max_memory:%llu\r\n"
6511 "vm_conf_page_size:%llu\r\n"
6512 "vm_conf_pages:%llu\r\n"
6513 "vm_stats_used_pages:%llu\r\n"
6514 "vm_stats_swapped_objects:%llu\r\n"
6515 "vm_stats_swappin_count:%llu\r\n"
6516 "vm_stats_swappout_count:%llu\r\n"
6517 "vm_stats_io_newjobs_len:%lu\r\n"
6518 "vm_stats_io_processing_len:%lu\r\n"
6519 "vm_stats_io_processed_len:%lu\r\n"
6520 "vm_stats_io_active_threads:%lu\r\n"
6521 "vm_stats_blocked_clients:%lu\r\n"
6522 ,(unsigned long long) server
.vm_max_memory
,
6523 (unsigned long long) server
.vm_page_size
,
6524 (unsigned long long) server
.vm_pages
,
6525 (unsigned long long) server
.vm_stats_used_pages
,
6526 (unsigned long long) server
.vm_stats_swapped_objects
,
6527 (unsigned long long) server
.vm_stats_swapins
,
6528 (unsigned long long) server
.vm_stats_swapouts
,
6529 (unsigned long) listLength(server
.io_newjobs
),
6530 (unsigned long) listLength(server
.io_processing
),
6531 (unsigned long) listLength(server
.io_processed
),
6532 (unsigned long) server
.io_active_threads
,
6533 (unsigned long) server
.vm_blocked_clients
6537 for (j
= 0; j
< server
.dbnum
; j
++) {
6538 long long keys
, vkeys
;
6540 keys
= dictSize(server
.db
[j
].dict
);
6541 vkeys
= dictSize(server
.db
[j
].expires
);
6542 if (keys
|| vkeys
) {
6543 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
6550 static void infoCommand(redisClient
*c
) {
6551 sds info
= genRedisInfoString();
6552 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
6553 (unsigned long)sdslen(info
)));
6554 addReplySds(c
,info
);
6555 addReply(c
,shared
.crlf
);
6558 static void monitorCommand(redisClient
*c
) {
6559 /* ignore MONITOR if aleady slave or in monitor mode */
6560 if (c
->flags
& REDIS_SLAVE
) return;
6562 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
6564 listAddNodeTail(server
.monitors
,c
);
6565 addReply(c
,shared
.ok
);
6568 /* ================================= Expire ================================= */
6569 static int removeExpire(redisDb
*db
, robj
*key
) {
6570 if (dictDelete(db
->expires
,key
) == DICT_OK
) {
6577 static int setExpire(redisDb
*db
, robj
*key
, time_t when
) {
6578 if (dictAdd(db
->expires
,key
,(void*)when
) == DICT_ERR
) {
6586 /* Return the expire time of the specified key, or -1 if no expire
6587 * is associated with this key (i.e. the key is non volatile) */
6588 static time_t getExpire(redisDb
*db
, robj
*key
) {
6591 /* No expire? return ASAP */
6592 if (dictSize(db
->expires
) == 0 ||
6593 (de
= dictFind(db
->expires
,key
)) == NULL
) return -1;
6595 return (time_t) dictGetEntryVal(de
);
6598 static int expireIfNeeded(redisDb
*db
, robj
*key
) {
6602 /* No expire? return ASAP */
6603 if (dictSize(db
->expires
) == 0 ||
6604 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
6606 /* Lookup the expire */
6607 when
= (time_t) dictGetEntryVal(de
);
6608 if (time(NULL
) <= when
) return 0;
6610 /* Delete the key */
6611 dictDelete(db
->expires
,key
);
6612 return dictDelete(db
->dict
,key
) == DICT_OK
;
6615 static int deleteIfVolatile(redisDb
*db
, robj
*key
) {
6618 /* No expire? return ASAP */
6619 if (dictSize(db
->expires
) == 0 ||
6620 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
6622 /* Delete the key */
6624 dictDelete(db
->expires
,key
);
6625 return dictDelete(db
->dict
,key
) == DICT_OK
;
6628 static void expireGenericCommand(redisClient
*c
, robj
*key
, time_t seconds
) {
6631 de
= dictFind(c
->db
->dict
,key
);
6633 addReply(c
,shared
.czero
);
6637 if (deleteKey(c
->db
,key
)) server
.dirty
++;
6638 addReply(c
, shared
.cone
);
6641 time_t when
= time(NULL
)+seconds
;
6642 if (setExpire(c
->db
,key
,when
)) {
6643 addReply(c
,shared
.cone
);
6646 addReply(c
,shared
.czero
);
6652 static void expireCommand(redisClient
*c
) {
6653 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10));
6656 static void expireatCommand(redisClient
*c
) {
6657 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10)-time(NULL
));
6660 static void ttlCommand(redisClient
*c
) {
6664 expire
= getExpire(c
->db
,c
->argv
[1]);
6666 ttl
= (int) (expire
-time(NULL
));
6667 if (ttl
< 0) ttl
= -1;
6669 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",ttl
));
6672 /* ================================ MULTI/EXEC ============================== */
6674 /* Client state initialization for MULTI/EXEC */
6675 static void initClientMultiState(redisClient
*c
) {
6676 c
->mstate
.commands
= NULL
;
6677 c
->mstate
.count
= 0;
6680 /* Release all the resources associated with MULTI/EXEC state */
6681 static void freeClientMultiState(redisClient
*c
) {
6684 for (j
= 0; j
< c
->mstate
.count
; j
++) {
6686 multiCmd
*mc
= c
->mstate
.commands
+j
;
6688 for (i
= 0; i
< mc
->argc
; i
++)
6689 decrRefCount(mc
->argv
[i
]);
6692 zfree(c
->mstate
.commands
);
6695 /* Add a new command into the MULTI commands queue */
6696 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
) {
6700 c
->mstate
.commands
= zrealloc(c
->mstate
.commands
,
6701 sizeof(multiCmd
)*(c
->mstate
.count
+1));
6702 mc
= c
->mstate
.commands
+c
->mstate
.count
;
6705 mc
->argv
= zmalloc(sizeof(robj
*)*c
->argc
);
6706 memcpy(mc
->argv
,c
->argv
,sizeof(robj
*)*c
->argc
);
6707 for (j
= 0; j
< c
->argc
; j
++)
6708 incrRefCount(mc
->argv
[j
]);
6712 static void multiCommand(redisClient
*c
) {
6713 c
->flags
|= REDIS_MULTI
;
6714 addReply(c
,shared
.ok
);
6717 static void discardCommand(redisClient
*c
) {
6718 if (!(c
->flags
& REDIS_MULTI
)) {
6719 addReplySds(c
,sdsnew("-ERR DISCARD without MULTI\r\n"));
6723 freeClientMultiState(c
);
6724 initClientMultiState(c
);
6725 c
->flags
&= (~REDIS_MULTI
);
6726 addReply(c
,shared
.ok
);
6729 static void execCommand(redisClient
*c
) {
6734 if (!(c
->flags
& REDIS_MULTI
)) {
6735 addReplySds(c
,sdsnew("-ERR EXEC without MULTI\r\n"));
6739 orig_argv
= c
->argv
;
6740 orig_argc
= c
->argc
;
6741 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->mstate
.count
));
6742 for (j
= 0; j
< c
->mstate
.count
; j
++) {
6743 c
->argc
= c
->mstate
.commands
[j
].argc
;
6744 c
->argv
= c
->mstate
.commands
[j
].argv
;
6745 call(c
,c
->mstate
.commands
[j
].cmd
);
6747 c
->argv
= orig_argv
;
6748 c
->argc
= orig_argc
;
6749 freeClientMultiState(c
);
6750 initClientMultiState(c
);
6751 c
->flags
&= (~REDIS_MULTI
);
6754 /* =========================== Blocking Operations ========================= */
6756 /* Currently Redis blocking operations support is limited to list POP ops,
6757 * so the current implementation is not fully generic, but it is also not
6758 * completely specific so it will not require a rewrite to support new
6759 * kind of blocking operations in the future.
6761 * Still it's important to note that list blocking operations can be already
6762 * used as a notification mechanism in order to implement other blocking
6763 * operations at application level, so there must be a very strong evidence
6764 * of usefulness and generality before new blocking operations are implemented.
6766 * This is how the current blocking POP works, we use BLPOP as example:
6767 * - If the user calls BLPOP and the key exists and contains a non empty list
6768 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
6769 * if there is not to block.
6770 * - If instead BLPOP is called and the key does not exists or the list is
6771 * empty we need to block. In order to do so we remove the notification for
6772 * new data to read in the client socket (so that we'll not serve new
6773 * requests if the blocking request is not served). Also we put the client
6774 * in a dictionary (db->blockingkeys) mapping keys to a list of clients
6775 * blocking for this keys.
6776 * - If a PUSH operation against a key with blocked clients waiting is
6777 * performed, we serve the first in the list: basically instead to push
6778 * the new element inside the list we return it to the (first / oldest)
6779 * blocking client, unblock the client, and remove it form the list.
6781 * The above comment and the source code should be enough in order to understand
6782 * the implementation and modify / fix it later.
6785 /* Set a client in blocking mode for the specified key, with the specified
6787 static void blockForKeys(redisClient
*c
, robj
**keys
, int numkeys
, time_t timeout
) {
6792 c
->blockingkeys
= zmalloc(sizeof(robj
*)*numkeys
);
6793 c
->blockingkeysnum
= numkeys
;
6794 c
->blockingto
= timeout
;
6795 for (j
= 0; j
< numkeys
; j
++) {
6796 /* Add the key in the client structure, to map clients -> keys */
6797 c
->blockingkeys
[j
] = keys
[j
];
6798 incrRefCount(keys
[j
]);
6800 /* And in the other "side", to map keys -> clients */
6801 de
= dictFind(c
->db
->blockingkeys
,keys
[j
]);
6805 /* For every key we take a list of clients blocked for it */
6807 retval
= dictAdd(c
->db
->blockingkeys
,keys
[j
],l
);
6808 incrRefCount(keys
[j
]);
6809 assert(retval
== DICT_OK
);
6811 l
= dictGetEntryVal(de
);
6813 listAddNodeTail(l
,c
);
6815 /* Mark the client as a blocked client */
6816 c
->flags
|= REDIS_BLOCKED
;
6817 server
.blpop_blocked_clients
++;
6820 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
6821 static void unblockClientWaitingData(redisClient
*c
) {
6826 assert(c
->blockingkeys
!= NULL
);
6827 /* The client may wait for multiple keys, so unblock it for every key. */
6828 for (j
= 0; j
< c
->blockingkeysnum
; j
++) {
6829 /* Remove this client from the list of clients waiting for this key. */
6830 de
= dictFind(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
6832 l
= dictGetEntryVal(de
);
6833 listDelNode(l
,listSearchKey(l
,c
));
6834 /* If the list is empty we need to remove it to avoid wasting memory */
6835 if (listLength(l
) == 0)
6836 dictDelete(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
6837 decrRefCount(c
->blockingkeys
[j
]);
6839 /* Cleanup the client structure */
6840 zfree(c
->blockingkeys
);
6841 c
->blockingkeys
= NULL
;
6842 c
->flags
&= (~REDIS_BLOCKED
);
6843 server
.blpop_blocked_clients
--;
6844 /* We want to process data if there is some command waiting
6845 * in the input buffer. Note that this is safe even if
6846 * unblockClientWaitingData() gets called from freeClient() because
6847 * freeClient() will be smart enough to call this function
6848 * *after* c->querybuf was set to NULL. */
6849 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0) processInputBuffer(c
);
6852 /* This should be called from any function PUSHing into lists.
6853 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
6854 * 'ele' is the element pushed.
6856 * If the function returns 0 there was no client waiting for a list push
6859 * If the function returns 1 there was a client waiting for a list push
6860 * against this key, the element was passed to this client thus it's not
6861 * needed to actually add it to the list and the caller should return asap. */
6862 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
) {
6863 struct dictEntry
*de
;
6864 redisClient
*receiver
;
6868 de
= dictFind(c
->db
->blockingkeys
,key
);
6869 if (de
== NULL
) return 0;
6870 l
= dictGetEntryVal(de
);
6873 receiver
= ln
->value
;
6875 addReplySds(receiver
,sdsnew("*2\r\n"));
6876 addReplyBulkLen(receiver
,key
);
6877 addReply(receiver
,key
);
6878 addReply(receiver
,shared
.crlf
);
6879 addReplyBulkLen(receiver
,ele
);
6880 addReply(receiver
,ele
);
6881 addReply(receiver
,shared
.crlf
);
6882 unblockClientWaitingData(receiver
);
6886 /* Blocking RPOP/LPOP */
6887 static void blockingPopGenericCommand(redisClient
*c
, int where
) {
6892 for (j
= 1; j
< c
->argc
-1; j
++) {
6893 o
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
6895 if (o
->type
!= REDIS_LIST
) {
6896 addReply(c
,shared
.wrongtypeerr
);
6899 list
*list
= o
->ptr
;
6900 if (listLength(list
) != 0) {
6901 /* If the list contains elements fall back to the usual
6902 * non-blocking POP operation */
6903 robj
*argv
[2], **orig_argv
;
6906 /* We need to alter the command arguments before to call
6907 * popGenericCommand() as the command takes a single key. */
6908 orig_argv
= c
->argv
;
6909 orig_argc
= c
->argc
;
6910 argv
[1] = c
->argv
[j
];
6914 /* Also the return value is different, we need to output
6915 * the multi bulk reply header and the key name. The
6916 * "real" command will add the last element (the value)
6917 * for us. If this souds like an hack to you it's just
6918 * because it is... */
6919 addReplySds(c
,sdsnew("*2\r\n"));
6920 addReplyBulkLen(c
,argv
[1]);
6921 addReply(c
,argv
[1]);
6922 addReply(c
,shared
.crlf
);
6923 popGenericCommand(c
,where
);
6925 /* Fix the client structure with the original stuff */
6926 c
->argv
= orig_argv
;
6927 c
->argc
= orig_argc
;
6933 /* If the list is empty or the key does not exists we must block */
6934 timeout
= strtol(c
->argv
[c
->argc
-1]->ptr
,NULL
,10);
6935 if (timeout
> 0) timeout
+= time(NULL
);
6936 blockForKeys(c
,c
->argv
+1,c
->argc
-2,timeout
);
6939 static void blpopCommand(redisClient
*c
) {
6940 blockingPopGenericCommand(c
,REDIS_HEAD
);
6943 static void brpopCommand(redisClient
*c
) {
6944 blockingPopGenericCommand(c
,REDIS_TAIL
);
6947 /* =============================== Replication ============================= */
6949 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6950 ssize_t nwritten
, ret
= size
;
6951 time_t start
= time(NULL
);
6955 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
6956 nwritten
= write(fd
,ptr
,size
);
6957 if (nwritten
== -1) return -1;
6961 if ((time(NULL
)-start
) > timeout
) {
6969 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6970 ssize_t nread
, totread
= 0;
6971 time_t start
= time(NULL
);
6975 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
6976 nread
= read(fd
,ptr
,size
);
6977 if (nread
== -1) return -1;
6982 if ((time(NULL
)-start
) > timeout
) {
6990 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6997 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
7000 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
7011 static void syncCommand(redisClient
*c
) {
7012 /* ignore SYNC if aleady slave or in monitor mode */
7013 if (c
->flags
& REDIS_SLAVE
) return;
7015 /* SYNC can't be issued when the server has pending data to send to
7016 * the client about already issued commands. We need a fresh reply
7017 * buffer registering the differences between the BGSAVE and the current
7018 * dataset, so that we can copy to other slaves if needed. */
7019 if (listLength(c
->reply
) != 0) {
7020 addReplySds(c
,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
7024 redisLog(REDIS_NOTICE
,"Slave ask for synchronization");
7025 /* Here we need to check if there is a background saving operation
7026 * in progress, or if it is required to start one */
7027 if (server
.bgsavechildpid
!= -1) {
7028 /* Ok a background save is in progress. Let's check if it is a good
7029 * one for replication, i.e. if there is another slave that is
7030 * registering differences since the server forked to save */
7035 listRewind(server
.slaves
,&li
);
7036 while((ln
= listNext(&li
))) {
7038 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) break;
7041 /* Perfect, the server is already registering differences for
7042 * another slave. Set the right state, and copy the buffer. */
7043 listRelease(c
->reply
);
7044 c
->reply
= listDup(slave
->reply
);
7045 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
7046 redisLog(REDIS_NOTICE
,"Waiting for end of BGSAVE for SYNC");
7048 /* No way, we need to wait for the next BGSAVE in order to
7049 * register differences */
7050 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
7051 redisLog(REDIS_NOTICE
,"Waiting for next BGSAVE for SYNC");
7054 /* Ok we don't have a BGSAVE in progress, let's start one */
7055 redisLog(REDIS_NOTICE
,"Starting BGSAVE for SYNC");
7056 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
7057 redisLog(REDIS_NOTICE
,"Replication failed, can't BGSAVE");
7058 addReplySds(c
,sdsnew("-ERR Unalbe to perform background save\r\n"));
7061 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
7064 c
->flags
|= REDIS_SLAVE
;
7066 listAddNodeTail(server
.slaves
,c
);
7070 static void sendBulkToSlave(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
7071 redisClient
*slave
= privdata
;
7073 REDIS_NOTUSED(mask
);
7074 char buf
[REDIS_IOBUF_LEN
];
7075 ssize_t nwritten
, buflen
;
7077 if (slave
->repldboff
== 0) {
7078 /* Write the bulk write count before to transfer the DB. In theory here
7079 * we don't know how much room there is in the output buffer of the
7080 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
7081 * operations) will never be smaller than the few bytes we need. */
7084 bulkcount
= sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
7086 if (write(fd
,bulkcount
,sdslen(bulkcount
)) != (signed)sdslen(bulkcount
))
7094 lseek(slave
->repldbfd
,slave
->repldboff
,SEEK_SET
);
7095 buflen
= read(slave
->repldbfd
,buf
,REDIS_IOBUF_LEN
);
7097 redisLog(REDIS_WARNING
,"Read error sending DB to slave: %s",
7098 (buflen
== 0) ? "premature EOF" : strerror(errno
));
7102 if ((nwritten
= write(fd
,buf
,buflen
)) == -1) {
7103 redisLog(REDIS_VERBOSE
,"Write error sending DB to slave: %s",
7108 slave
->repldboff
+= nwritten
;
7109 if (slave
->repldboff
== slave
->repldbsize
) {
7110 close(slave
->repldbfd
);
7111 slave
->repldbfd
= -1;
7112 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
7113 slave
->replstate
= REDIS_REPL_ONLINE
;
7114 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
,
7115 sendReplyToClient
, slave
) == AE_ERR
) {
7119 addReplySds(slave
,sdsempty());
7120 redisLog(REDIS_NOTICE
,"Synchronization with slave succeeded");
7124 /* This function is called at the end of every backgrond saving.
7125 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
7126 * otherwise REDIS_ERR is passed to the function.
7128 * The goal of this function is to handle slaves waiting for a successful
7129 * background saving in order to perform non-blocking synchronization. */
7130 static void updateSlavesWaitingBgsave(int bgsaveerr
) {
7132 int startbgsave
= 0;
7135 listRewind(server
.slaves
,&li
);
7136 while((ln
= listNext(&li
))) {
7137 redisClient
*slave
= ln
->value
;
7139 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) {
7141 slave
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
7142 } else if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) {
7143 struct redis_stat buf
;
7145 if (bgsaveerr
!= REDIS_OK
) {
7147 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE child returned an error");
7150 if ((slave
->repldbfd
= open(server
.dbfilename
,O_RDONLY
)) == -1 ||
7151 redis_fstat(slave
->repldbfd
,&buf
) == -1) {
7153 redisLog(REDIS_WARNING
,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno
));
7156 slave
->repldboff
= 0;
7157 slave
->repldbsize
= buf
.st_size
;
7158 slave
->replstate
= REDIS_REPL_SEND_BULK
;
7159 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
7160 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
, sendBulkToSlave
, slave
) == AE_ERR
) {
7167 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
7170 listRewind(server
.slaves
,&li
);
7171 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE failed");
7172 while((ln
= listNext(&li
))) {
7173 redisClient
*slave
= ln
->value
;
7175 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
)
7182 static int syncWithMaster(void) {
7183 char buf
[1024], tmpfile
[256], authcmd
[1024];
7185 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
7186 int dfd
, maxtries
= 5;
7189 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
7194 /* AUTH with the master if required. */
7195 if(server
.masterauth
) {
7196 snprintf(authcmd
, 1024, "AUTH %s\r\n", server
.masterauth
);
7197 if (syncWrite(fd
, authcmd
, strlen(server
.masterauth
)+7, 5) == -1) {
7199 redisLog(REDIS_WARNING
,"Unable to AUTH to MASTER: %s",
7203 /* Read the AUTH result. */
7204 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
7206 redisLog(REDIS_WARNING
,"I/O error reading auth result from MASTER: %s",
7210 if (buf
[0] != '+') {
7212 redisLog(REDIS_WARNING
,"Cannot AUTH to MASTER, is the masterauth password correct?");
7217 /* Issue the SYNC command */
7218 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
7220 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
7224 /* Read the bulk write count */
7225 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
7227 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
7231 if (buf
[0] != '$') {
7233 redisLog(REDIS_WARNING
,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
7236 dumpsize
= strtol(buf
+1,NULL
,10);
7237 redisLog(REDIS_NOTICE
,"Receiving %ld bytes data dump from MASTER",dumpsize
);
7238 /* Read the bulk write data on a temp file */
7240 snprintf(tmpfile
,256,
7241 "temp-%d.%ld.rdb",(int)time(NULL
),(long int)getpid());
7242 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
|O_EXCL
,0644);
7243 if (dfd
!= -1) break;
7248 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
7252 int nread
, nwritten
;
7254 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
7256 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
7262 nwritten
= write(dfd
,buf
,nread
);
7263 if (nwritten
== -1) {
7264 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
7272 if (rename(tmpfile
,server
.dbfilename
) == -1) {
7273 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
7279 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
7280 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
7284 server
.master
= createClient(fd
);
7285 server
.master
->flags
|= REDIS_MASTER
;
7286 server
.master
->authenticated
= 1;
7287 server
.replstate
= REDIS_REPL_CONNECTED
;
7291 static void slaveofCommand(redisClient
*c
) {
7292 if (!strcasecmp(c
->argv
[1]->ptr
,"no") &&
7293 !strcasecmp(c
->argv
[2]->ptr
,"one")) {
7294 if (server
.masterhost
) {
7295 sdsfree(server
.masterhost
);
7296 server
.masterhost
= NULL
;
7297 if (server
.master
) freeClient(server
.master
);
7298 server
.replstate
= REDIS_REPL_NONE
;
7299 redisLog(REDIS_NOTICE
,"MASTER MODE enabled (user request)");
7302 sdsfree(server
.masterhost
);
7303 server
.masterhost
= sdsdup(c
->argv
[1]->ptr
);
7304 server
.masterport
= atoi(c
->argv
[2]->ptr
);
7305 if (server
.master
) freeClient(server
.master
);
7306 server
.replstate
= REDIS_REPL_CONNECT
;
7307 redisLog(REDIS_NOTICE
,"SLAVE OF %s:%d enabled (user request)",
7308 server
.masterhost
, server
.masterport
);
7310 addReply(c
,shared
.ok
);
7313 /* ============================ Maxmemory directive ======================== */
7315 /* Try to free one object form the pre-allocated objects free list.
7316 * This is useful under low mem conditions as by default we take 1 million
7317 * free objects allocated. On success REDIS_OK is returned, otherwise
7319 static int tryFreeOneObjectFromFreelist(void) {
7322 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
7323 if (listLength(server
.objfreelist
)) {
7324 listNode
*head
= listFirst(server
.objfreelist
);
7325 o
= listNodeValue(head
);
7326 listDelNode(server
.objfreelist
,head
);
7327 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
7331 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
7336 /* This function gets called when 'maxmemory' is set on the config file to limit
7337 * the max memory used by the server, and we are out of memory.
7338 * This function will try to, in order:
7340 * - Free objects from the free list
7341 * - Try to remove keys with an EXPIRE set
7343 * It is not possible to free enough memory to reach used-memory < maxmemory
7344 * the server will start refusing commands that will enlarge even more the
7347 static void freeMemoryIfNeeded(void) {
7348 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
7349 int j
, k
, freed
= 0;
7351 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
7352 for (j
= 0; j
< server
.dbnum
; j
++) {
7354 robj
*minkey
= NULL
;
7355 struct dictEntry
*de
;
7357 if (dictSize(server
.db
[j
].expires
)) {
7359 /* From a sample of three keys drop the one nearest to
7360 * the natural expire */
7361 for (k
= 0; k
< 3; k
++) {
7364 de
= dictGetRandomKey(server
.db
[j
].expires
);
7365 t
= (time_t) dictGetEntryVal(de
);
7366 if (minttl
== -1 || t
< minttl
) {
7367 minkey
= dictGetEntryKey(de
);
7371 deleteKey(server
.db
+j
,minkey
);
7374 if (!freed
) return; /* nothing to free... */
7378 /* ============================== Append Only file ========================== */
7380 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
7381 sds buf
= sdsempty();
7387 /* The DB this command was targetting is not the same as the last command
7388 * we appendend. To issue a SELECT command is needed. */
7389 if (dictid
!= server
.appendseldb
) {
7392 snprintf(seldb
,sizeof(seldb
),"%d",dictid
);
7393 buf
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
7394 (unsigned long)strlen(seldb
),seldb
);
7395 server
.appendseldb
= dictid
;
7398 /* "Fix" the argv vector if the command is EXPIRE. We want to translate
7399 * EXPIREs into EXPIREATs calls */
7400 if (cmd
->proc
== expireCommand
) {
7403 tmpargv
[0] = createStringObject("EXPIREAT",8);
7404 tmpargv
[1] = argv
[1];
7405 incrRefCount(argv
[1]);
7406 when
= time(NULL
)+strtol(argv
[2]->ptr
,NULL
,10);
7407 tmpargv
[2] = createObject(REDIS_STRING
,
7408 sdscatprintf(sdsempty(),"%ld",when
));
7412 /* Append the actual command */
7413 buf
= sdscatprintf(buf
,"*%d\r\n",argc
);
7414 for (j
= 0; j
< argc
; j
++) {
7417 o
= getDecodedObject(o
);
7418 buf
= sdscatprintf(buf
,"$%lu\r\n",(unsigned long)sdslen(o
->ptr
));
7419 buf
= sdscatlen(buf
,o
->ptr
,sdslen(o
->ptr
));
7420 buf
= sdscatlen(buf
,"\r\n",2);
7424 /* Free the objects from the modified argv for EXPIREAT */
7425 if (cmd
->proc
== expireCommand
) {
7426 for (j
= 0; j
< 3; j
++)
7427 decrRefCount(argv
[j
]);
7430 /* We want to perform a single write. This should be guaranteed atomic
7431 * at least if the filesystem we are writing is a real physical one.
7432 * While this will save us against the server being killed I don't think
7433 * there is much to do about the whole server stopping for power problems
7435 nwritten
= write(server
.appendfd
,buf
,sdslen(buf
));
7436 if (nwritten
!= (signed)sdslen(buf
)) {
7437 /* Ooops, we are in troubles. The best thing to do for now is
7438 * to simply exit instead to give the illusion that everything is
7439 * working as expected. */
7440 if (nwritten
== -1) {
7441 redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
));
7443 redisLog(REDIS_WARNING
,"Exiting on short write while writing to the append-only file: %s",strerror(errno
));
7447 /* If a background append only file rewriting is in progress we want to
7448 * accumulate the differences between the child DB and the current one
7449 * in a buffer, so that when the child process will do its work we
7450 * can append the differences to the new append only file. */
7451 if (server
.bgrewritechildpid
!= -1)
7452 server
.bgrewritebuf
= sdscatlen(server
.bgrewritebuf
,buf
,sdslen(buf
));
7456 if (server
.appendfsync
== APPENDFSYNC_ALWAYS
||
7457 (server
.appendfsync
== APPENDFSYNC_EVERYSEC
&&
7458 now
-server
.lastfsync
> 1))
7460 fsync(server
.appendfd
); /* Let's try to get this data on the disk */
7461 server
.lastfsync
= now
;
7465 /* In Redis commands are always executed in the context of a client, so in
7466 * order to load the append only file we need to create a fake client. */
7467 static struct redisClient
*createFakeClient(void) {
7468 struct redisClient
*c
= zmalloc(sizeof(*c
));
7472 c
->querybuf
= sdsempty();
7476 /* We set the fake client as a slave waiting for the synchronization
7477 * so that Redis will not try to send replies to this client. */
7478 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
7479 c
->reply
= listCreate();
7480 listSetFreeMethod(c
->reply
,decrRefCount
);
7481 listSetDupMethod(c
->reply
,dupClientReplyValue
);
7485 static void freeFakeClient(struct redisClient
*c
) {
7486 sdsfree(c
->querybuf
);
7487 listRelease(c
->reply
);
7491 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
7492 * error (the append only file is zero-length) REDIS_ERR is returned. On
7493 * fatal error an error message is logged and the program exists. */
7494 int loadAppendOnlyFile(char *filename
) {
7495 struct redisClient
*fakeClient
;
7496 FILE *fp
= fopen(filename
,"r");
7497 struct redis_stat sb
;
7498 unsigned long long loadedkeys
= 0;
7500 if (redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0)
7504 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
7508 fakeClient
= createFakeClient();
7515 struct redisCommand
*cmd
;
7517 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
7523 if (buf
[0] != '*') goto fmterr
;
7525 argv
= zmalloc(sizeof(robj
*)*argc
);
7526 for (j
= 0; j
< argc
; j
++) {
7527 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
7528 if (buf
[0] != '$') goto fmterr
;
7529 len
= strtol(buf
+1,NULL
,10);
7530 argsds
= sdsnewlen(NULL
,len
);
7531 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
7532 argv
[j
] = createObject(REDIS_STRING
,argsds
);
7533 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
7536 /* Command lookup */
7537 cmd
= lookupCommand(argv
[0]->ptr
);
7539 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
7542 /* Try object sharing and encoding */
7543 if (server
.shareobjects
) {
7545 for(j
= 1; j
< argc
; j
++)
7546 argv
[j
] = tryObjectSharing(argv
[j
]);
7548 if (cmd
->flags
& REDIS_CMD_BULK
)
7549 tryObjectEncoding(argv
[argc
-1]);
7550 /* Run the command in the context of a fake client */
7551 fakeClient
->argc
= argc
;
7552 fakeClient
->argv
= argv
;
7553 cmd
->proc(fakeClient
);
7554 /* Discard the reply objects list from the fake client */
7555 while(listLength(fakeClient
->reply
))
7556 listDelNode(fakeClient
->reply
,listFirst(fakeClient
->reply
));
7557 /* Clean up, ready for the next command */
7558 for (j
= 0; j
< argc
; j
++) decrRefCount(argv
[j
]);
7560 /* Handle swapping while loading big datasets when VM is on */
7562 if (server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
7563 while (zmalloc_used_memory() > server
.vm_max_memory
) {
7564 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
7569 freeFakeClient(fakeClient
);
7574 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
7576 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
7580 redisLog(REDIS_WARNING
,"Bad file format reading the append only file");
7584 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
7585 static int fwriteBulkObject(FILE *fp
, robj
*obj
) {
7589 /* Avoid the incr/decr ref count business if possible to help
7590 * copy-on-write (we are often in a child process when this function
7592 * Also makes sure that key objects don't get incrRefCount-ed when VM
7594 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
7595 obj
= getDecodedObject(obj
);
7598 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(long)sdslen(obj
->ptr
));
7599 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) goto err
;
7600 if (sdslen(obj
->ptr
) && fwrite(obj
->ptr
,sdslen(obj
->ptr
),1,fp
) == 0)
7602 if (fwrite("\r\n",2,1,fp
) == 0) goto err
;
7603 if (decrrc
) decrRefCount(obj
);
7606 if (decrrc
) decrRefCount(obj
);
7610 /* Write binary-safe string into a file in the bulkformat
7611 * $<count>\r\n<payload>\r\n */
7612 static int fwriteBulkString(FILE *fp
, char *s
, unsigned long len
) {
7615 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(unsigned long)len
);
7616 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
7617 if (len
&& fwrite(s
,len
,1,fp
) == 0) return 0;
7618 if (fwrite("\r\n",2,1,fp
) == 0) return 0;
7622 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
7623 static int fwriteBulkDouble(FILE *fp
, double d
) {
7624 char buf
[128], dbuf
[128];
7626 snprintf(dbuf
,sizeof(dbuf
),"%.17g\r\n",d
);
7627 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(dbuf
)-2);
7628 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
7629 if (fwrite(dbuf
,strlen(dbuf
),1,fp
) == 0) return 0;
7633 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
7634 static int fwriteBulkLong(FILE *fp
, long l
) {
7635 char buf
[128], lbuf
[128];
7637 snprintf(lbuf
,sizeof(lbuf
),"%ld\r\n",l
);
7638 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(lbuf
)-2);
7639 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
7640 if (fwrite(lbuf
,strlen(lbuf
),1,fp
) == 0) return 0;
7644 /* Write a sequence of commands able to fully rebuild the dataset into
7645 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
7646 static int rewriteAppendOnlyFile(char *filename
) {
7647 dictIterator
*di
= NULL
;
7652 time_t now
= time(NULL
);
7654 /* Note that we have to use a different temp name here compared to the
7655 * one used by rewriteAppendOnlyFileBackground() function. */
7656 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
7657 fp
= fopen(tmpfile
,"w");
7659 redisLog(REDIS_WARNING
, "Failed rewriting the append only file: %s", strerror(errno
));
7662 for (j
= 0; j
< server
.dbnum
; j
++) {
7663 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
7664 redisDb
*db
= server
.db
+j
;
7666 if (dictSize(d
) == 0) continue;
7667 di
= dictGetIterator(d
);
7673 /* SELECT the new DB */
7674 if (fwrite(selectcmd
,sizeof(selectcmd
)-1,1,fp
) == 0) goto werr
;
7675 if (fwriteBulkLong(fp
,j
) == 0) goto werr
;
7677 /* Iterate this DB writing every entry */
7678 while((de
= dictNext(di
)) != NULL
) {
7683 key
= dictGetEntryKey(de
);
7684 /* If the value for this key is swapped, load a preview in memory.
7685 * We use a "swapped" flag to remember if we need to free the
7686 * value object instead to just increment the ref count anyway
7687 * in order to avoid copy-on-write of pages if we are forked() */
7688 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
7689 key
->storage
== REDIS_VM_SWAPPING
) {
7690 o
= dictGetEntryVal(de
);
7693 o
= vmPreviewObject(key
);
7696 expiretime
= getExpire(db
,key
);
7698 /* Save the key and associated value */
7699 if (o
->type
== REDIS_STRING
) {
7700 /* Emit a SET command */
7701 char cmd
[]="*3\r\n$3\r\nSET\r\n";
7702 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7704 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
7705 if (fwriteBulkObject(fp
,o
) == 0) goto werr
;
7706 } else if (o
->type
== REDIS_LIST
) {
7707 /* Emit the RPUSHes needed to rebuild the list */
7708 list
*list
= o
->ptr
;
7712 listRewind(list
,&li
);
7713 while((ln
= listNext(&li
))) {
7714 char cmd
[]="*3\r\n$5\r\nRPUSH\r\n";
7715 robj
*eleobj
= listNodeValue(ln
);
7717 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7718 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
7719 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
7721 } else if (o
->type
== REDIS_SET
) {
7722 /* Emit the SADDs needed to rebuild the set */
7724 dictIterator
*di
= dictGetIterator(set
);
7727 while((de
= dictNext(di
)) != NULL
) {
7728 char cmd
[]="*3\r\n$4\r\nSADD\r\n";
7729 robj
*eleobj
= dictGetEntryKey(de
);
7731 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7732 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
7733 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
7735 dictReleaseIterator(di
);
7736 } else if (o
->type
== REDIS_ZSET
) {
7737 /* Emit the ZADDs needed to rebuild the sorted set */
7739 dictIterator
*di
= dictGetIterator(zs
->dict
);
7742 while((de
= dictNext(di
)) != NULL
) {
7743 char cmd
[]="*4\r\n$4\r\nZADD\r\n";
7744 robj
*eleobj
= dictGetEntryKey(de
);
7745 double *score
= dictGetEntryVal(de
);
7747 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7748 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
7749 if (fwriteBulkDouble(fp
,*score
) == 0) goto werr
;
7750 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
7752 dictReleaseIterator(di
);
7753 } else if (o
->type
== REDIS_HASH
) {
7754 char cmd
[]="*4\r\n$4\r\nHSET\r\n";
7756 /* Emit the HSETs needed to rebuild the hash */
7757 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
7758 unsigned char *p
= zipmapRewind(o
->ptr
);
7759 unsigned char *field
, *val
;
7760 unsigned int flen
, vlen
;
7762 while((p
= zipmapNext(p
,&field
,&flen
,&val
,&vlen
)) != NULL
) {
7763 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7764 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
7765 if (fwriteBulkString(fp
,(char*)field
,flen
) == -1)
7767 if (fwriteBulkString(fp
,(char*)val
,vlen
) == -1)
7771 dictIterator
*di
= dictGetIterator(o
->ptr
);
7774 while((de
= dictNext(di
)) != NULL
) {
7775 robj
*field
= dictGetEntryKey(de
);
7776 robj
*val
= dictGetEntryVal(de
);
7778 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7779 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
7780 if (fwriteBulkObject(fp
,field
) == -1) return -1;
7781 if (fwriteBulkObject(fp
,val
) == -1) return -1;
7783 dictReleaseIterator(di
);
7786 redisAssert(0 != 0);
7788 /* Save the expire time */
7789 if (expiretime
!= -1) {
7790 char cmd
[]="*3\r\n$8\r\nEXPIREAT\r\n";
7791 /* If this key is already expired skip it */
7792 if (expiretime
< now
) continue;
7793 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7794 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
7795 if (fwriteBulkLong(fp
,expiretime
) == 0) goto werr
;
7797 if (swapped
) decrRefCount(o
);
7799 dictReleaseIterator(di
);
7802 /* Make sure data will not remain on the OS's output buffers */
7807 /* Use RENAME to make sure the DB file is changed atomically only
7808 * if the generate DB file is ok. */
7809 if (rename(tmpfile
,filename
) == -1) {
7810 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
7814 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
7820 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
7821 if (di
) dictReleaseIterator(di
);
7825 /* This is how rewriting of the append only file in background works:
7827 * 1) The user calls BGREWRITEAOF
7828 * 2) Redis calls this function, that forks():
7829 * 2a) the child rewrite the append only file in a temp file.
7830 * 2b) the parent accumulates differences in server.bgrewritebuf.
7831 * 3) When the child finished '2a' exists.
7832 * 4) The parent will trap the exit code, if it's OK, will append the
7833 * data accumulated into server.bgrewritebuf into the temp file, and
7834 * finally will rename(2) the temp file in the actual file name.
7835 * The the new file is reopened as the new append only file. Profit!
7837 static int rewriteAppendOnlyFileBackground(void) {
7840 if (server
.bgrewritechildpid
!= -1) return REDIS_ERR
;
7841 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
7842 if ((childpid
= fork()) == 0) {
7846 if (server
.vm_enabled
) vmReopenSwapFile();
7848 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
7849 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
7856 if (childpid
== -1) {
7857 redisLog(REDIS_WARNING
,
7858 "Can't rewrite append only file in background: fork: %s",
7862 redisLog(REDIS_NOTICE
,
7863 "Background append only file rewriting started by pid %d",childpid
);
7864 server
.bgrewritechildpid
= childpid
;
7865 /* We set appendseldb to -1 in order to force the next call to the
7866 * feedAppendOnlyFile() to issue a SELECT command, so the differences
7867 * accumulated by the parent into server.bgrewritebuf will start
7868 * with a SELECT statement and it will be safe to merge. */
7869 server
.appendseldb
= -1;
7872 return REDIS_OK
; /* unreached */
7875 static void bgrewriteaofCommand(redisClient
*c
) {
7876 if (server
.bgrewritechildpid
!= -1) {
7877 addReplySds(c
,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
7880 if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
7881 char *status
= "+Background append only file rewriting started\r\n";
7882 addReplySds(c
,sdsnew(status
));
7884 addReply(c
,shared
.err
);
7888 static void aofRemoveTempFile(pid_t childpid
) {
7891 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
7895 /* Virtual Memory is composed mainly of two subsystems:
7896 * - Blocking Virutal Memory
7897 * - Threaded Virtual Memory I/O
7898 * The two parts are not fully decoupled, but functions are split among two
7899 * different sections of the source code (delimited by comments) in order to
7900 * make more clear what functionality is about the blocking VM and what about
7901 * the threaded (not blocking) VM.
7905 * Redis VM is a blocking VM (one that blocks reading swapped values from
7906 * disk into memory when a value swapped out is needed in memory) that is made
7907 * unblocking by trying to examine the command argument vector in order to
7908 * load in background values that will likely be needed in order to exec
7909 * the command. The command is executed only once all the relevant keys
7910 * are loaded into memory.
7912 * This basically is almost as simple of a blocking VM, but almost as parallel
7913 * as a fully non-blocking VM.
7916 /* =================== Virtual Memory - Blocking Side ====================== */
7918 /* substitute the first occurrence of '%p' with the process pid in the
7919 * swap file name. */
7920 static void expandVmSwapFilename(void) {
7921 char *p
= strstr(server
.vm_swap_file
,"%p");
7927 new = sdscat(new,server
.vm_swap_file
);
7928 new = sdscatprintf(new,"%ld",(long) getpid());
7929 new = sdscat(new,p
+2);
7930 zfree(server
.vm_swap_file
);
7931 server
.vm_swap_file
= new;
7934 static void vmInit(void) {
7939 if (server
.vm_max_threads
!= 0)
7940 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
7942 expandVmSwapFilename();
7943 redisLog(REDIS_NOTICE
,"Using '%s' as swap file",server
.vm_swap_file
);
7944 if ((server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b")) == NULL
) {
7945 server
.vm_fp
= fopen(server
.vm_swap_file
,"w+b");
7947 if (server
.vm_fp
== NULL
) {
7948 redisLog(REDIS_WARNING
,
7949 "Impossible to open the swap file: %s. Exiting.",
7953 server
.vm_fd
= fileno(server
.vm_fp
);
7954 server
.vm_next_page
= 0;
7955 server
.vm_near_pages
= 0;
7956 server
.vm_stats_used_pages
= 0;
7957 server
.vm_stats_swapped_objects
= 0;
7958 server
.vm_stats_swapouts
= 0;
7959 server
.vm_stats_swapins
= 0;
7960 totsize
= server
.vm_pages
*server
.vm_page_size
;
7961 redisLog(REDIS_NOTICE
,"Allocating %lld bytes of swap file",totsize
);
7962 if (ftruncate(server
.vm_fd
,totsize
) == -1) {
7963 redisLog(REDIS_WARNING
,"Can't ftruncate swap file: %s. Exiting.",
7967 redisLog(REDIS_NOTICE
,"Swap file allocated with success");
7969 server
.vm_bitmap
= zmalloc((server
.vm_pages
+7)/8);
7970 redisLog(REDIS_VERBOSE
,"Allocated %lld bytes page table for %lld pages",
7971 (long long) (server
.vm_pages
+7)/8, server
.vm_pages
);
7972 memset(server
.vm_bitmap
,0,(server
.vm_pages
+7)/8);
7974 /* Initialize threaded I/O (used by Virtual Memory) */
7975 server
.io_newjobs
= listCreate();
7976 server
.io_processing
= listCreate();
7977 server
.io_processed
= listCreate();
7978 server
.io_ready_clients
= listCreate();
7979 pthread_mutex_init(&server
.io_mutex
,NULL
);
7980 pthread_mutex_init(&server
.obj_freelist_mutex
,NULL
);
7981 pthread_mutex_init(&server
.io_swapfile_mutex
,NULL
);
7982 server
.io_active_threads
= 0;
7983 if (pipe(pipefds
) == -1) {
7984 redisLog(REDIS_WARNING
,"Unable to intialized VM: pipe(2): %s. Exiting."
7988 server
.io_ready_pipe_read
= pipefds
[0];
7989 server
.io_ready_pipe_write
= pipefds
[1];
7990 redisAssert(anetNonBlock(NULL
,server
.io_ready_pipe_read
) != ANET_ERR
);
7991 /* LZF requires a lot of stack */
7992 pthread_attr_init(&server
.io_threads_attr
);
7993 pthread_attr_getstacksize(&server
.io_threads_attr
, &stacksize
);
7994 while (stacksize
< REDIS_THREAD_STACK_SIZE
) stacksize
*= 2;
7995 pthread_attr_setstacksize(&server
.io_threads_attr
, stacksize
);
7996 /* Listen for events in the threaded I/O pipe */
7997 if (aeCreateFileEvent(server
.el
, server
.io_ready_pipe_read
, AE_READABLE
,
7998 vmThreadedIOCompletedJob
, NULL
) == AE_ERR
)
7999 oom("creating file event");
8002 /* Mark the page as used */
8003 static void vmMarkPageUsed(off_t page
) {
8004 off_t byte
= page
/8;
8006 redisAssert(vmFreePage(page
) == 1);
8007 server
.vm_bitmap
[byte
] |= 1<<bit
;
8010 /* Mark N contiguous pages as used, with 'page' being the first. */
8011 static void vmMarkPagesUsed(off_t page
, off_t count
) {
8014 for (j
= 0; j
< count
; j
++)
8015 vmMarkPageUsed(page
+j
);
8016 server
.vm_stats_used_pages
+= count
;
8017 redisLog(REDIS_DEBUG
,"Mark USED pages: %lld pages at %lld\n",
8018 (long long)count
, (long long)page
);
8021 /* Mark the page as free */
8022 static void vmMarkPageFree(off_t page
) {
8023 off_t byte
= page
/8;
8025 redisAssert(vmFreePage(page
) == 0);
8026 server
.vm_bitmap
[byte
] &= ~(1<<bit
);
8029 /* Mark N contiguous pages as free, with 'page' being the first. */
8030 static void vmMarkPagesFree(off_t page
, off_t count
) {
8033 for (j
= 0; j
< count
; j
++)
8034 vmMarkPageFree(page
+j
);
8035 server
.vm_stats_used_pages
-= count
;
8036 redisLog(REDIS_DEBUG
,"Mark FREE pages: %lld pages at %lld\n",
8037 (long long)count
, (long long)page
);
8040 /* Test if the page is free */
8041 static int vmFreePage(off_t page
) {
8042 off_t byte
= page
/8;
8044 return (server
.vm_bitmap
[byte
] & (1<<bit
)) == 0;
8047 /* Find N contiguous free pages storing the first page of the cluster in *first.
8048 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
8049 * REDIS_ERR is returned.
8051 * This function uses a simple algorithm: we try to allocate
8052 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
8053 * again from the start of the swap file searching for free spaces.
8055 * If it looks pretty clear that there are no free pages near our offset
8056 * we try to find less populated places doing a forward jump of
8057 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
8058 * without hurry, and then we jump again and so forth...
8060 * This function can be improved using a free list to avoid to guess
8061 * too much, since we could collect data about freed pages.
8063 * note: I implemented this function just after watching an episode of
8064 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
8066 static int vmFindContiguousPages(off_t
*first
, off_t n
) {
8067 off_t base
, offset
= 0, since_jump
= 0, numfree
= 0;
8069 if (server
.vm_near_pages
== REDIS_VM_MAX_NEAR_PAGES
) {
8070 server
.vm_near_pages
= 0;
8071 server
.vm_next_page
= 0;
8073 server
.vm_near_pages
++; /* Yet another try for pages near to the old ones */
8074 base
= server
.vm_next_page
;
8076 while(offset
< server
.vm_pages
) {
8077 off_t
this = base
+offset
;
8079 /* If we overflow, restart from page zero */
8080 if (this >= server
.vm_pages
) {
8081 this -= server
.vm_pages
;
8083 /* Just overflowed, what we found on tail is no longer
8084 * interesting, as it's no longer contiguous. */
8088 if (vmFreePage(this)) {
8089 /* This is a free page */
8091 /* Already got N free pages? Return to the caller, with success */
8093 *first
= this-(n
-1);
8094 server
.vm_next_page
= this+1;
8095 redisLog(REDIS_DEBUG
, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n
, (long long) *first
);
8099 /* The current one is not a free page */
8103 /* Fast-forward if the current page is not free and we already
8104 * searched enough near this place. */
8106 if (!numfree
&& since_jump
>= REDIS_VM_MAX_RANDOM_JUMP
/4) {
8107 offset
+= random() % REDIS_VM_MAX_RANDOM_JUMP
;
8109 /* Note that even if we rewind after the jump, we are don't need
8110 * to make sure numfree is set to zero as we only jump *if* it
8111 * is set to zero. */
8113 /* Otherwise just check the next page */
8120 /* Write the specified object at the specified page of the swap file */
8121 static int vmWriteObjectOnSwap(robj
*o
, off_t page
) {
8122 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
8123 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
8124 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
8125 redisLog(REDIS_WARNING
,
8126 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
8130 rdbSaveObject(server
.vm_fp
,o
);
8131 fflush(server
.vm_fp
);
8132 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
8136 /* Swap the 'val' object relative to 'key' into disk. Store all the information
8137 * needed to later retrieve the object into the key object.
8138 * If we can't find enough contiguous empty pages to swap the object on disk
8139 * REDIS_ERR is returned. */
8140 static int vmSwapObjectBlocking(robj
*key
, robj
*val
) {
8141 off_t pages
= rdbSavedObjectPages(val
,NULL
);
8144 assert(key
->storage
== REDIS_VM_MEMORY
);
8145 assert(key
->refcount
== 1);
8146 if (vmFindContiguousPages(&page
,pages
) == REDIS_ERR
) return REDIS_ERR
;
8147 if (vmWriteObjectOnSwap(val
,page
) == REDIS_ERR
) return REDIS_ERR
;
8148 key
->vm
.page
= page
;
8149 key
->vm
.usedpages
= pages
;
8150 key
->storage
= REDIS_VM_SWAPPED
;
8151 key
->vtype
= val
->type
;
8152 decrRefCount(val
); /* Deallocate the object from memory. */
8153 vmMarkPagesUsed(page
,pages
);
8154 redisLog(REDIS_DEBUG
,"VM: object %s swapped out at %lld (%lld pages)",
8155 (unsigned char*) key
->ptr
,
8156 (unsigned long long) page
, (unsigned long long) pages
);
8157 server
.vm_stats_swapped_objects
++;
8158 server
.vm_stats_swapouts
++;
8162 static robj
*vmReadObjectFromSwap(off_t page
, int type
) {
8165 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
8166 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
8167 redisLog(REDIS_WARNING
,
8168 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
8172 o
= rdbLoadObject(type
,server
.vm_fp
);
8174 redisLog(REDIS_WARNING
, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno
));
8177 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
8181 /* Load the value object relative to the 'key' object from swap to memory.
8182 * The newly allocated object is returned.
8184 * If preview is true the unserialized object is returned to the caller but
8185 * no changes are made to the key object, nor the pages are marked as freed */
8186 static robj
*vmGenericLoadObject(robj
*key
, int preview
) {
8189 redisAssert(key
->storage
== REDIS_VM_SWAPPED
|| key
->storage
== REDIS_VM_LOADING
);
8190 val
= vmReadObjectFromSwap(key
->vm
.page
,key
->vtype
);
8192 key
->storage
= REDIS_VM_MEMORY
;
8193 key
->vm
.atime
= server
.unixtime
;
8194 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
8195 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk",
8196 (unsigned char*) key
->ptr
);
8197 server
.vm_stats_swapped_objects
--;
8199 redisLog(REDIS_DEBUG
, "VM: object %s previewed from disk",
8200 (unsigned char*) key
->ptr
);
8202 server
.vm_stats_swapins
++;
8206 /* Plain object loading, from swap to memory */
8207 static robj
*vmLoadObject(robj
*key
) {
8208 /* If we are loading the object in background, stop it, we
8209 * need to load this object synchronously ASAP. */
8210 if (key
->storage
== REDIS_VM_LOADING
)
8211 vmCancelThreadedIOJob(key
);
8212 return vmGenericLoadObject(key
,0);
8215 /* Just load the value on disk, without to modify the key.
8216 * This is useful when we want to perform some operation on the value
8217 * without to really bring it from swap to memory, like while saving the
8218 * dataset or rewriting the append only log. */
8219 static robj
*vmPreviewObject(robj
*key
) {
8220 return vmGenericLoadObject(key
,1);
8223 /* How a good candidate is this object for swapping?
8224 * The better candidate it is, the greater the returned value.
8226 * Currently we try to perform a fast estimation of the object size in
8227 * memory, and combine it with aging informations.
8229 * Basically swappability = idle-time * log(estimated size)
8231 * Bigger objects are preferred over smaller objects, but not
8232 * proportionally, this is why we use the logarithm. This algorithm is
8233 * just a first try and will probably be tuned later. */
8234 static double computeObjectSwappability(robj
*o
) {
8235 time_t age
= server
.unixtime
- o
->vm
.atime
;
8239 struct dictEntry
*de
;
8242 if (age
<= 0) return 0;
8245 if (o
->encoding
!= REDIS_ENCODING_RAW
) {
8248 asize
= sdslen(o
->ptr
)+sizeof(*o
)+sizeof(long)*2;
8253 listNode
*ln
= listFirst(l
);
8255 asize
= sizeof(list
);
8257 robj
*ele
= ln
->value
;
8260 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
8261 (sizeof(*o
)+sdslen(ele
->ptr
)) :
8263 asize
+= (sizeof(listNode
)+elesize
)*listLength(l
);
8268 z
= (o
->type
== REDIS_ZSET
);
8269 d
= z
? ((zset
*)o
->ptr
)->dict
: o
->ptr
;
8271 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
8272 if (z
) asize
+= sizeof(zset
)-sizeof(dict
);
8277 de
= dictGetRandomKey(d
);
8278 ele
= dictGetEntryKey(de
);
8279 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
8280 (sizeof(*o
)+sdslen(ele
->ptr
)) :
8282 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
8283 if (z
) asize
+= sizeof(zskiplistNode
)*dictSize(d
);
8287 return (double)age
*log(1+asize
);
8290 /* Try to swap an object that's a good candidate for swapping.
8291 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
8292 * to swap any object at all.
8294 * If 'usethreaded' is true, Redis will try to swap the object in background
8295 * using I/O threads. */
8296 static int vmSwapOneObject(int usethreads
) {
8298 struct dictEntry
*best
= NULL
;
8299 double best_swappability
= 0;
8300 redisDb
*best_db
= NULL
;
8303 for (j
= 0; j
< server
.dbnum
; j
++) {
8304 redisDb
*db
= server
.db
+j
;
8305 /* Why maxtries is set to 100?
8306 * Because this way (usually) we'll find 1 object even if just 1% - 2%
8307 * are swappable objects */
8310 if (dictSize(db
->dict
) == 0) continue;
8311 for (i
= 0; i
< 5; i
++) {
8313 double swappability
;
8315 if (maxtries
) maxtries
--;
8316 de
= dictGetRandomKey(db
->dict
);
8317 key
= dictGetEntryKey(de
);
8318 val
= dictGetEntryVal(de
);
8319 /* Only swap objects that are currently in memory.
8321 * Also don't swap shared objects if threaded VM is on, as we
8322 * try to ensure that the main thread does not touch the
8323 * object while the I/O thread is using it, but we can't
8324 * control other keys without adding additional mutex. */
8325 if (key
->storage
!= REDIS_VM_MEMORY
||
8326 (server
.vm_max_threads
!= 0 && val
->refcount
!= 1)) {
8327 if (maxtries
) i
--; /* don't count this try */
8330 swappability
= computeObjectSwappability(val
);
8331 if (!best
|| swappability
> best_swappability
) {
8333 best_swappability
= swappability
;
8338 if (best
== NULL
) return REDIS_ERR
;
8339 key
= dictGetEntryKey(best
);
8340 val
= dictGetEntryVal(best
);
8342 redisLog(REDIS_DEBUG
,"Key with best swappability: %s, %f",
8343 key
->ptr
, best_swappability
);
8345 /* Unshare the key if needed */
8346 if (key
->refcount
> 1) {
8347 robj
*newkey
= dupStringObject(key
);
8349 key
= dictGetEntryKey(best
) = newkey
;
8353 vmSwapObjectThreaded(key
,val
,best_db
);
8356 if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
8357 dictGetEntryVal(best
) = NULL
;
8365 static int vmSwapOneObjectBlocking() {
8366 return vmSwapOneObject(0);
8369 static int vmSwapOneObjectThreaded() {
8370 return vmSwapOneObject(1);
8373 /* Return true if it's safe to swap out objects in a given moment.
8374 * Basically we don't want to swap objects out while there is a BGSAVE
8375 * or a BGAEOREWRITE running in backgroud. */
8376 static int vmCanSwapOut(void) {
8377 return (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1);
8380 /* Delete a key if swapped. Returns 1 if the key was found, was swapped
8381 * and was deleted. Otherwise 0 is returned. */
8382 static int deleteIfSwapped(redisDb
*db
, robj
*key
) {
8386 if ((de
= dictFind(db
->dict
,key
)) == NULL
) return 0;
8387 foundkey
= dictGetEntryKey(de
);
8388 if (foundkey
->storage
== REDIS_VM_MEMORY
) return 0;
8393 /* =================== Virtual Memory - Threaded I/O ======================= */
8395 static void freeIOJob(iojob
*j
) {
8396 if ((j
->type
== REDIS_IOJOB_PREPARE_SWAP
||
8397 j
->type
== REDIS_IOJOB_DO_SWAP
||
8398 j
->type
== REDIS_IOJOB_LOAD
) && j
->val
!= NULL
)
8399 decrRefCount(j
->val
);
8400 decrRefCount(j
->key
);
8404 /* Every time a thread finished a Job, it writes a byte into the write side
8405 * of an unix pipe in order to "awake" the main thread, and this function
8407 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
,
8411 int retval
, processed
= 0, toprocess
= -1, trytoswap
= 1;
8413 REDIS_NOTUSED(mask
);
8414 REDIS_NOTUSED(privdata
);
8416 /* For every byte we read in the read side of the pipe, there is one
8417 * I/O job completed to process. */
8418 while((retval
= read(fd
,buf
,1)) == 1) {
8422 struct dictEntry
*de
;
8424 redisLog(REDIS_DEBUG
,"Processing I/O completed job");
8426 /* Get the processed element (the oldest one) */
8428 assert(listLength(server
.io_processed
) != 0);
8429 if (toprocess
== -1) {
8430 toprocess
= (listLength(server
.io_processed
)*REDIS_MAX_COMPLETED_JOBS_PROCESSED
)/100;
8431 if (toprocess
<= 0) toprocess
= 1;
8433 ln
= listFirst(server
.io_processed
);
8435 listDelNode(server
.io_processed
,ln
);
8437 /* If this job is marked as canceled, just ignore it */
8442 /* Post process it in the main thread, as there are things we
8443 * can do just here to avoid race conditions and/or invasive locks */
8444 redisLog(REDIS_DEBUG
,"Job %p type: %d, key at %p (%s) refcount: %d\n", (void*) j
, j
->type
, (void*)j
->key
, (char*)j
->key
->ptr
, j
->key
->refcount
);
8445 de
= dictFind(j
->db
->dict
,j
->key
);
8447 key
= dictGetEntryKey(de
);
8448 if (j
->type
== REDIS_IOJOB_LOAD
) {
8451 /* Key loaded, bring it at home */
8452 key
->storage
= REDIS_VM_MEMORY
;
8453 key
->vm
.atime
= server
.unixtime
;
8454 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
8455 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk (threaded)",
8456 (unsigned char*) key
->ptr
);
8457 server
.vm_stats_swapped_objects
--;
8458 server
.vm_stats_swapins
++;
8459 dictGetEntryVal(de
) = j
->val
;
8460 incrRefCount(j
->val
);
8463 /* Handle clients waiting for this key to be loaded. */
8464 handleClientsBlockedOnSwappedKey(db
,key
);
8465 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
8466 /* Now we know the amount of pages required to swap this object.
8467 * Let's find some space for it, and queue this task again
8468 * rebranded as REDIS_IOJOB_DO_SWAP. */
8469 if (!vmCanSwapOut() ||
8470 vmFindContiguousPages(&j
->page
,j
->pages
) == REDIS_ERR
)
8472 /* Ooops... no space or we can't swap as there is
8473 * a fork()ed Redis trying to save stuff on disk. */
8475 key
->storage
= REDIS_VM_MEMORY
; /* undo operation */
8477 /* Note that we need to mark this pages as used now,
8478 * if the job will be canceled, we'll mark them as freed
8480 vmMarkPagesUsed(j
->page
,j
->pages
);
8481 j
->type
= REDIS_IOJOB_DO_SWAP
;
8486 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
8489 /* Key swapped. We can finally free some memory. */
8490 if (key
->storage
!= REDIS_VM_SWAPPING
) {
8491 printf("key->storage: %d\n",key
->storage
);
8492 printf("key->name: %s\n",(char*)key
->ptr
);
8493 printf("key->refcount: %d\n",key
->refcount
);
8494 printf("val: %p\n",(void*)j
->val
);
8495 printf("val->type: %d\n",j
->val
->type
);
8496 printf("val->ptr: %s\n",(char*)j
->val
->ptr
);
8498 redisAssert(key
->storage
== REDIS_VM_SWAPPING
);
8499 val
= dictGetEntryVal(de
);
8500 key
->vm
.page
= j
->page
;
8501 key
->vm
.usedpages
= j
->pages
;
8502 key
->storage
= REDIS_VM_SWAPPED
;
8503 key
->vtype
= j
->val
->type
;
8504 decrRefCount(val
); /* Deallocate the object from memory. */
8505 dictGetEntryVal(de
) = NULL
;
8506 redisLog(REDIS_DEBUG
,
8507 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
8508 (unsigned char*) key
->ptr
,
8509 (unsigned long long) j
->page
, (unsigned long long) j
->pages
);
8510 server
.vm_stats_swapped_objects
++;
8511 server
.vm_stats_swapouts
++;
8513 /* Put a few more swap requests in queue if we are still
8515 if (trytoswap
&& vmCanSwapOut() &&
8516 zmalloc_used_memory() > server
.vm_max_memory
)
8521 more
= listLength(server
.io_newjobs
) <
8522 (unsigned) server
.vm_max_threads
;
8524 /* Don't waste CPU time if swappable objects are rare. */
8525 if (vmSwapOneObjectThreaded() == REDIS_ERR
) {
8533 if (processed
== toprocess
) return;
8535 if (retval
< 0 && errno
!= EAGAIN
) {
8536 redisLog(REDIS_WARNING
,
8537 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
8542 static void lockThreadedIO(void) {
8543 pthread_mutex_lock(&server
.io_mutex
);
8546 static void unlockThreadedIO(void) {
8547 pthread_mutex_unlock(&server
.io_mutex
);
8550 /* Remove the specified object from the threaded I/O queue if still not
8551 * processed, otherwise make sure to flag it as canceled. */
8552 static void vmCancelThreadedIOJob(robj
*o
) {
8554 server
.io_newjobs
, /* 0 */
8555 server
.io_processing
, /* 1 */
8556 server
.io_processed
/* 2 */
8560 assert(o
->storage
== REDIS_VM_LOADING
|| o
->storage
== REDIS_VM_SWAPPING
);
8563 /* Search for a matching key in one of the queues */
8564 for (i
= 0; i
< 3; i
++) {
8568 listRewind(lists
[i
],&li
);
8569 while ((ln
= listNext(&li
)) != NULL
) {
8570 iojob
*job
= ln
->value
;
8572 if (job
->canceled
) continue; /* Skip this, already canceled. */
8573 if (compareStringObjects(job
->key
,o
) == 0) {
8574 redisLog(REDIS_DEBUG
,"*** CANCELED %p (%s) (type %d) (LIST ID %d)\n",
8575 (void*)job
, (char*)o
->ptr
, job
->type
, i
);
8576 /* Mark the pages as free since the swap didn't happened
8577 * or happened but is now discarded. */
8578 if (i
!= 1 && job
->type
== REDIS_IOJOB_DO_SWAP
)
8579 vmMarkPagesFree(job
->page
,job
->pages
);
8580 /* Cancel the job. It depends on the list the job is
8583 case 0: /* io_newjobs */
8584 /* If the job was yet not processed the best thing to do
8585 * is to remove it from the queue at all */
8587 listDelNode(lists
[i
],ln
);
8589 case 1: /* io_processing */
8590 /* Oh Shi- the thread is messing with the Job:
8592 * Probably it's accessing the object if this is a
8593 * PREPARE_SWAP or DO_SWAP job.
8594 * If it's a LOAD job it may be reading from disk and
8595 * if we don't wait for the job to terminate before to
8596 * cancel it, maybe in a few microseconds data can be
8597 * corrupted in this pages. So the short story is:
8599 * Better to wait for the job to move into the
8600 * next queue (processed)... */
8602 /* We try again and again until the job is completed. */
8604 /* But let's wait some time for the I/O thread
8605 * to finish with this job. After all this condition
8606 * should be very rare. */
8609 case 2: /* io_processed */
8610 /* The job was already processed, that's easy...
8611 * just mark it as canceled so that we'll ignore it
8612 * when processing completed jobs. */
8616 /* Finally we have to adjust the storage type of the object
8617 * in order to "UNDO" the operaiton. */
8618 if (o
->storage
== REDIS_VM_LOADING
)
8619 o
->storage
= REDIS_VM_SWAPPED
;
8620 else if (o
->storage
== REDIS_VM_SWAPPING
)
8621 o
->storage
= REDIS_VM_MEMORY
;
8628 assert(1 != 1); /* We should never reach this */
8631 static void *IOThreadEntryPoint(void *arg
) {
8636 pthread_detach(pthread_self());
8638 /* Get a new job to process */
8640 if (listLength(server
.io_newjobs
) == 0) {
8641 /* No new jobs in queue, exit. */
8642 redisLog(REDIS_DEBUG
,"Thread %ld exiting, nothing to do",
8643 (long) pthread_self());
8644 server
.io_active_threads
--;
8648 ln
= listFirst(server
.io_newjobs
);
8650 listDelNode(server
.io_newjobs
,ln
);
8651 /* Add the job in the processing queue */
8652 j
->thread
= pthread_self();
8653 listAddNodeTail(server
.io_processing
,j
);
8654 ln
= listLast(server
.io_processing
); /* We use ln later to remove it */
8656 redisLog(REDIS_DEBUG
,"Thread %ld got a new job (type %d): %p about key '%s'",
8657 (long) pthread_self(), j
->type
, (void*)j
, (char*)j
->key
->ptr
);
8659 /* Process the Job */
8660 if (j
->type
== REDIS_IOJOB_LOAD
) {
8661 j
->val
= vmReadObjectFromSwap(j
->page
,j
->key
->vtype
);
8662 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
8663 FILE *fp
= fopen("/dev/null","w+");
8664 j
->pages
= rdbSavedObjectPages(j
->val
,fp
);
8666 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
8667 if (vmWriteObjectOnSwap(j
->val
,j
->page
) == REDIS_ERR
)
8671 /* Done: insert the job into the processed queue */
8672 redisLog(REDIS_DEBUG
,"Thread %ld completed the job: %p (key %s)",
8673 (long) pthread_self(), (void*)j
, (char*)j
->key
->ptr
);
8675 listDelNode(server
.io_processing
,ln
);
8676 listAddNodeTail(server
.io_processed
,j
);
8679 /* Signal the main thread there is new stuff to process */
8680 assert(write(server
.io_ready_pipe_write
,"x",1) == 1);
8682 return NULL
; /* never reached */
8685 static void spawnIOThread(void) {
8687 sigset_t mask
, omask
;
8690 sigaddset(&mask
,SIGCHLD
);
8691 sigaddset(&mask
,SIGHUP
);
8692 sigaddset(&mask
,SIGPIPE
);
8693 pthread_sigmask(SIG_SETMASK
, &mask
, &omask
);
8694 pthread_create(&thread
,&server
.io_threads_attr
,IOThreadEntryPoint
,NULL
);
8695 pthread_sigmask(SIG_SETMASK
, &omask
, NULL
);
8696 server
.io_active_threads
++;
8699 /* We need to wait for the last thread to exit before we are able to
8700 * fork() in order to BGSAVE or BGREWRITEAOF. */
8701 static void waitEmptyIOJobsQueue(void) {
8703 int io_processed_len
;
8706 if (listLength(server
.io_newjobs
) == 0 &&
8707 listLength(server
.io_processing
) == 0 &&
8708 server
.io_active_threads
== 0)
8713 /* While waiting for empty jobs queue condition we post-process some
8714 * finshed job, as I/O threads may be hanging trying to write against
8715 * the io_ready_pipe_write FD but there are so much pending jobs that
8717 io_processed_len
= listLength(server
.io_processed
);
8719 if (io_processed_len
) {
8720 vmThreadedIOCompletedJob(NULL
,server
.io_ready_pipe_read
,NULL
,0);
8721 usleep(1000); /* 1 millisecond */
8723 usleep(10000); /* 10 milliseconds */
8728 static void vmReopenSwapFile(void) {
8729 /* Note: we don't close the old one as we are in the child process
8730 * and don't want to mess at all with the original file object. */
8731 server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b");
8732 if (server
.vm_fp
== NULL
) {
8733 redisLog(REDIS_WARNING
,"Can't re-open the VM swap file: %s. Exiting.",
8734 server
.vm_swap_file
);
8737 server
.vm_fd
= fileno(server
.vm_fp
);
8740 /* This function must be called while with threaded IO locked */
8741 static void queueIOJob(iojob
*j
) {
8742 redisLog(REDIS_DEBUG
,"Queued IO Job %p type %d about key '%s'\n",
8743 (void*)j
, j
->type
, (char*)j
->key
->ptr
);
8744 listAddNodeTail(server
.io_newjobs
,j
);
8745 if (server
.io_active_threads
< server
.vm_max_threads
)
8749 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
) {
8752 assert(key
->storage
== REDIS_VM_MEMORY
);
8753 assert(key
->refcount
== 1);
8755 j
= zmalloc(sizeof(*j
));
8756 j
->type
= REDIS_IOJOB_PREPARE_SWAP
;
8758 j
->key
= dupStringObject(key
);
8762 j
->thread
= (pthread_t
) -1;
8763 key
->storage
= REDIS_VM_SWAPPING
;
8771 /* ============ Virtual Memory - Blocking clients on missing keys =========== */
8773 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
8774 * If there is not already a job loading the key, it is craeted.
8775 * The key is added to the io_keys list in the client structure, and also
8776 * in the hash table mapping swapped keys to waiting clients, that is,
8777 * server.io_waited_keys. */
8778 static int waitForSwappedKey(redisClient
*c
, robj
*key
) {
8779 struct dictEntry
*de
;
8783 /* If the key does not exist or is already in RAM we don't need to
8784 * block the client at all. */
8785 de
= dictFind(c
->db
->dict
,key
);
8786 if (de
== NULL
) return 0;
8787 o
= dictGetEntryKey(de
);
8788 if (o
->storage
== REDIS_VM_MEMORY
) {
8790 } else if (o
->storage
== REDIS_VM_SWAPPING
) {
8791 /* We were swapping the key, undo it! */
8792 vmCancelThreadedIOJob(o
);
8796 /* OK: the key is either swapped, or being loaded just now. */
8798 /* Add the key to the list of keys this client is waiting for.
8799 * This maps clients to keys they are waiting for. */
8800 listAddNodeTail(c
->io_keys
,key
);
8803 /* Add the client to the swapped keys => clients waiting map. */
8804 de
= dictFind(c
->db
->io_keys
,key
);
8808 /* For every key we take a list of clients blocked for it */
8810 retval
= dictAdd(c
->db
->io_keys
,key
,l
);
8812 assert(retval
== DICT_OK
);
8814 l
= dictGetEntryVal(de
);
8816 listAddNodeTail(l
,c
);
8818 /* Are we already loading the key from disk? If not create a job */
8819 if (o
->storage
== REDIS_VM_SWAPPED
) {
8822 o
->storage
= REDIS_VM_LOADING
;
8823 j
= zmalloc(sizeof(*j
));
8824 j
->type
= REDIS_IOJOB_LOAD
;
8826 j
->key
= dupStringObject(key
);
8827 j
->key
->vtype
= o
->vtype
;
8828 j
->page
= o
->vm
.page
;
8831 j
->thread
= (pthread_t
) -1;
8839 /* Is this client attempting to run a command against swapped keys?
8840 * If so, block it ASAP, load the keys in background, then resume it.
8842 * The important idea about this function is that it can fail! If keys will
8843 * still be swapped when the client is resumed, this key lookups will
8844 * just block loading keys from disk. In practical terms this should only
8845 * happen with SORT BY command or if there is a bug in this function.
8847 * Return 1 if the client is marked as blocked, 0 if the client can
8848 * continue as the keys it is going to access appear to be in memory. */
8849 static int blockClientOnSwappedKeys(struct redisCommand
*cmd
, redisClient
*c
) {
8852 if (cmd
->vm_firstkey
== 0) return 0;
8853 last
= cmd
->vm_lastkey
;
8854 if (last
< 0) last
= c
->argc
+last
;
8855 for (j
= cmd
->vm_firstkey
; j
<= last
; j
+= cmd
->vm_keystep
)
8856 waitForSwappedKey(c
,c
->argv
[j
]);
8857 /* If the client was blocked for at least one key, mark it as blocked. */
8858 if (listLength(c
->io_keys
)) {
8859 c
->flags
|= REDIS_IO_WAIT
;
8860 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
8861 server
.vm_blocked_clients
++;
8868 /* Remove the 'key' from the list of blocked keys for a given client.
8870 * The function returns 1 when there are no longer blocking keys after
8871 * the current one was removed (and the client can be unblocked). */
8872 static int dontWaitForSwappedKey(redisClient
*c
, robj
*key
) {
8876 struct dictEntry
*de
;
8878 /* Remove the key from the list of keys this client is waiting for. */
8879 listRewind(c
->io_keys
,&li
);
8880 while ((ln
= listNext(&li
)) != NULL
) {
8881 if (compareStringObjects(ln
->value
,key
) == 0) {
8882 listDelNode(c
->io_keys
,ln
);
8888 /* Remove the client form the key => waiting clients map. */
8889 de
= dictFind(c
->db
->io_keys
,key
);
8891 l
= dictGetEntryVal(de
);
8892 ln
= listSearchKey(l
,c
);
8895 if (listLength(l
) == 0)
8896 dictDelete(c
->db
->io_keys
,key
);
8898 return listLength(c
->io_keys
) == 0;
8901 static void handleClientsBlockedOnSwappedKey(redisDb
*db
, robj
*key
) {
8902 struct dictEntry
*de
;
8907 de
= dictFind(db
->io_keys
,key
);
8910 l
= dictGetEntryVal(de
);
8911 len
= listLength(l
);
8912 /* Note: we can't use something like while(listLength(l)) as the list
8913 * can be freed by the calling function when we remove the last element. */
8916 redisClient
*c
= ln
->value
;
8918 if (dontWaitForSwappedKey(c
,key
)) {
8919 /* Put the client in the list of clients ready to go as we
8920 * loaded all the keys about it. */
8921 listAddNodeTail(server
.io_ready_clients
,c
);
8926 /* ================================= Debugging ============================== */
8928 static void debugCommand(redisClient
*c
) {
8929 if (!strcasecmp(c
->argv
[1]->ptr
,"segfault")) {
8931 } else if (!strcasecmp(c
->argv
[1]->ptr
,"reload")) {
8932 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
8933 addReply(c
,shared
.err
);
8937 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
8938 addReply(c
,shared
.err
);
8941 redisLog(REDIS_WARNING
,"DB reloaded by DEBUG RELOAD");
8942 addReply(c
,shared
.ok
);
8943 } else if (!strcasecmp(c
->argv
[1]->ptr
,"loadaof")) {
8945 if (loadAppendOnlyFile(server
.appendfilename
) != REDIS_OK
) {
8946 addReply(c
,shared
.err
);
8949 redisLog(REDIS_WARNING
,"Append Only File loaded by DEBUG LOADAOF");
8950 addReply(c
,shared
.ok
);
8951 } else if (!strcasecmp(c
->argv
[1]->ptr
,"object") && c
->argc
== 3) {
8952 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
8956 addReply(c
,shared
.nokeyerr
);
8959 key
= dictGetEntryKey(de
);
8960 val
= dictGetEntryVal(de
);
8961 if (!server
.vm_enabled
|| (key
->storage
== REDIS_VM_MEMORY
||
8962 key
->storage
== REDIS_VM_SWAPPING
)) {
8966 if (val
->encoding
< (sizeof(strencoding
)/sizeof(char*))) {
8967 strenc
= strencoding
[val
->encoding
];
8969 snprintf(buf
,64,"unknown encoding %d\n", val
->encoding
);
8972 addReplySds(c
,sdscatprintf(sdsempty(),
8973 "+Key at:%p refcount:%d, value at:%p refcount:%d "
8974 "encoding:%s serializedlength:%lld\r\n",
8975 (void*)key
, key
->refcount
, (void*)val
, val
->refcount
,
8976 strenc
, (long long) rdbSavedObjectLen(val
,NULL
)));
8978 addReplySds(c
,sdscatprintf(sdsempty(),
8979 "+Key at:%p refcount:%d, value swapped at: page %llu "
8980 "using %llu pages\r\n",
8981 (void*)key
, key
->refcount
, (unsigned long long) key
->vm
.page
,
8982 (unsigned long long) key
->vm
.usedpages
));
8984 } else if (!strcasecmp(c
->argv
[1]->ptr
,"swapout") && c
->argc
== 3) {
8985 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
8988 if (!server
.vm_enabled
) {
8989 addReplySds(c
,sdsnew("-ERR Virtual Memory is disabled\r\n"));
8993 addReply(c
,shared
.nokeyerr
);
8996 key
= dictGetEntryKey(de
);
8997 val
= dictGetEntryVal(de
);
8998 /* If the key is shared we want to create a copy */
8999 if (key
->refcount
> 1) {
9000 robj
*newkey
= dupStringObject(key
);
9002 key
= dictGetEntryKey(de
) = newkey
;
9005 if (key
->storage
!= REDIS_VM_MEMORY
) {
9006 addReplySds(c
,sdsnew("-ERR This key is not in memory\r\n"));
9007 } else if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
9008 dictGetEntryVal(de
) = NULL
;
9009 addReply(c
,shared
.ok
);
9011 addReply(c
,shared
.err
);
9014 addReplySds(c
,sdsnew(
9015 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPOUT <key>|RELOAD]\r\n"));
9019 static void _redisAssert(char *estr
, char *file
, int line
) {
9020 redisLog(REDIS_WARNING
,"=== ASSERTION FAILED ===");
9021 redisLog(REDIS_WARNING
,"==> %s:%d '%s' is not true\n",file
,line
,estr
);
9022 #ifdef HAVE_BACKTRACE
9023 redisLog(REDIS_WARNING
,"(forcing SIGSEGV in order to print the stack trace)");
9028 /* =================================== Main! ================================ */
9031 int linuxOvercommitMemoryValue(void) {
9032 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
9036 if (fgets(buf
,64,fp
) == NULL
) {
9045 void linuxOvercommitMemoryWarning(void) {
9046 if (linuxOvercommitMemoryValue() == 0) {
9047 redisLog(REDIS_WARNING
,"WARNING overcommit_memory is set to 0! Background save may fail under low condition memory. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.");
9050 #endif /* __linux__ */
9052 static void daemonize(void) {
9056 if (fork() != 0) exit(0); /* parent exits */
9057 setsid(); /* create a new session */
9059 /* Every output goes to /dev/null. If Redis is daemonized but
9060 * the 'logfile' is set to 'stdout' in the configuration file
9061 * it will not log at all. */
9062 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
9063 dup2(fd
, STDIN_FILENO
);
9064 dup2(fd
, STDOUT_FILENO
);
9065 dup2(fd
, STDERR_FILENO
);
9066 if (fd
> STDERR_FILENO
) close(fd
);
9068 /* Try to write the pid file */
9069 fp
= fopen(server
.pidfile
,"w");
9071 fprintf(fp
,"%d\n",getpid());
9076 int main(int argc
, char **argv
) {
9081 resetServerSaveParams();
9082 loadServerConfig(argv
[1]);
9083 } else if (argc
> 2) {
9084 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
9087 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'");
9089 if (server
.daemonize
) daemonize();
9091 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
9093 linuxOvercommitMemoryWarning();
9096 if (server
.appendonly
) {
9097 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
9098 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %ld seconds",time(NULL
)-start
);
9100 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
9101 redisLog(REDIS_NOTICE
,"DB loaded from disk: %ld seconds",time(NULL
)-start
);
9103 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
9104 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
9106 aeDeleteEventLoop(server
.el
);
9110 /* ============================= Backtrace support ========================= */
9112 #ifdef HAVE_BACKTRACE
9113 static char *findFuncName(void *pointer
, unsigned long *offset
);
9115 static void *getMcontextEip(ucontext_t
*uc
) {
9116 #if defined(__FreeBSD__)
9117 return (void*) uc
->uc_mcontext
.mc_eip
;
9118 #elif defined(__dietlibc__)
9119 return (void*) uc
->uc_mcontext
.eip
;
9120 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
9122 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
9124 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
9126 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
9127 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
9128 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
9130 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
9132 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
9133 return (void*) uc
->uc_mcontext
.gregs
[REG_EIP
]; /* Linux 32/64 bit */
9134 #elif defined(__ia64__) /* Linux IA64 */
9135 return (void*) uc
->uc_mcontext
.sc_ip
;
9141 static void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
9143 char **messages
= NULL
;
9144 int i
, trace_size
= 0;
9145 unsigned long offset
=0;
9146 ucontext_t
*uc
= (ucontext_t
*) secret
;
9148 REDIS_NOTUSED(info
);
9150 redisLog(REDIS_WARNING
,
9151 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
9152 infostring
= genRedisInfoString();
9153 redisLog(REDIS_WARNING
, "%s",infostring
);
9154 /* It's not safe to sdsfree() the returned string under memory
9155 * corruption conditions. Let it leak as we are going to abort */
9157 trace_size
= backtrace(trace
, 100);
9158 /* overwrite sigaction with caller's address */
9159 if (getMcontextEip(uc
) != NULL
) {
9160 trace
[1] = getMcontextEip(uc
);
9162 messages
= backtrace_symbols(trace
, trace_size
);
9164 for (i
=1; i
<trace_size
; ++i
) {
9165 char *fn
= findFuncName(trace
[i
], &offset
), *p
;
9167 p
= strchr(messages
[i
],'+');
9168 if (!fn
|| (p
&& ((unsigned long)strtol(p
+1,NULL
,10)) < offset
)) {
9169 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
9171 redisLog(REDIS_WARNING
,"%d redis-server %p %s + %d", i
, trace
[i
], fn
, (unsigned int)offset
);
9174 /* free(messages); Don't call free() with possibly corrupted memory. */
9178 static void setupSigSegvAction(void) {
9179 struct sigaction act
;
9181 sigemptyset (&act
.sa_mask
);
9182 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
9183 * is used. Otherwise, sa_handler is used */
9184 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
9185 act
.sa_sigaction
= segvHandler
;
9186 sigaction (SIGSEGV
, &act
, NULL
);
9187 sigaction (SIGBUS
, &act
, NULL
);
9188 sigaction (SIGFPE
, &act
, NULL
);
9189 sigaction (SIGILL
, &act
, NULL
);
9190 sigaction (SIGBUS
, &act
, NULL
);
9194 #include "staticsymbols.h"
9195 /* This function try to convert a pointer into a function name. It's used in
9196 * oreder to provide a backtrace under segmentation fault that's able to
9197 * display functions declared as static (otherwise the backtrace is useless). */
9198 static char *findFuncName(void *pointer
, unsigned long *offset
){
9200 unsigned long off
, minoff
= 0;
9202 /* Try to match against the Symbol with the smallest offset */
9203 for (i
=0; symsTable
[i
].pointer
; i
++) {
9204 unsigned long lp
= (unsigned long) pointer
;
9206 if (lp
!= (unsigned long)-1 && lp
>= symsTable
[i
].pointer
) {
9207 off
=lp
-symsTable
[i
].pointer
;
9208 if (ret
< 0 || off
< minoff
) {
9214 if (ret
== -1) return NULL
;
9216 return symsTable
[ret
].name
;
9218 #else /* HAVE_BACKTRACE */
9219 static void setupSigSegvAction(void) {
9221 #endif /* HAVE_BACKTRACE */