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_BULK
,1,1,1},
745 {"zrevrank",zrevrankCommand
,3,REDIS_CMD_BULK
,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 /* We want to convert the zipmap into an hash table right now if the
5936 * entry to be added is too big. Note that we check if the object
5937 * is integer encoded before to try fetching the length in the test below.
5938 * This is because integers are small, but currently stringObjectLen()
5939 * performs a slow conversion: not worth it. */
5940 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
&&
5941 ((c
->argv
[2]->encoding
== REDIS_ENCODING_RAW
&&
5942 sdslen(c
->argv
[2]->ptr
) > server
.hash_max_zipmap_value
) ||
5943 (c
->argv
[3]->encoding
== REDIS_ENCODING_RAW
&&
5944 sdslen(c
->argv
[3]->ptr
) > server
.hash_max_zipmap_value
)))
5946 convertToRealHash(o
);
5949 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
5950 unsigned char *zm
= o
->ptr
;
5951 robj
*valobj
= getDecodedObject(c
->argv
[3]);
5953 zm
= zipmapSet(zm
,c
->argv
[2]->ptr
,sdslen(c
->argv
[2]->ptr
),
5954 valobj
->ptr
,sdslen(valobj
->ptr
),&update
);
5955 decrRefCount(valobj
);
5958 /* And here there is the second check for hash conversion...
5959 * we want to do it only if the operation was not just an update as
5960 * zipmapLen() is O(N). */
5961 if (!update
&& zipmapLen(zm
) > server
.hash_max_zipmap_entries
)
5962 convertToRealHash(o
);
5964 tryObjectEncoding(c
->argv
[2]);
5965 /* note that c->argv[3] is already encoded, as the latest arg
5966 * of a bulk command is always integer encoded if possible. */
5967 if (dictAdd(o
->ptr
,c
->argv
[2],c
->argv
[3]) == DICT_OK
) {
5968 incrRefCount(c
->argv
[2]);
5972 incrRefCount(c
->argv
[3]);
5975 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",update
== 0));
5978 static void hgetCommand(redisClient
*c
) {
5979 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5982 addReply(c
,shared
.nullbulk
);
5985 if (o
->type
!= REDIS_HASH
) {
5986 addReply(c
,shared
.wrongtypeerr
);
5990 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
5991 unsigned char *zm
= o
->ptr
;
5995 if (zipmapGet(zm
,c
->argv
[2]->ptr
,sdslen(c
->argv
[2]->ptr
), &val
,&vlen
)) {
5996 addReplySds(c
,sdscatprintf(sdsempty(),"$%u\r\n", vlen
));
5997 addReplySds(c
,sdsnewlen(val
,vlen
));
5998 addReply(c
,shared
.crlf
);
6001 addReply(c
,shared
.nullbulk
);
6005 struct dictEntry
*de
;
6007 de
= dictFind(o
->ptr
,c
->argv
[2]);
6009 addReply(c
,shared
.nullbulk
);
6011 robj
*e
= dictGetEntryVal(de
);
6013 addReplyBulkLen(c
,e
);
6015 addReply(c
,shared
.crlf
);
6021 static void hdelCommand(redisClient
*c
) {
6022 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[1]);
6025 addReply(c
,shared
.czero
);
6030 if (o
->type
!= REDIS_HASH
) {
6031 addReply(c
,shared
.wrongtypeerr
);
6035 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6036 o
->ptr
= zipmapDel((unsigned char*) o
->ptr
,
6037 (unsigned char*) c
->argv
[2]->ptr
,
6038 sdslen(c
->argv
[2]->ptr
), &deleted
);
6040 deleted
= dictDelete((dict
*)o
->ptr
,c
->argv
[2]) == DICT_OK
;
6042 addReply(c
,deleted
? shared
.cone
: shared
.czero
);
6046 static void convertToRealHash(robj
*o
) {
6047 unsigned char *key
, *val
, *p
, *zm
= o
->ptr
;
6048 unsigned int klen
, vlen
;
6049 dict
*dict
= dictCreate(&hashDictType
,NULL
);
6051 assert(o
->type
== REDIS_HASH
&& o
->encoding
!= REDIS_ENCODING_HT
);
6052 p
= zipmapRewind(zm
);
6053 while((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) != NULL
) {
6054 robj
*keyobj
, *valobj
;
6056 keyobj
= createStringObject((char*)key
,klen
);
6057 valobj
= createStringObject((char*)val
,vlen
);
6058 tryObjectEncoding(keyobj
);
6059 tryObjectEncoding(valobj
);
6060 dictAdd(dict
,keyobj
,valobj
);
6062 o
->encoding
= REDIS_ENCODING_HT
;
6067 /* ========================= Non type-specific commands ==================== */
6069 static void flushdbCommand(redisClient
*c
) {
6070 server
.dirty
+= dictSize(c
->db
->dict
);
6071 dictEmpty(c
->db
->dict
);
6072 dictEmpty(c
->db
->expires
);
6073 addReply(c
,shared
.ok
);
6076 static void flushallCommand(redisClient
*c
) {
6077 server
.dirty
+= emptyDb();
6078 addReply(c
,shared
.ok
);
6079 rdbSave(server
.dbfilename
);
6083 static redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
6084 redisSortOperation
*so
= zmalloc(sizeof(*so
));
6086 so
->pattern
= pattern
;
6090 /* Return the value associated to the key with a name obtained
6091 * substituting the first occurence of '*' in 'pattern' with 'subst' */
6092 static robj
*lookupKeyByPattern(redisDb
*db
, robj
*pattern
, robj
*subst
) {
6096 int prefixlen
, sublen
, postfixlen
;
6097 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
6101 char buf
[REDIS_SORTKEY_MAX
+1];
6104 /* If the pattern is "#" return the substitution object itself in order
6105 * to implement the "SORT ... GET #" feature. */
6106 spat
= pattern
->ptr
;
6107 if (spat
[0] == '#' && spat
[1] == '\0') {
6111 /* The substitution object may be specially encoded. If so we create
6112 * a decoded object on the fly. Otherwise getDecodedObject will just
6113 * increment the ref count, that we'll decrement later. */
6114 subst
= getDecodedObject(subst
);
6117 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
6118 p
= strchr(spat
,'*');
6120 decrRefCount(subst
);
6125 sublen
= sdslen(ssub
);
6126 postfixlen
= sdslen(spat
)-(prefixlen
+1);
6127 memcpy(keyname
.buf
,spat
,prefixlen
);
6128 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
6129 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
6130 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
6131 keyname
.len
= prefixlen
+sublen
+postfixlen
;
6133 initStaticStringObject(keyobj
,((char*)&keyname
)+(sizeof(long)*2))
6134 decrRefCount(subst
);
6136 /* printf("lookup '%s' => %p\n", keyname.buf,de); */
6137 return lookupKeyRead(db
,&keyobj
);
6140 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
6141 * the additional parameter is not standard but a BSD-specific we have to
6142 * pass sorting parameters via the global 'server' structure */
6143 static int sortCompare(const void *s1
, const void *s2
) {
6144 const redisSortObject
*so1
= s1
, *so2
= s2
;
6147 if (!server
.sort_alpha
) {
6148 /* Numeric sorting. Here it's trivial as we precomputed scores */
6149 if (so1
->u
.score
> so2
->u
.score
) {
6151 } else if (so1
->u
.score
< so2
->u
.score
) {
6157 /* Alphanumeric sorting */
6158 if (server
.sort_bypattern
) {
6159 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
6160 /* At least one compare object is NULL */
6161 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
6163 else if (so1
->u
.cmpobj
== NULL
)
6168 /* We have both the objects, use strcoll */
6169 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
6172 /* Compare elements directly */
6175 dec1
= getDecodedObject(so1
->obj
);
6176 dec2
= getDecodedObject(so2
->obj
);
6177 cmp
= strcoll(dec1
->ptr
,dec2
->ptr
);
6182 return server
.sort_desc
? -cmp
: cmp
;
6185 /* The SORT command is the most complex command in Redis. Warning: this code
6186 * is optimized for speed and a bit less for readability */
6187 static void sortCommand(redisClient
*c
) {
6190 int desc
= 0, alpha
= 0;
6191 int limit_start
= 0, limit_count
= -1, start
, end
;
6192 int j
, dontsort
= 0, vectorlen
;
6193 int getop
= 0; /* GET operation counter */
6194 robj
*sortval
, *sortby
= NULL
, *storekey
= NULL
;
6195 redisSortObject
*vector
; /* Resulting vector to sort */
6197 /* Lookup the key to sort. It must be of the right types */
6198 sortval
= lookupKeyRead(c
->db
,c
->argv
[1]);
6199 if (sortval
== NULL
) {
6200 addReply(c
,shared
.nullmultibulk
);
6203 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
&&
6204 sortval
->type
!= REDIS_ZSET
)
6206 addReply(c
,shared
.wrongtypeerr
);
6210 /* Create a list of operations to perform for every sorted element.
6211 * Operations can be GET/DEL/INCR/DECR */
6212 operations
= listCreate();
6213 listSetFreeMethod(operations
,zfree
);
6216 /* Now we need to protect sortval incrementing its count, in the future
6217 * SORT may have options able to overwrite/delete keys during the sorting
6218 * and the sorted key itself may get destroied */
6219 incrRefCount(sortval
);
6221 /* The SORT command has an SQL-alike syntax, parse it */
6222 while(j
< c
->argc
) {
6223 int leftargs
= c
->argc
-j
-1;
6224 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
6226 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
6228 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
6230 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
6231 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
6232 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
6234 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"store") && leftargs
>= 1) {
6235 storekey
= c
->argv
[j
+1];
6237 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
6238 sortby
= c
->argv
[j
+1];
6239 /* If the BY pattern does not contain '*', i.e. it is constant,
6240 * we don't need to sort nor to lookup the weight keys. */
6241 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
6243 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
6244 listAddNodeTail(operations
,createSortOperation(
6245 REDIS_SORT_GET
,c
->argv
[j
+1]));
6249 decrRefCount(sortval
);
6250 listRelease(operations
);
6251 addReply(c
,shared
.syntaxerr
);
6257 /* Load the sorting vector with all the objects to sort */
6258 switch(sortval
->type
) {
6259 case REDIS_LIST
: vectorlen
= listLength((list
*)sortval
->ptr
); break;
6260 case REDIS_SET
: vectorlen
= dictSize((dict
*)sortval
->ptr
); break;
6261 case REDIS_ZSET
: vectorlen
= dictSize(((zset
*)sortval
->ptr
)->dict
); break;
6262 default: vectorlen
= 0; redisAssert(0); /* Avoid GCC warning */
6264 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
6267 if (sortval
->type
== REDIS_LIST
) {
6268 list
*list
= sortval
->ptr
;
6272 listRewind(list
,&li
);
6273 while((ln
= listNext(&li
))) {
6274 robj
*ele
= ln
->value
;
6275 vector
[j
].obj
= ele
;
6276 vector
[j
].u
.score
= 0;
6277 vector
[j
].u
.cmpobj
= NULL
;
6285 if (sortval
->type
== REDIS_SET
) {
6288 zset
*zs
= sortval
->ptr
;
6292 di
= dictGetIterator(set
);
6293 while((setele
= dictNext(di
)) != NULL
) {
6294 vector
[j
].obj
= dictGetEntryKey(setele
);
6295 vector
[j
].u
.score
= 0;
6296 vector
[j
].u
.cmpobj
= NULL
;
6299 dictReleaseIterator(di
);
6301 redisAssert(j
== vectorlen
);
6303 /* Now it's time to load the right scores in the sorting vector */
6304 if (dontsort
== 0) {
6305 for (j
= 0; j
< vectorlen
; j
++) {
6309 byval
= lookupKeyByPattern(c
->db
,sortby
,vector
[j
].obj
);
6310 if (!byval
|| byval
->type
!= REDIS_STRING
) continue;
6312 vector
[j
].u
.cmpobj
= getDecodedObject(byval
);
6314 if (byval
->encoding
== REDIS_ENCODING_RAW
) {
6315 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
6317 /* Don't need to decode the object if it's
6318 * integer-encoded (the only encoding supported) so
6319 * far. We can just cast it */
6320 if (byval
->encoding
== REDIS_ENCODING_INT
) {
6321 vector
[j
].u
.score
= (long)byval
->ptr
;
6323 redisAssert(1 != 1);
6328 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_RAW
)
6329 vector
[j
].u
.score
= strtod(vector
[j
].obj
->ptr
,NULL
);
6331 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_INT
)
6332 vector
[j
].u
.score
= (long) vector
[j
].obj
->ptr
;
6334 redisAssert(1 != 1);
6341 /* We are ready to sort the vector... perform a bit of sanity check
6342 * on the LIMIT option too. We'll use a partial version of quicksort. */
6343 start
= (limit_start
< 0) ? 0 : limit_start
;
6344 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
6345 if (start
>= vectorlen
) {
6346 start
= vectorlen
-1;
6349 if (end
>= vectorlen
) end
= vectorlen
-1;
6351 if (dontsort
== 0) {
6352 server
.sort_desc
= desc
;
6353 server
.sort_alpha
= alpha
;
6354 server
.sort_bypattern
= sortby
? 1 : 0;
6355 if (sortby
&& (start
!= 0 || end
!= vectorlen
-1))
6356 pqsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
, start
,end
);
6358 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
6361 /* Send command output to the output buffer, performing the specified
6362 * GET/DEL/INCR/DECR operations if any. */
6363 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
6364 if (storekey
== NULL
) {
6365 /* STORE option not specified, sent the sorting result to client */
6366 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
6367 for (j
= start
; j
<= end
; j
++) {
6372 addReplyBulkLen(c
,vector
[j
].obj
);
6373 addReply(c
,vector
[j
].obj
);
6374 addReply(c
,shared
.crlf
);
6376 listRewind(operations
,&li
);
6377 while((ln
= listNext(&li
))) {
6378 redisSortOperation
*sop
= ln
->value
;
6379 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
6382 if (sop
->type
== REDIS_SORT_GET
) {
6383 if (!val
|| val
->type
!= REDIS_STRING
) {
6384 addReply(c
,shared
.nullbulk
);
6386 addReplyBulkLen(c
,val
);
6388 addReply(c
,shared
.crlf
);
6391 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
6396 robj
*listObject
= createListObject();
6397 list
*listPtr
= (list
*) listObject
->ptr
;
6399 /* STORE option specified, set the sorting result as a List object */
6400 for (j
= start
; j
<= end
; j
++) {
6405 listAddNodeTail(listPtr
,vector
[j
].obj
);
6406 incrRefCount(vector
[j
].obj
);
6408 listRewind(operations
,&li
);
6409 while((ln
= listNext(&li
))) {
6410 redisSortOperation
*sop
= ln
->value
;
6411 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
6414 if (sop
->type
== REDIS_SORT_GET
) {
6415 if (!val
|| val
->type
!= REDIS_STRING
) {
6416 listAddNodeTail(listPtr
,createStringObject("",0));
6418 listAddNodeTail(listPtr
,val
);
6422 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
6426 if (dictReplace(c
->db
->dict
,storekey
,listObject
)) {
6427 incrRefCount(storekey
);
6429 /* Note: we add 1 because the DB is dirty anyway since even if the
6430 * SORT result is empty a new key is set and maybe the old content
6432 server
.dirty
+= 1+outputlen
;
6433 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",outputlen
));
6437 decrRefCount(sortval
);
6438 listRelease(operations
);
6439 for (j
= 0; j
< vectorlen
; j
++) {
6440 if (sortby
&& alpha
&& vector
[j
].u
.cmpobj
)
6441 decrRefCount(vector
[j
].u
.cmpobj
);
6446 /* Convert an amount of bytes into a human readable string in the form
6447 * of 100B, 2G, 100M, 4K, and so forth. */
6448 static void bytesToHuman(char *s
, unsigned long long n
) {
6453 sprintf(s
,"%lluB",n
);
6455 } else if (n
< (1024*1024)) {
6456 d
= (double)n
/(1024);
6457 sprintf(s
,"%.2fK",d
);
6458 } else if (n
< (1024LL*1024*1024)) {
6459 d
= (double)n
/(1024*1024);
6460 sprintf(s
,"%.2fM",d
);
6461 } else if (n
< (1024LL*1024*1024*1024)) {
6462 d
= (double)n
/(1024LL*1024*1024);
6463 sprintf(s
,"%.2fG",d
);
6467 /* Create the string returned by the INFO command. This is decoupled
6468 * by the INFO command itself as we need to report the same information
6469 * on memory corruption problems. */
6470 static sds
genRedisInfoString(void) {
6472 time_t uptime
= time(NULL
)-server
.stat_starttime
;
6476 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
6477 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
6479 bytesToHuman(hmem
,zmalloc_used_memory());
6480 info
= sdscatprintf(sdsempty(),
6481 "redis_version:%s\r\n"
6483 "multiplexing_api:%s\r\n"
6484 "process_id:%ld\r\n"
6485 "uptime_in_seconds:%ld\r\n"
6486 "uptime_in_days:%ld\r\n"
6487 "connected_clients:%d\r\n"
6488 "connected_slaves:%d\r\n"
6489 "blocked_clients:%d\r\n"
6490 "used_memory:%zu\r\n"
6491 "used_memory_human:%s\r\n"
6492 "changes_since_last_save:%lld\r\n"
6493 "bgsave_in_progress:%d\r\n"
6494 "last_save_time:%ld\r\n"
6495 "bgrewriteaof_in_progress:%d\r\n"
6496 "total_connections_received:%lld\r\n"
6497 "total_commands_processed:%lld\r\n"
6498 "hash_max_zipmap_entries:%ld\r\n"
6499 "hash_max_zipmap_value:%ld\r\n"
6503 (sizeof(long) == 8) ? "64" : "32",
6508 listLength(server
.clients
)-listLength(server
.slaves
),
6509 listLength(server
.slaves
),
6510 server
.blpop_blocked_clients
,
6511 zmalloc_used_memory(),
6514 server
.bgsavechildpid
!= -1,
6516 server
.bgrewritechildpid
!= -1,
6517 server
.stat_numconnections
,
6518 server
.stat_numcommands
,
6519 server
.hash_max_zipmap_entries
,
6520 server
.hash_max_zipmap_value
,
6521 server
.vm_enabled
!= 0,
6522 server
.masterhost
== NULL
? "master" : "slave"
6524 if (server
.masterhost
) {
6525 info
= sdscatprintf(info
,
6526 "master_host:%s\r\n"
6527 "master_port:%d\r\n"
6528 "master_link_status:%s\r\n"
6529 "master_last_io_seconds_ago:%d\r\n"
6532 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
6534 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1
6537 if (server
.vm_enabled
) {
6539 info
= sdscatprintf(info
,
6540 "vm_conf_max_memory:%llu\r\n"
6541 "vm_conf_page_size:%llu\r\n"
6542 "vm_conf_pages:%llu\r\n"
6543 "vm_stats_used_pages:%llu\r\n"
6544 "vm_stats_swapped_objects:%llu\r\n"
6545 "vm_stats_swappin_count:%llu\r\n"
6546 "vm_stats_swappout_count:%llu\r\n"
6547 "vm_stats_io_newjobs_len:%lu\r\n"
6548 "vm_stats_io_processing_len:%lu\r\n"
6549 "vm_stats_io_processed_len:%lu\r\n"
6550 "vm_stats_io_active_threads:%lu\r\n"
6551 "vm_stats_blocked_clients:%lu\r\n"
6552 ,(unsigned long long) server
.vm_max_memory
,
6553 (unsigned long long) server
.vm_page_size
,
6554 (unsigned long long) server
.vm_pages
,
6555 (unsigned long long) server
.vm_stats_used_pages
,
6556 (unsigned long long) server
.vm_stats_swapped_objects
,
6557 (unsigned long long) server
.vm_stats_swapins
,
6558 (unsigned long long) server
.vm_stats_swapouts
,
6559 (unsigned long) listLength(server
.io_newjobs
),
6560 (unsigned long) listLength(server
.io_processing
),
6561 (unsigned long) listLength(server
.io_processed
),
6562 (unsigned long) server
.io_active_threads
,
6563 (unsigned long) server
.vm_blocked_clients
6567 for (j
= 0; j
< server
.dbnum
; j
++) {
6568 long long keys
, vkeys
;
6570 keys
= dictSize(server
.db
[j
].dict
);
6571 vkeys
= dictSize(server
.db
[j
].expires
);
6572 if (keys
|| vkeys
) {
6573 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
6580 static void infoCommand(redisClient
*c
) {
6581 sds info
= genRedisInfoString();
6582 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
6583 (unsigned long)sdslen(info
)));
6584 addReplySds(c
,info
);
6585 addReply(c
,shared
.crlf
);
6588 static void monitorCommand(redisClient
*c
) {
6589 /* ignore MONITOR if aleady slave or in monitor mode */
6590 if (c
->flags
& REDIS_SLAVE
) return;
6592 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
6594 listAddNodeTail(server
.monitors
,c
);
6595 addReply(c
,shared
.ok
);
6598 /* ================================= Expire ================================= */
6599 static int removeExpire(redisDb
*db
, robj
*key
) {
6600 if (dictDelete(db
->expires
,key
) == DICT_OK
) {
6607 static int setExpire(redisDb
*db
, robj
*key
, time_t when
) {
6608 if (dictAdd(db
->expires
,key
,(void*)when
) == DICT_ERR
) {
6616 /* Return the expire time of the specified key, or -1 if no expire
6617 * is associated with this key (i.e. the key is non volatile) */
6618 static time_t getExpire(redisDb
*db
, robj
*key
) {
6621 /* No expire? return ASAP */
6622 if (dictSize(db
->expires
) == 0 ||
6623 (de
= dictFind(db
->expires
,key
)) == NULL
) return -1;
6625 return (time_t) dictGetEntryVal(de
);
6628 static int expireIfNeeded(redisDb
*db
, robj
*key
) {
6632 /* No expire? return ASAP */
6633 if (dictSize(db
->expires
) == 0 ||
6634 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
6636 /* Lookup the expire */
6637 when
= (time_t) dictGetEntryVal(de
);
6638 if (time(NULL
) <= when
) return 0;
6640 /* Delete the key */
6641 dictDelete(db
->expires
,key
);
6642 return dictDelete(db
->dict
,key
) == DICT_OK
;
6645 static int deleteIfVolatile(redisDb
*db
, robj
*key
) {
6648 /* No expire? return ASAP */
6649 if (dictSize(db
->expires
) == 0 ||
6650 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
6652 /* Delete the key */
6654 dictDelete(db
->expires
,key
);
6655 return dictDelete(db
->dict
,key
) == DICT_OK
;
6658 static void expireGenericCommand(redisClient
*c
, robj
*key
, time_t seconds
) {
6661 de
= dictFind(c
->db
->dict
,key
);
6663 addReply(c
,shared
.czero
);
6667 if (deleteKey(c
->db
,key
)) server
.dirty
++;
6668 addReply(c
, shared
.cone
);
6671 time_t when
= time(NULL
)+seconds
;
6672 if (setExpire(c
->db
,key
,when
)) {
6673 addReply(c
,shared
.cone
);
6676 addReply(c
,shared
.czero
);
6682 static void expireCommand(redisClient
*c
) {
6683 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10));
6686 static void expireatCommand(redisClient
*c
) {
6687 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10)-time(NULL
));
6690 static void ttlCommand(redisClient
*c
) {
6694 expire
= getExpire(c
->db
,c
->argv
[1]);
6696 ttl
= (int) (expire
-time(NULL
));
6697 if (ttl
< 0) ttl
= -1;
6699 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",ttl
));
6702 /* ================================ MULTI/EXEC ============================== */
6704 /* Client state initialization for MULTI/EXEC */
6705 static void initClientMultiState(redisClient
*c
) {
6706 c
->mstate
.commands
= NULL
;
6707 c
->mstate
.count
= 0;
6710 /* Release all the resources associated with MULTI/EXEC state */
6711 static void freeClientMultiState(redisClient
*c
) {
6714 for (j
= 0; j
< c
->mstate
.count
; j
++) {
6716 multiCmd
*mc
= c
->mstate
.commands
+j
;
6718 for (i
= 0; i
< mc
->argc
; i
++)
6719 decrRefCount(mc
->argv
[i
]);
6722 zfree(c
->mstate
.commands
);
6725 /* Add a new command into the MULTI commands queue */
6726 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
) {
6730 c
->mstate
.commands
= zrealloc(c
->mstate
.commands
,
6731 sizeof(multiCmd
)*(c
->mstate
.count
+1));
6732 mc
= c
->mstate
.commands
+c
->mstate
.count
;
6735 mc
->argv
= zmalloc(sizeof(robj
*)*c
->argc
);
6736 memcpy(mc
->argv
,c
->argv
,sizeof(robj
*)*c
->argc
);
6737 for (j
= 0; j
< c
->argc
; j
++)
6738 incrRefCount(mc
->argv
[j
]);
6742 static void multiCommand(redisClient
*c
) {
6743 c
->flags
|= REDIS_MULTI
;
6744 addReply(c
,shared
.ok
);
6747 static void discardCommand(redisClient
*c
) {
6748 if (!(c
->flags
& REDIS_MULTI
)) {
6749 addReplySds(c
,sdsnew("-ERR DISCARD without MULTI\r\n"));
6753 freeClientMultiState(c
);
6754 initClientMultiState(c
);
6755 c
->flags
&= (~REDIS_MULTI
);
6756 addReply(c
,shared
.ok
);
6759 static void execCommand(redisClient
*c
) {
6764 if (!(c
->flags
& REDIS_MULTI
)) {
6765 addReplySds(c
,sdsnew("-ERR EXEC without MULTI\r\n"));
6769 orig_argv
= c
->argv
;
6770 orig_argc
= c
->argc
;
6771 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->mstate
.count
));
6772 for (j
= 0; j
< c
->mstate
.count
; j
++) {
6773 c
->argc
= c
->mstate
.commands
[j
].argc
;
6774 c
->argv
= c
->mstate
.commands
[j
].argv
;
6775 call(c
,c
->mstate
.commands
[j
].cmd
);
6777 c
->argv
= orig_argv
;
6778 c
->argc
= orig_argc
;
6779 freeClientMultiState(c
);
6780 initClientMultiState(c
);
6781 c
->flags
&= (~REDIS_MULTI
);
6784 /* =========================== Blocking Operations ========================= */
6786 /* Currently Redis blocking operations support is limited to list POP ops,
6787 * so the current implementation is not fully generic, but it is also not
6788 * completely specific so it will not require a rewrite to support new
6789 * kind of blocking operations in the future.
6791 * Still it's important to note that list blocking operations can be already
6792 * used as a notification mechanism in order to implement other blocking
6793 * operations at application level, so there must be a very strong evidence
6794 * of usefulness and generality before new blocking operations are implemented.
6796 * This is how the current blocking POP works, we use BLPOP as example:
6797 * - If the user calls BLPOP and the key exists and contains a non empty list
6798 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
6799 * if there is not to block.
6800 * - If instead BLPOP is called and the key does not exists or the list is
6801 * empty we need to block. In order to do so we remove the notification for
6802 * new data to read in the client socket (so that we'll not serve new
6803 * requests if the blocking request is not served). Also we put the client
6804 * in a dictionary (db->blockingkeys) mapping keys to a list of clients
6805 * blocking for this keys.
6806 * - If a PUSH operation against a key with blocked clients waiting is
6807 * performed, we serve the first in the list: basically instead to push
6808 * the new element inside the list we return it to the (first / oldest)
6809 * blocking client, unblock the client, and remove it form the list.
6811 * The above comment and the source code should be enough in order to understand
6812 * the implementation and modify / fix it later.
6815 /* Set a client in blocking mode for the specified key, with the specified
6817 static void blockForKeys(redisClient
*c
, robj
**keys
, int numkeys
, time_t timeout
) {
6822 c
->blockingkeys
= zmalloc(sizeof(robj
*)*numkeys
);
6823 c
->blockingkeysnum
= numkeys
;
6824 c
->blockingto
= timeout
;
6825 for (j
= 0; j
< numkeys
; j
++) {
6826 /* Add the key in the client structure, to map clients -> keys */
6827 c
->blockingkeys
[j
] = keys
[j
];
6828 incrRefCount(keys
[j
]);
6830 /* And in the other "side", to map keys -> clients */
6831 de
= dictFind(c
->db
->blockingkeys
,keys
[j
]);
6835 /* For every key we take a list of clients blocked for it */
6837 retval
= dictAdd(c
->db
->blockingkeys
,keys
[j
],l
);
6838 incrRefCount(keys
[j
]);
6839 assert(retval
== DICT_OK
);
6841 l
= dictGetEntryVal(de
);
6843 listAddNodeTail(l
,c
);
6845 /* Mark the client as a blocked client */
6846 c
->flags
|= REDIS_BLOCKED
;
6847 server
.blpop_blocked_clients
++;
6850 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
6851 static void unblockClientWaitingData(redisClient
*c
) {
6856 assert(c
->blockingkeys
!= NULL
);
6857 /* The client may wait for multiple keys, so unblock it for every key. */
6858 for (j
= 0; j
< c
->blockingkeysnum
; j
++) {
6859 /* Remove this client from the list of clients waiting for this key. */
6860 de
= dictFind(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
6862 l
= dictGetEntryVal(de
);
6863 listDelNode(l
,listSearchKey(l
,c
));
6864 /* If the list is empty we need to remove it to avoid wasting memory */
6865 if (listLength(l
) == 0)
6866 dictDelete(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
6867 decrRefCount(c
->blockingkeys
[j
]);
6869 /* Cleanup the client structure */
6870 zfree(c
->blockingkeys
);
6871 c
->blockingkeys
= NULL
;
6872 c
->flags
&= (~REDIS_BLOCKED
);
6873 server
.blpop_blocked_clients
--;
6874 /* We want to process data if there is some command waiting
6875 * in the input buffer. Note that this is safe even if
6876 * unblockClientWaitingData() gets called from freeClient() because
6877 * freeClient() will be smart enough to call this function
6878 * *after* c->querybuf was set to NULL. */
6879 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0) processInputBuffer(c
);
6882 /* This should be called from any function PUSHing into lists.
6883 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
6884 * 'ele' is the element pushed.
6886 * If the function returns 0 there was no client waiting for a list push
6889 * If the function returns 1 there was a client waiting for a list push
6890 * against this key, the element was passed to this client thus it's not
6891 * needed to actually add it to the list and the caller should return asap. */
6892 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
) {
6893 struct dictEntry
*de
;
6894 redisClient
*receiver
;
6898 de
= dictFind(c
->db
->blockingkeys
,key
);
6899 if (de
== NULL
) return 0;
6900 l
= dictGetEntryVal(de
);
6903 receiver
= ln
->value
;
6905 addReplySds(receiver
,sdsnew("*2\r\n"));
6906 addReplyBulkLen(receiver
,key
);
6907 addReply(receiver
,key
);
6908 addReply(receiver
,shared
.crlf
);
6909 addReplyBulkLen(receiver
,ele
);
6910 addReply(receiver
,ele
);
6911 addReply(receiver
,shared
.crlf
);
6912 unblockClientWaitingData(receiver
);
6916 /* Blocking RPOP/LPOP */
6917 static void blockingPopGenericCommand(redisClient
*c
, int where
) {
6922 for (j
= 1; j
< c
->argc
-1; j
++) {
6923 o
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
6925 if (o
->type
!= REDIS_LIST
) {
6926 addReply(c
,shared
.wrongtypeerr
);
6929 list
*list
= o
->ptr
;
6930 if (listLength(list
) != 0) {
6931 /* If the list contains elements fall back to the usual
6932 * non-blocking POP operation */
6933 robj
*argv
[2], **orig_argv
;
6936 /* We need to alter the command arguments before to call
6937 * popGenericCommand() as the command takes a single key. */
6938 orig_argv
= c
->argv
;
6939 orig_argc
= c
->argc
;
6940 argv
[1] = c
->argv
[j
];
6944 /* Also the return value is different, we need to output
6945 * the multi bulk reply header and the key name. The
6946 * "real" command will add the last element (the value)
6947 * for us. If this souds like an hack to you it's just
6948 * because it is... */
6949 addReplySds(c
,sdsnew("*2\r\n"));
6950 addReplyBulkLen(c
,argv
[1]);
6951 addReply(c
,argv
[1]);
6952 addReply(c
,shared
.crlf
);
6953 popGenericCommand(c
,where
);
6955 /* Fix the client structure with the original stuff */
6956 c
->argv
= orig_argv
;
6957 c
->argc
= orig_argc
;
6963 /* If the list is empty or the key does not exists we must block */
6964 timeout
= strtol(c
->argv
[c
->argc
-1]->ptr
,NULL
,10);
6965 if (timeout
> 0) timeout
+= time(NULL
);
6966 blockForKeys(c
,c
->argv
+1,c
->argc
-2,timeout
);
6969 static void blpopCommand(redisClient
*c
) {
6970 blockingPopGenericCommand(c
,REDIS_HEAD
);
6973 static void brpopCommand(redisClient
*c
) {
6974 blockingPopGenericCommand(c
,REDIS_TAIL
);
6977 /* =============================== Replication ============================= */
6979 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6980 ssize_t nwritten
, ret
= size
;
6981 time_t start
= time(NULL
);
6985 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
6986 nwritten
= write(fd
,ptr
,size
);
6987 if (nwritten
== -1) return -1;
6991 if ((time(NULL
)-start
) > timeout
) {
6999 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) {
7000 ssize_t nread
, totread
= 0;
7001 time_t start
= time(NULL
);
7005 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
7006 nread
= read(fd
,ptr
,size
);
7007 if (nread
== -1) return -1;
7012 if ((time(NULL
)-start
) > timeout
) {
7020 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
7027 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
7030 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
7041 static void syncCommand(redisClient
*c
) {
7042 /* ignore SYNC if aleady slave or in monitor mode */
7043 if (c
->flags
& REDIS_SLAVE
) return;
7045 /* SYNC can't be issued when the server has pending data to send to
7046 * the client about already issued commands. We need a fresh reply
7047 * buffer registering the differences between the BGSAVE and the current
7048 * dataset, so that we can copy to other slaves if needed. */
7049 if (listLength(c
->reply
) != 0) {
7050 addReplySds(c
,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
7054 redisLog(REDIS_NOTICE
,"Slave ask for synchronization");
7055 /* Here we need to check if there is a background saving operation
7056 * in progress, or if it is required to start one */
7057 if (server
.bgsavechildpid
!= -1) {
7058 /* Ok a background save is in progress. Let's check if it is a good
7059 * one for replication, i.e. if there is another slave that is
7060 * registering differences since the server forked to save */
7065 listRewind(server
.slaves
,&li
);
7066 while((ln
= listNext(&li
))) {
7068 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) break;
7071 /* Perfect, the server is already registering differences for
7072 * another slave. Set the right state, and copy the buffer. */
7073 listRelease(c
->reply
);
7074 c
->reply
= listDup(slave
->reply
);
7075 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
7076 redisLog(REDIS_NOTICE
,"Waiting for end of BGSAVE for SYNC");
7078 /* No way, we need to wait for the next BGSAVE in order to
7079 * register differences */
7080 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
7081 redisLog(REDIS_NOTICE
,"Waiting for next BGSAVE for SYNC");
7084 /* Ok we don't have a BGSAVE in progress, let's start one */
7085 redisLog(REDIS_NOTICE
,"Starting BGSAVE for SYNC");
7086 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
7087 redisLog(REDIS_NOTICE
,"Replication failed, can't BGSAVE");
7088 addReplySds(c
,sdsnew("-ERR Unalbe to perform background save\r\n"));
7091 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
7094 c
->flags
|= REDIS_SLAVE
;
7096 listAddNodeTail(server
.slaves
,c
);
7100 static void sendBulkToSlave(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
7101 redisClient
*slave
= privdata
;
7103 REDIS_NOTUSED(mask
);
7104 char buf
[REDIS_IOBUF_LEN
];
7105 ssize_t nwritten
, buflen
;
7107 if (slave
->repldboff
== 0) {
7108 /* Write the bulk write count before to transfer the DB. In theory here
7109 * we don't know how much room there is in the output buffer of the
7110 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
7111 * operations) will never be smaller than the few bytes we need. */
7114 bulkcount
= sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
7116 if (write(fd
,bulkcount
,sdslen(bulkcount
)) != (signed)sdslen(bulkcount
))
7124 lseek(slave
->repldbfd
,slave
->repldboff
,SEEK_SET
);
7125 buflen
= read(slave
->repldbfd
,buf
,REDIS_IOBUF_LEN
);
7127 redisLog(REDIS_WARNING
,"Read error sending DB to slave: %s",
7128 (buflen
== 0) ? "premature EOF" : strerror(errno
));
7132 if ((nwritten
= write(fd
,buf
,buflen
)) == -1) {
7133 redisLog(REDIS_VERBOSE
,"Write error sending DB to slave: %s",
7138 slave
->repldboff
+= nwritten
;
7139 if (slave
->repldboff
== slave
->repldbsize
) {
7140 close(slave
->repldbfd
);
7141 slave
->repldbfd
= -1;
7142 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
7143 slave
->replstate
= REDIS_REPL_ONLINE
;
7144 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
,
7145 sendReplyToClient
, slave
) == AE_ERR
) {
7149 addReplySds(slave
,sdsempty());
7150 redisLog(REDIS_NOTICE
,"Synchronization with slave succeeded");
7154 /* This function is called at the end of every backgrond saving.
7155 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
7156 * otherwise REDIS_ERR is passed to the function.
7158 * The goal of this function is to handle slaves waiting for a successful
7159 * background saving in order to perform non-blocking synchronization. */
7160 static void updateSlavesWaitingBgsave(int bgsaveerr
) {
7162 int startbgsave
= 0;
7165 listRewind(server
.slaves
,&li
);
7166 while((ln
= listNext(&li
))) {
7167 redisClient
*slave
= ln
->value
;
7169 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) {
7171 slave
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
7172 } else if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) {
7173 struct redis_stat buf
;
7175 if (bgsaveerr
!= REDIS_OK
) {
7177 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE child returned an error");
7180 if ((slave
->repldbfd
= open(server
.dbfilename
,O_RDONLY
)) == -1 ||
7181 redis_fstat(slave
->repldbfd
,&buf
) == -1) {
7183 redisLog(REDIS_WARNING
,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno
));
7186 slave
->repldboff
= 0;
7187 slave
->repldbsize
= buf
.st_size
;
7188 slave
->replstate
= REDIS_REPL_SEND_BULK
;
7189 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
7190 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
, sendBulkToSlave
, slave
) == AE_ERR
) {
7197 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
7200 listRewind(server
.slaves
,&li
);
7201 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE failed");
7202 while((ln
= listNext(&li
))) {
7203 redisClient
*slave
= ln
->value
;
7205 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
)
7212 static int syncWithMaster(void) {
7213 char buf
[1024], tmpfile
[256], authcmd
[1024];
7215 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
7216 int dfd
, maxtries
= 5;
7219 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
7224 /* AUTH with the master if required. */
7225 if(server
.masterauth
) {
7226 snprintf(authcmd
, 1024, "AUTH %s\r\n", server
.masterauth
);
7227 if (syncWrite(fd
, authcmd
, strlen(server
.masterauth
)+7, 5) == -1) {
7229 redisLog(REDIS_WARNING
,"Unable to AUTH to MASTER: %s",
7233 /* Read the AUTH result. */
7234 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
7236 redisLog(REDIS_WARNING
,"I/O error reading auth result from MASTER: %s",
7240 if (buf
[0] != '+') {
7242 redisLog(REDIS_WARNING
,"Cannot AUTH to MASTER, is the masterauth password correct?");
7247 /* Issue the SYNC command */
7248 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
7250 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
7254 /* Read the bulk write count */
7255 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
7257 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
7261 if (buf
[0] != '$') {
7263 redisLog(REDIS_WARNING
,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
7266 dumpsize
= strtol(buf
+1,NULL
,10);
7267 redisLog(REDIS_NOTICE
,"Receiving %ld bytes data dump from MASTER",dumpsize
);
7268 /* Read the bulk write data on a temp file */
7270 snprintf(tmpfile
,256,
7271 "temp-%d.%ld.rdb",(int)time(NULL
),(long int)getpid());
7272 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
|O_EXCL
,0644);
7273 if (dfd
!= -1) break;
7278 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
7282 int nread
, nwritten
;
7284 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
7286 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
7292 nwritten
= write(dfd
,buf
,nread
);
7293 if (nwritten
== -1) {
7294 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
7302 if (rename(tmpfile
,server
.dbfilename
) == -1) {
7303 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
7309 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
7310 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
7314 server
.master
= createClient(fd
);
7315 server
.master
->flags
|= REDIS_MASTER
;
7316 server
.master
->authenticated
= 1;
7317 server
.replstate
= REDIS_REPL_CONNECTED
;
7321 static void slaveofCommand(redisClient
*c
) {
7322 if (!strcasecmp(c
->argv
[1]->ptr
,"no") &&
7323 !strcasecmp(c
->argv
[2]->ptr
,"one")) {
7324 if (server
.masterhost
) {
7325 sdsfree(server
.masterhost
);
7326 server
.masterhost
= NULL
;
7327 if (server
.master
) freeClient(server
.master
);
7328 server
.replstate
= REDIS_REPL_NONE
;
7329 redisLog(REDIS_NOTICE
,"MASTER MODE enabled (user request)");
7332 sdsfree(server
.masterhost
);
7333 server
.masterhost
= sdsdup(c
->argv
[1]->ptr
);
7334 server
.masterport
= atoi(c
->argv
[2]->ptr
);
7335 if (server
.master
) freeClient(server
.master
);
7336 server
.replstate
= REDIS_REPL_CONNECT
;
7337 redisLog(REDIS_NOTICE
,"SLAVE OF %s:%d enabled (user request)",
7338 server
.masterhost
, server
.masterport
);
7340 addReply(c
,shared
.ok
);
7343 /* ============================ Maxmemory directive ======================== */
7345 /* Try to free one object form the pre-allocated objects free list.
7346 * This is useful under low mem conditions as by default we take 1 million
7347 * free objects allocated. On success REDIS_OK is returned, otherwise
7349 static int tryFreeOneObjectFromFreelist(void) {
7352 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
7353 if (listLength(server
.objfreelist
)) {
7354 listNode
*head
= listFirst(server
.objfreelist
);
7355 o
= listNodeValue(head
);
7356 listDelNode(server
.objfreelist
,head
);
7357 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
7361 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
7366 /* This function gets called when 'maxmemory' is set on the config file to limit
7367 * the max memory used by the server, and we are out of memory.
7368 * This function will try to, in order:
7370 * - Free objects from the free list
7371 * - Try to remove keys with an EXPIRE set
7373 * It is not possible to free enough memory to reach used-memory < maxmemory
7374 * the server will start refusing commands that will enlarge even more the
7377 static void freeMemoryIfNeeded(void) {
7378 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
7379 int j
, k
, freed
= 0;
7381 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
7382 for (j
= 0; j
< server
.dbnum
; j
++) {
7384 robj
*minkey
= NULL
;
7385 struct dictEntry
*de
;
7387 if (dictSize(server
.db
[j
].expires
)) {
7389 /* From a sample of three keys drop the one nearest to
7390 * the natural expire */
7391 for (k
= 0; k
< 3; k
++) {
7394 de
= dictGetRandomKey(server
.db
[j
].expires
);
7395 t
= (time_t) dictGetEntryVal(de
);
7396 if (minttl
== -1 || t
< minttl
) {
7397 minkey
= dictGetEntryKey(de
);
7401 deleteKey(server
.db
+j
,minkey
);
7404 if (!freed
) return; /* nothing to free... */
7408 /* ============================== Append Only file ========================== */
7410 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
7411 sds buf
= sdsempty();
7417 /* The DB this command was targetting is not the same as the last command
7418 * we appendend. To issue a SELECT command is needed. */
7419 if (dictid
!= server
.appendseldb
) {
7422 snprintf(seldb
,sizeof(seldb
),"%d",dictid
);
7423 buf
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
7424 (unsigned long)strlen(seldb
),seldb
);
7425 server
.appendseldb
= dictid
;
7428 /* "Fix" the argv vector if the command is EXPIRE. We want to translate
7429 * EXPIREs into EXPIREATs calls */
7430 if (cmd
->proc
== expireCommand
) {
7433 tmpargv
[0] = createStringObject("EXPIREAT",8);
7434 tmpargv
[1] = argv
[1];
7435 incrRefCount(argv
[1]);
7436 when
= time(NULL
)+strtol(argv
[2]->ptr
,NULL
,10);
7437 tmpargv
[2] = createObject(REDIS_STRING
,
7438 sdscatprintf(sdsempty(),"%ld",when
));
7442 /* Append the actual command */
7443 buf
= sdscatprintf(buf
,"*%d\r\n",argc
);
7444 for (j
= 0; j
< argc
; j
++) {
7447 o
= getDecodedObject(o
);
7448 buf
= sdscatprintf(buf
,"$%lu\r\n",(unsigned long)sdslen(o
->ptr
));
7449 buf
= sdscatlen(buf
,o
->ptr
,sdslen(o
->ptr
));
7450 buf
= sdscatlen(buf
,"\r\n",2);
7454 /* Free the objects from the modified argv for EXPIREAT */
7455 if (cmd
->proc
== expireCommand
) {
7456 for (j
= 0; j
< 3; j
++)
7457 decrRefCount(argv
[j
]);
7460 /* We want to perform a single write. This should be guaranteed atomic
7461 * at least if the filesystem we are writing is a real physical one.
7462 * While this will save us against the server being killed I don't think
7463 * there is much to do about the whole server stopping for power problems
7465 nwritten
= write(server
.appendfd
,buf
,sdslen(buf
));
7466 if (nwritten
!= (signed)sdslen(buf
)) {
7467 /* Ooops, we are in troubles. The best thing to do for now is
7468 * to simply exit instead to give the illusion that everything is
7469 * working as expected. */
7470 if (nwritten
== -1) {
7471 redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
));
7473 redisLog(REDIS_WARNING
,"Exiting on short write while writing to the append-only file: %s",strerror(errno
));
7477 /* If a background append only file rewriting is in progress we want to
7478 * accumulate the differences between the child DB and the current one
7479 * in a buffer, so that when the child process will do its work we
7480 * can append the differences to the new append only file. */
7481 if (server
.bgrewritechildpid
!= -1)
7482 server
.bgrewritebuf
= sdscatlen(server
.bgrewritebuf
,buf
,sdslen(buf
));
7486 if (server
.appendfsync
== APPENDFSYNC_ALWAYS
||
7487 (server
.appendfsync
== APPENDFSYNC_EVERYSEC
&&
7488 now
-server
.lastfsync
> 1))
7490 fsync(server
.appendfd
); /* Let's try to get this data on the disk */
7491 server
.lastfsync
= now
;
7495 /* In Redis commands are always executed in the context of a client, so in
7496 * order to load the append only file we need to create a fake client. */
7497 static struct redisClient
*createFakeClient(void) {
7498 struct redisClient
*c
= zmalloc(sizeof(*c
));
7502 c
->querybuf
= sdsempty();
7506 /* We set the fake client as a slave waiting for the synchronization
7507 * so that Redis will not try to send replies to this client. */
7508 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
7509 c
->reply
= listCreate();
7510 listSetFreeMethod(c
->reply
,decrRefCount
);
7511 listSetDupMethod(c
->reply
,dupClientReplyValue
);
7515 static void freeFakeClient(struct redisClient
*c
) {
7516 sdsfree(c
->querybuf
);
7517 listRelease(c
->reply
);
7521 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
7522 * error (the append only file is zero-length) REDIS_ERR is returned. On
7523 * fatal error an error message is logged and the program exists. */
7524 int loadAppendOnlyFile(char *filename
) {
7525 struct redisClient
*fakeClient
;
7526 FILE *fp
= fopen(filename
,"r");
7527 struct redis_stat sb
;
7528 unsigned long long loadedkeys
= 0;
7530 if (redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0)
7534 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
7538 fakeClient
= createFakeClient();
7545 struct redisCommand
*cmd
;
7547 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
7553 if (buf
[0] != '*') goto fmterr
;
7555 argv
= zmalloc(sizeof(robj
*)*argc
);
7556 for (j
= 0; j
< argc
; j
++) {
7557 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
7558 if (buf
[0] != '$') goto fmterr
;
7559 len
= strtol(buf
+1,NULL
,10);
7560 argsds
= sdsnewlen(NULL
,len
);
7561 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
7562 argv
[j
] = createObject(REDIS_STRING
,argsds
);
7563 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
7566 /* Command lookup */
7567 cmd
= lookupCommand(argv
[0]->ptr
);
7569 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
7572 /* Try object sharing and encoding */
7573 if (server
.shareobjects
) {
7575 for(j
= 1; j
< argc
; j
++)
7576 argv
[j
] = tryObjectSharing(argv
[j
]);
7578 if (cmd
->flags
& REDIS_CMD_BULK
)
7579 tryObjectEncoding(argv
[argc
-1]);
7580 /* Run the command in the context of a fake client */
7581 fakeClient
->argc
= argc
;
7582 fakeClient
->argv
= argv
;
7583 cmd
->proc(fakeClient
);
7584 /* Discard the reply objects list from the fake client */
7585 while(listLength(fakeClient
->reply
))
7586 listDelNode(fakeClient
->reply
,listFirst(fakeClient
->reply
));
7587 /* Clean up, ready for the next command */
7588 for (j
= 0; j
< argc
; j
++) decrRefCount(argv
[j
]);
7590 /* Handle swapping while loading big datasets when VM is on */
7592 if (server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
7593 while (zmalloc_used_memory() > server
.vm_max_memory
) {
7594 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
7599 freeFakeClient(fakeClient
);
7604 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
7606 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
7610 redisLog(REDIS_WARNING
,"Bad file format reading the append only file");
7614 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
7615 static int fwriteBulkObject(FILE *fp
, robj
*obj
) {
7619 /* Avoid the incr/decr ref count business if possible to help
7620 * copy-on-write (we are often in a child process when this function
7622 * Also makes sure that key objects don't get incrRefCount-ed when VM
7624 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
7625 obj
= getDecodedObject(obj
);
7628 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(long)sdslen(obj
->ptr
));
7629 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) goto err
;
7630 if (sdslen(obj
->ptr
) && fwrite(obj
->ptr
,sdslen(obj
->ptr
),1,fp
) == 0)
7632 if (fwrite("\r\n",2,1,fp
) == 0) goto err
;
7633 if (decrrc
) decrRefCount(obj
);
7636 if (decrrc
) decrRefCount(obj
);
7640 /* Write binary-safe string into a file in the bulkformat
7641 * $<count>\r\n<payload>\r\n */
7642 static int fwriteBulkString(FILE *fp
, char *s
, unsigned long len
) {
7645 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(unsigned long)len
);
7646 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
7647 if (len
&& fwrite(s
,len
,1,fp
) == 0) return 0;
7648 if (fwrite("\r\n",2,1,fp
) == 0) return 0;
7652 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
7653 static int fwriteBulkDouble(FILE *fp
, double d
) {
7654 char buf
[128], dbuf
[128];
7656 snprintf(dbuf
,sizeof(dbuf
),"%.17g\r\n",d
);
7657 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(dbuf
)-2);
7658 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
7659 if (fwrite(dbuf
,strlen(dbuf
),1,fp
) == 0) return 0;
7663 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
7664 static int fwriteBulkLong(FILE *fp
, long l
) {
7665 char buf
[128], lbuf
[128];
7667 snprintf(lbuf
,sizeof(lbuf
),"%ld\r\n",l
);
7668 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(lbuf
)-2);
7669 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
7670 if (fwrite(lbuf
,strlen(lbuf
),1,fp
) == 0) return 0;
7674 /* Write a sequence of commands able to fully rebuild the dataset into
7675 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
7676 static int rewriteAppendOnlyFile(char *filename
) {
7677 dictIterator
*di
= NULL
;
7682 time_t now
= time(NULL
);
7684 /* Note that we have to use a different temp name here compared to the
7685 * one used by rewriteAppendOnlyFileBackground() function. */
7686 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
7687 fp
= fopen(tmpfile
,"w");
7689 redisLog(REDIS_WARNING
, "Failed rewriting the append only file: %s", strerror(errno
));
7692 for (j
= 0; j
< server
.dbnum
; j
++) {
7693 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
7694 redisDb
*db
= server
.db
+j
;
7696 if (dictSize(d
) == 0) continue;
7697 di
= dictGetIterator(d
);
7703 /* SELECT the new DB */
7704 if (fwrite(selectcmd
,sizeof(selectcmd
)-1,1,fp
) == 0) goto werr
;
7705 if (fwriteBulkLong(fp
,j
) == 0) goto werr
;
7707 /* Iterate this DB writing every entry */
7708 while((de
= dictNext(di
)) != NULL
) {
7713 key
= dictGetEntryKey(de
);
7714 /* If the value for this key is swapped, load a preview in memory.
7715 * We use a "swapped" flag to remember if we need to free the
7716 * value object instead to just increment the ref count anyway
7717 * in order to avoid copy-on-write of pages if we are forked() */
7718 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
7719 key
->storage
== REDIS_VM_SWAPPING
) {
7720 o
= dictGetEntryVal(de
);
7723 o
= vmPreviewObject(key
);
7726 expiretime
= getExpire(db
,key
);
7728 /* Save the key and associated value */
7729 if (o
->type
== REDIS_STRING
) {
7730 /* Emit a SET command */
7731 char cmd
[]="*3\r\n$3\r\nSET\r\n";
7732 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7734 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
7735 if (fwriteBulkObject(fp
,o
) == 0) goto werr
;
7736 } else if (o
->type
== REDIS_LIST
) {
7737 /* Emit the RPUSHes needed to rebuild the list */
7738 list
*list
= o
->ptr
;
7742 listRewind(list
,&li
);
7743 while((ln
= listNext(&li
))) {
7744 char cmd
[]="*3\r\n$5\r\nRPUSH\r\n";
7745 robj
*eleobj
= listNodeValue(ln
);
7747 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7748 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
7749 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
7751 } else if (o
->type
== REDIS_SET
) {
7752 /* Emit the SADDs needed to rebuild the set */
7754 dictIterator
*di
= dictGetIterator(set
);
7757 while((de
= dictNext(di
)) != NULL
) {
7758 char cmd
[]="*3\r\n$4\r\nSADD\r\n";
7759 robj
*eleobj
= dictGetEntryKey(de
);
7761 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7762 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
7763 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
7765 dictReleaseIterator(di
);
7766 } else if (o
->type
== REDIS_ZSET
) {
7767 /* Emit the ZADDs needed to rebuild the sorted set */
7769 dictIterator
*di
= dictGetIterator(zs
->dict
);
7772 while((de
= dictNext(di
)) != NULL
) {
7773 char cmd
[]="*4\r\n$4\r\nZADD\r\n";
7774 robj
*eleobj
= dictGetEntryKey(de
);
7775 double *score
= dictGetEntryVal(de
);
7777 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7778 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
7779 if (fwriteBulkDouble(fp
,*score
) == 0) goto werr
;
7780 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
7782 dictReleaseIterator(di
);
7783 } else if (o
->type
== REDIS_HASH
) {
7784 char cmd
[]="*4\r\n$4\r\nHSET\r\n";
7786 /* Emit the HSETs needed to rebuild the hash */
7787 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
7788 unsigned char *p
= zipmapRewind(o
->ptr
);
7789 unsigned char *field
, *val
;
7790 unsigned int flen
, vlen
;
7792 while((p
= zipmapNext(p
,&field
,&flen
,&val
,&vlen
)) != NULL
) {
7793 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7794 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
7795 if (fwriteBulkString(fp
,(char*)field
,flen
) == -1)
7797 if (fwriteBulkString(fp
,(char*)val
,vlen
) == -1)
7801 dictIterator
*di
= dictGetIterator(o
->ptr
);
7804 while((de
= dictNext(di
)) != NULL
) {
7805 robj
*field
= dictGetEntryKey(de
);
7806 robj
*val
= dictGetEntryVal(de
);
7808 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7809 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
7810 if (fwriteBulkObject(fp
,field
) == -1) return -1;
7811 if (fwriteBulkObject(fp
,val
) == -1) return -1;
7813 dictReleaseIterator(di
);
7816 redisAssert(0 != 0);
7818 /* Save the expire time */
7819 if (expiretime
!= -1) {
7820 char cmd
[]="*3\r\n$8\r\nEXPIREAT\r\n";
7821 /* If this key is already expired skip it */
7822 if (expiretime
< now
) continue;
7823 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7824 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
7825 if (fwriteBulkLong(fp
,expiretime
) == 0) goto werr
;
7827 if (swapped
) decrRefCount(o
);
7829 dictReleaseIterator(di
);
7832 /* Make sure data will not remain on the OS's output buffers */
7837 /* Use RENAME to make sure the DB file is changed atomically only
7838 * if the generate DB file is ok. */
7839 if (rename(tmpfile
,filename
) == -1) {
7840 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
7844 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
7850 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
7851 if (di
) dictReleaseIterator(di
);
7855 /* This is how rewriting of the append only file in background works:
7857 * 1) The user calls BGREWRITEAOF
7858 * 2) Redis calls this function, that forks():
7859 * 2a) the child rewrite the append only file in a temp file.
7860 * 2b) the parent accumulates differences in server.bgrewritebuf.
7861 * 3) When the child finished '2a' exists.
7862 * 4) The parent will trap the exit code, if it's OK, will append the
7863 * data accumulated into server.bgrewritebuf into the temp file, and
7864 * finally will rename(2) the temp file in the actual file name.
7865 * The the new file is reopened as the new append only file. Profit!
7867 static int rewriteAppendOnlyFileBackground(void) {
7870 if (server
.bgrewritechildpid
!= -1) return REDIS_ERR
;
7871 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
7872 if ((childpid
= fork()) == 0) {
7876 if (server
.vm_enabled
) vmReopenSwapFile();
7878 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
7879 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
7886 if (childpid
== -1) {
7887 redisLog(REDIS_WARNING
,
7888 "Can't rewrite append only file in background: fork: %s",
7892 redisLog(REDIS_NOTICE
,
7893 "Background append only file rewriting started by pid %d",childpid
);
7894 server
.bgrewritechildpid
= childpid
;
7895 /* We set appendseldb to -1 in order to force the next call to the
7896 * feedAppendOnlyFile() to issue a SELECT command, so the differences
7897 * accumulated by the parent into server.bgrewritebuf will start
7898 * with a SELECT statement and it will be safe to merge. */
7899 server
.appendseldb
= -1;
7902 return REDIS_OK
; /* unreached */
7905 static void bgrewriteaofCommand(redisClient
*c
) {
7906 if (server
.bgrewritechildpid
!= -1) {
7907 addReplySds(c
,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
7910 if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
7911 char *status
= "+Background append only file rewriting started\r\n";
7912 addReplySds(c
,sdsnew(status
));
7914 addReply(c
,shared
.err
);
7918 static void aofRemoveTempFile(pid_t childpid
) {
7921 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
7925 /* Virtual Memory is composed mainly of two subsystems:
7926 * - Blocking Virutal Memory
7927 * - Threaded Virtual Memory I/O
7928 * The two parts are not fully decoupled, but functions are split among two
7929 * different sections of the source code (delimited by comments) in order to
7930 * make more clear what functionality is about the blocking VM and what about
7931 * the threaded (not blocking) VM.
7935 * Redis VM is a blocking VM (one that blocks reading swapped values from
7936 * disk into memory when a value swapped out is needed in memory) that is made
7937 * unblocking by trying to examine the command argument vector in order to
7938 * load in background values that will likely be needed in order to exec
7939 * the command. The command is executed only once all the relevant keys
7940 * are loaded into memory.
7942 * This basically is almost as simple of a blocking VM, but almost as parallel
7943 * as a fully non-blocking VM.
7946 /* =================== Virtual Memory - Blocking Side ====================== */
7948 /* substitute the first occurrence of '%p' with the process pid in the
7949 * swap file name. */
7950 static void expandVmSwapFilename(void) {
7951 char *p
= strstr(server
.vm_swap_file
,"%p");
7957 new = sdscat(new,server
.vm_swap_file
);
7958 new = sdscatprintf(new,"%ld",(long) getpid());
7959 new = sdscat(new,p
+2);
7960 zfree(server
.vm_swap_file
);
7961 server
.vm_swap_file
= new;
7964 static void vmInit(void) {
7969 if (server
.vm_max_threads
!= 0)
7970 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
7972 expandVmSwapFilename();
7973 redisLog(REDIS_NOTICE
,"Using '%s' as swap file",server
.vm_swap_file
);
7974 if ((server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b")) == NULL
) {
7975 server
.vm_fp
= fopen(server
.vm_swap_file
,"w+b");
7977 if (server
.vm_fp
== NULL
) {
7978 redisLog(REDIS_WARNING
,
7979 "Impossible to open the swap file: %s. Exiting.",
7983 server
.vm_fd
= fileno(server
.vm_fp
);
7984 server
.vm_next_page
= 0;
7985 server
.vm_near_pages
= 0;
7986 server
.vm_stats_used_pages
= 0;
7987 server
.vm_stats_swapped_objects
= 0;
7988 server
.vm_stats_swapouts
= 0;
7989 server
.vm_stats_swapins
= 0;
7990 totsize
= server
.vm_pages
*server
.vm_page_size
;
7991 redisLog(REDIS_NOTICE
,"Allocating %lld bytes of swap file",totsize
);
7992 if (ftruncate(server
.vm_fd
,totsize
) == -1) {
7993 redisLog(REDIS_WARNING
,"Can't ftruncate swap file: %s. Exiting.",
7997 redisLog(REDIS_NOTICE
,"Swap file allocated with success");
7999 server
.vm_bitmap
= zmalloc((server
.vm_pages
+7)/8);
8000 redisLog(REDIS_VERBOSE
,"Allocated %lld bytes page table for %lld pages",
8001 (long long) (server
.vm_pages
+7)/8, server
.vm_pages
);
8002 memset(server
.vm_bitmap
,0,(server
.vm_pages
+7)/8);
8004 /* Initialize threaded I/O (used by Virtual Memory) */
8005 server
.io_newjobs
= listCreate();
8006 server
.io_processing
= listCreate();
8007 server
.io_processed
= listCreate();
8008 server
.io_ready_clients
= listCreate();
8009 pthread_mutex_init(&server
.io_mutex
,NULL
);
8010 pthread_mutex_init(&server
.obj_freelist_mutex
,NULL
);
8011 pthread_mutex_init(&server
.io_swapfile_mutex
,NULL
);
8012 server
.io_active_threads
= 0;
8013 if (pipe(pipefds
) == -1) {
8014 redisLog(REDIS_WARNING
,"Unable to intialized VM: pipe(2): %s. Exiting."
8018 server
.io_ready_pipe_read
= pipefds
[0];
8019 server
.io_ready_pipe_write
= pipefds
[1];
8020 redisAssert(anetNonBlock(NULL
,server
.io_ready_pipe_read
) != ANET_ERR
);
8021 /* LZF requires a lot of stack */
8022 pthread_attr_init(&server
.io_threads_attr
);
8023 pthread_attr_getstacksize(&server
.io_threads_attr
, &stacksize
);
8024 while (stacksize
< REDIS_THREAD_STACK_SIZE
) stacksize
*= 2;
8025 pthread_attr_setstacksize(&server
.io_threads_attr
, stacksize
);
8026 /* Listen for events in the threaded I/O pipe */
8027 if (aeCreateFileEvent(server
.el
, server
.io_ready_pipe_read
, AE_READABLE
,
8028 vmThreadedIOCompletedJob
, NULL
) == AE_ERR
)
8029 oom("creating file event");
8032 /* Mark the page as used */
8033 static void vmMarkPageUsed(off_t page
) {
8034 off_t byte
= page
/8;
8036 redisAssert(vmFreePage(page
) == 1);
8037 server
.vm_bitmap
[byte
] |= 1<<bit
;
8040 /* Mark N contiguous pages as used, with 'page' being the first. */
8041 static void vmMarkPagesUsed(off_t page
, off_t count
) {
8044 for (j
= 0; j
< count
; j
++)
8045 vmMarkPageUsed(page
+j
);
8046 server
.vm_stats_used_pages
+= count
;
8047 redisLog(REDIS_DEBUG
,"Mark USED pages: %lld pages at %lld\n",
8048 (long long)count
, (long long)page
);
8051 /* Mark the page as free */
8052 static void vmMarkPageFree(off_t page
) {
8053 off_t byte
= page
/8;
8055 redisAssert(vmFreePage(page
) == 0);
8056 server
.vm_bitmap
[byte
] &= ~(1<<bit
);
8059 /* Mark N contiguous pages as free, with 'page' being the first. */
8060 static void vmMarkPagesFree(off_t page
, off_t count
) {
8063 for (j
= 0; j
< count
; j
++)
8064 vmMarkPageFree(page
+j
);
8065 server
.vm_stats_used_pages
-= count
;
8066 redisLog(REDIS_DEBUG
,"Mark FREE pages: %lld pages at %lld\n",
8067 (long long)count
, (long long)page
);
8070 /* Test if the page is free */
8071 static int vmFreePage(off_t page
) {
8072 off_t byte
= page
/8;
8074 return (server
.vm_bitmap
[byte
] & (1<<bit
)) == 0;
8077 /* Find N contiguous free pages storing the first page of the cluster in *first.
8078 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
8079 * REDIS_ERR is returned.
8081 * This function uses a simple algorithm: we try to allocate
8082 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
8083 * again from the start of the swap file searching for free spaces.
8085 * If it looks pretty clear that there are no free pages near our offset
8086 * we try to find less populated places doing a forward jump of
8087 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
8088 * without hurry, and then we jump again and so forth...
8090 * This function can be improved using a free list to avoid to guess
8091 * too much, since we could collect data about freed pages.
8093 * note: I implemented this function just after watching an episode of
8094 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
8096 static int vmFindContiguousPages(off_t
*first
, off_t n
) {
8097 off_t base
, offset
= 0, since_jump
= 0, numfree
= 0;
8099 if (server
.vm_near_pages
== REDIS_VM_MAX_NEAR_PAGES
) {
8100 server
.vm_near_pages
= 0;
8101 server
.vm_next_page
= 0;
8103 server
.vm_near_pages
++; /* Yet another try for pages near to the old ones */
8104 base
= server
.vm_next_page
;
8106 while(offset
< server
.vm_pages
) {
8107 off_t
this = base
+offset
;
8109 /* If we overflow, restart from page zero */
8110 if (this >= server
.vm_pages
) {
8111 this -= server
.vm_pages
;
8113 /* Just overflowed, what we found on tail is no longer
8114 * interesting, as it's no longer contiguous. */
8118 if (vmFreePage(this)) {
8119 /* This is a free page */
8121 /* Already got N free pages? Return to the caller, with success */
8123 *first
= this-(n
-1);
8124 server
.vm_next_page
= this+1;
8125 redisLog(REDIS_DEBUG
, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n
, (long long) *first
);
8129 /* The current one is not a free page */
8133 /* Fast-forward if the current page is not free and we already
8134 * searched enough near this place. */
8136 if (!numfree
&& since_jump
>= REDIS_VM_MAX_RANDOM_JUMP
/4) {
8137 offset
+= random() % REDIS_VM_MAX_RANDOM_JUMP
;
8139 /* Note that even if we rewind after the jump, we are don't need
8140 * to make sure numfree is set to zero as we only jump *if* it
8141 * is set to zero. */
8143 /* Otherwise just check the next page */
8150 /* Write the specified object at the specified page of the swap file */
8151 static int vmWriteObjectOnSwap(robj
*o
, off_t page
) {
8152 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
8153 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
8154 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
8155 redisLog(REDIS_WARNING
,
8156 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
8160 rdbSaveObject(server
.vm_fp
,o
);
8161 fflush(server
.vm_fp
);
8162 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
8166 /* Swap the 'val' object relative to 'key' into disk. Store all the information
8167 * needed to later retrieve the object into the key object.
8168 * If we can't find enough contiguous empty pages to swap the object on disk
8169 * REDIS_ERR is returned. */
8170 static int vmSwapObjectBlocking(robj
*key
, robj
*val
) {
8171 off_t pages
= rdbSavedObjectPages(val
,NULL
);
8174 assert(key
->storage
== REDIS_VM_MEMORY
);
8175 assert(key
->refcount
== 1);
8176 if (vmFindContiguousPages(&page
,pages
) == REDIS_ERR
) return REDIS_ERR
;
8177 if (vmWriteObjectOnSwap(val
,page
) == REDIS_ERR
) return REDIS_ERR
;
8178 key
->vm
.page
= page
;
8179 key
->vm
.usedpages
= pages
;
8180 key
->storage
= REDIS_VM_SWAPPED
;
8181 key
->vtype
= val
->type
;
8182 decrRefCount(val
); /* Deallocate the object from memory. */
8183 vmMarkPagesUsed(page
,pages
);
8184 redisLog(REDIS_DEBUG
,"VM: object %s swapped out at %lld (%lld pages)",
8185 (unsigned char*) key
->ptr
,
8186 (unsigned long long) page
, (unsigned long long) pages
);
8187 server
.vm_stats_swapped_objects
++;
8188 server
.vm_stats_swapouts
++;
8192 static robj
*vmReadObjectFromSwap(off_t page
, int type
) {
8195 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
8196 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
8197 redisLog(REDIS_WARNING
,
8198 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
8202 o
= rdbLoadObject(type
,server
.vm_fp
);
8204 redisLog(REDIS_WARNING
, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno
));
8207 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
8211 /* Load the value object relative to the 'key' object from swap to memory.
8212 * The newly allocated object is returned.
8214 * If preview is true the unserialized object is returned to the caller but
8215 * no changes are made to the key object, nor the pages are marked as freed */
8216 static robj
*vmGenericLoadObject(robj
*key
, int preview
) {
8219 redisAssert(key
->storage
== REDIS_VM_SWAPPED
|| key
->storage
== REDIS_VM_LOADING
);
8220 val
= vmReadObjectFromSwap(key
->vm
.page
,key
->vtype
);
8222 key
->storage
= REDIS_VM_MEMORY
;
8223 key
->vm
.atime
= server
.unixtime
;
8224 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
8225 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk",
8226 (unsigned char*) key
->ptr
);
8227 server
.vm_stats_swapped_objects
--;
8229 redisLog(REDIS_DEBUG
, "VM: object %s previewed from disk",
8230 (unsigned char*) key
->ptr
);
8232 server
.vm_stats_swapins
++;
8236 /* Plain object loading, from swap to memory */
8237 static robj
*vmLoadObject(robj
*key
) {
8238 /* If we are loading the object in background, stop it, we
8239 * need to load this object synchronously ASAP. */
8240 if (key
->storage
== REDIS_VM_LOADING
)
8241 vmCancelThreadedIOJob(key
);
8242 return vmGenericLoadObject(key
,0);
8245 /* Just load the value on disk, without to modify the key.
8246 * This is useful when we want to perform some operation on the value
8247 * without to really bring it from swap to memory, like while saving the
8248 * dataset or rewriting the append only log. */
8249 static robj
*vmPreviewObject(robj
*key
) {
8250 return vmGenericLoadObject(key
,1);
8253 /* How a good candidate is this object for swapping?
8254 * The better candidate it is, the greater the returned value.
8256 * Currently we try to perform a fast estimation of the object size in
8257 * memory, and combine it with aging informations.
8259 * Basically swappability = idle-time * log(estimated size)
8261 * Bigger objects are preferred over smaller objects, but not
8262 * proportionally, this is why we use the logarithm. This algorithm is
8263 * just a first try and will probably be tuned later. */
8264 static double computeObjectSwappability(robj
*o
) {
8265 time_t age
= server
.unixtime
- o
->vm
.atime
;
8269 struct dictEntry
*de
;
8272 if (age
<= 0) return 0;
8275 if (o
->encoding
!= REDIS_ENCODING_RAW
) {
8278 asize
= sdslen(o
->ptr
)+sizeof(*o
)+sizeof(long)*2;
8283 listNode
*ln
= listFirst(l
);
8285 asize
= sizeof(list
);
8287 robj
*ele
= ln
->value
;
8290 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
8291 (sizeof(*o
)+sdslen(ele
->ptr
)) :
8293 asize
+= (sizeof(listNode
)+elesize
)*listLength(l
);
8298 z
= (o
->type
== REDIS_ZSET
);
8299 d
= z
? ((zset
*)o
->ptr
)->dict
: o
->ptr
;
8301 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
8302 if (z
) asize
+= sizeof(zset
)-sizeof(dict
);
8307 de
= dictGetRandomKey(d
);
8308 ele
= dictGetEntryKey(de
);
8309 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
8310 (sizeof(*o
)+sdslen(ele
->ptr
)) :
8312 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
8313 if (z
) asize
+= sizeof(zskiplistNode
)*dictSize(d
);
8317 return (double)age
*log(1+asize
);
8320 /* Try to swap an object that's a good candidate for swapping.
8321 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
8322 * to swap any object at all.
8324 * If 'usethreaded' is true, Redis will try to swap the object in background
8325 * using I/O threads. */
8326 static int vmSwapOneObject(int usethreads
) {
8328 struct dictEntry
*best
= NULL
;
8329 double best_swappability
= 0;
8330 redisDb
*best_db
= NULL
;
8333 for (j
= 0; j
< server
.dbnum
; j
++) {
8334 redisDb
*db
= server
.db
+j
;
8335 /* Why maxtries is set to 100?
8336 * Because this way (usually) we'll find 1 object even if just 1% - 2%
8337 * are swappable objects */
8340 if (dictSize(db
->dict
) == 0) continue;
8341 for (i
= 0; i
< 5; i
++) {
8343 double swappability
;
8345 if (maxtries
) maxtries
--;
8346 de
= dictGetRandomKey(db
->dict
);
8347 key
= dictGetEntryKey(de
);
8348 val
= dictGetEntryVal(de
);
8349 /* Only swap objects that are currently in memory.
8351 * Also don't swap shared objects if threaded VM is on, as we
8352 * try to ensure that the main thread does not touch the
8353 * object while the I/O thread is using it, but we can't
8354 * control other keys without adding additional mutex. */
8355 if (key
->storage
!= REDIS_VM_MEMORY
||
8356 (server
.vm_max_threads
!= 0 && val
->refcount
!= 1)) {
8357 if (maxtries
) i
--; /* don't count this try */
8360 swappability
= computeObjectSwappability(val
);
8361 if (!best
|| swappability
> best_swappability
) {
8363 best_swappability
= swappability
;
8368 if (best
== NULL
) return REDIS_ERR
;
8369 key
= dictGetEntryKey(best
);
8370 val
= dictGetEntryVal(best
);
8372 redisLog(REDIS_DEBUG
,"Key with best swappability: %s, %f",
8373 key
->ptr
, best_swappability
);
8375 /* Unshare the key if needed */
8376 if (key
->refcount
> 1) {
8377 robj
*newkey
= dupStringObject(key
);
8379 key
= dictGetEntryKey(best
) = newkey
;
8383 vmSwapObjectThreaded(key
,val
,best_db
);
8386 if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
8387 dictGetEntryVal(best
) = NULL
;
8395 static int vmSwapOneObjectBlocking() {
8396 return vmSwapOneObject(0);
8399 static int vmSwapOneObjectThreaded() {
8400 return vmSwapOneObject(1);
8403 /* Return true if it's safe to swap out objects in a given moment.
8404 * Basically we don't want to swap objects out while there is a BGSAVE
8405 * or a BGAEOREWRITE running in backgroud. */
8406 static int vmCanSwapOut(void) {
8407 return (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1);
8410 /* Delete a key if swapped. Returns 1 if the key was found, was swapped
8411 * and was deleted. Otherwise 0 is returned. */
8412 static int deleteIfSwapped(redisDb
*db
, robj
*key
) {
8416 if ((de
= dictFind(db
->dict
,key
)) == NULL
) return 0;
8417 foundkey
= dictGetEntryKey(de
);
8418 if (foundkey
->storage
== REDIS_VM_MEMORY
) return 0;
8423 /* =================== Virtual Memory - Threaded I/O ======================= */
8425 static void freeIOJob(iojob
*j
) {
8426 if ((j
->type
== REDIS_IOJOB_PREPARE_SWAP
||
8427 j
->type
== REDIS_IOJOB_DO_SWAP
||
8428 j
->type
== REDIS_IOJOB_LOAD
) && j
->val
!= NULL
)
8429 decrRefCount(j
->val
);
8430 decrRefCount(j
->key
);
8434 /* Every time a thread finished a Job, it writes a byte into the write side
8435 * of an unix pipe in order to "awake" the main thread, and this function
8437 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
,
8441 int retval
, processed
= 0, toprocess
= -1, trytoswap
= 1;
8443 REDIS_NOTUSED(mask
);
8444 REDIS_NOTUSED(privdata
);
8446 /* For every byte we read in the read side of the pipe, there is one
8447 * I/O job completed to process. */
8448 while((retval
= read(fd
,buf
,1)) == 1) {
8452 struct dictEntry
*de
;
8454 redisLog(REDIS_DEBUG
,"Processing I/O completed job");
8456 /* Get the processed element (the oldest one) */
8458 assert(listLength(server
.io_processed
) != 0);
8459 if (toprocess
== -1) {
8460 toprocess
= (listLength(server
.io_processed
)*REDIS_MAX_COMPLETED_JOBS_PROCESSED
)/100;
8461 if (toprocess
<= 0) toprocess
= 1;
8463 ln
= listFirst(server
.io_processed
);
8465 listDelNode(server
.io_processed
,ln
);
8467 /* If this job is marked as canceled, just ignore it */
8472 /* Post process it in the main thread, as there are things we
8473 * can do just here to avoid race conditions and/or invasive locks */
8474 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
);
8475 de
= dictFind(j
->db
->dict
,j
->key
);
8477 key
= dictGetEntryKey(de
);
8478 if (j
->type
== REDIS_IOJOB_LOAD
) {
8481 /* Key loaded, bring it at home */
8482 key
->storage
= REDIS_VM_MEMORY
;
8483 key
->vm
.atime
= server
.unixtime
;
8484 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
8485 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk (threaded)",
8486 (unsigned char*) key
->ptr
);
8487 server
.vm_stats_swapped_objects
--;
8488 server
.vm_stats_swapins
++;
8489 dictGetEntryVal(de
) = j
->val
;
8490 incrRefCount(j
->val
);
8493 /* Handle clients waiting for this key to be loaded. */
8494 handleClientsBlockedOnSwappedKey(db
,key
);
8495 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
8496 /* Now we know the amount of pages required to swap this object.
8497 * Let's find some space for it, and queue this task again
8498 * rebranded as REDIS_IOJOB_DO_SWAP. */
8499 if (!vmCanSwapOut() ||
8500 vmFindContiguousPages(&j
->page
,j
->pages
) == REDIS_ERR
)
8502 /* Ooops... no space or we can't swap as there is
8503 * a fork()ed Redis trying to save stuff on disk. */
8505 key
->storage
= REDIS_VM_MEMORY
; /* undo operation */
8507 /* Note that we need to mark this pages as used now,
8508 * if the job will be canceled, we'll mark them as freed
8510 vmMarkPagesUsed(j
->page
,j
->pages
);
8511 j
->type
= REDIS_IOJOB_DO_SWAP
;
8516 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
8519 /* Key swapped. We can finally free some memory. */
8520 if (key
->storage
!= REDIS_VM_SWAPPING
) {
8521 printf("key->storage: %d\n",key
->storage
);
8522 printf("key->name: %s\n",(char*)key
->ptr
);
8523 printf("key->refcount: %d\n",key
->refcount
);
8524 printf("val: %p\n",(void*)j
->val
);
8525 printf("val->type: %d\n",j
->val
->type
);
8526 printf("val->ptr: %s\n",(char*)j
->val
->ptr
);
8528 redisAssert(key
->storage
== REDIS_VM_SWAPPING
);
8529 val
= dictGetEntryVal(de
);
8530 key
->vm
.page
= j
->page
;
8531 key
->vm
.usedpages
= j
->pages
;
8532 key
->storage
= REDIS_VM_SWAPPED
;
8533 key
->vtype
= j
->val
->type
;
8534 decrRefCount(val
); /* Deallocate the object from memory. */
8535 dictGetEntryVal(de
) = NULL
;
8536 redisLog(REDIS_DEBUG
,
8537 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
8538 (unsigned char*) key
->ptr
,
8539 (unsigned long long) j
->page
, (unsigned long long) j
->pages
);
8540 server
.vm_stats_swapped_objects
++;
8541 server
.vm_stats_swapouts
++;
8543 /* Put a few more swap requests in queue if we are still
8545 if (trytoswap
&& vmCanSwapOut() &&
8546 zmalloc_used_memory() > server
.vm_max_memory
)
8551 more
= listLength(server
.io_newjobs
) <
8552 (unsigned) server
.vm_max_threads
;
8554 /* Don't waste CPU time if swappable objects are rare. */
8555 if (vmSwapOneObjectThreaded() == REDIS_ERR
) {
8563 if (processed
== toprocess
) return;
8565 if (retval
< 0 && errno
!= EAGAIN
) {
8566 redisLog(REDIS_WARNING
,
8567 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
8572 static void lockThreadedIO(void) {
8573 pthread_mutex_lock(&server
.io_mutex
);
8576 static void unlockThreadedIO(void) {
8577 pthread_mutex_unlock(&server
.io_mutex
);
8580 /* Remove the specified object from the threaded I/O queue if still not
8581 * processed, otherwise make sure to flag it as canceled. */
8582 static void vmCancelThreadedIOJob(robj
*o
) {
8584 server
.io_newjobs
, /* 0 */
8585 server
.io_processing
, /* 1 */
8586 server
.io_processed
/* 2 */
8590 assert(o
->storage
== REDIS_VM_LOADING
|| o
->storage
== REDIS_VM_SWAPPING
);
8593 /* Search for a matching key in one of the queues */
8594 for (i
= 0; i
< 3; i
++) {
8598 listRewind(lists
[i
],&li
);
8599 while ((ln
= listNext(&li
)) != NULL
) {
8600 iojob
*job
= ln
->value
;
8602 if (job
->canceled
) continue; /* Skip this, already canceled. */
8603 if (compareStringObjects(job
->key
,o
) == 0) {
8604 redisLog(REDIS_DEBUG
,"*** CANCELED %p (%s) (type %d) (LIST ID %d)\n",
8605 (void*)job
, (char*)o
->ptr
, job
->type
, i
);
8606 /* Mark the pages as free since the swap didn't happened
8607 * or happened but is now discarded. */
8608 if (i
!= 1 && job
->type
== REDIS_IOJOB_DO_SWAP
)
8609 vmMarkPagesFree(job
->page
,job
->pages
);
8610 /* Cancel the job. It depends on the list the job is
8613 case 0: /* io_newjobs */
8614 /* If the job was yet not processed the best thing to do
8615 * is to remove it from the queue at all */
8617 listDelNode(lists
[i
],ln
);
8619 case 1: /* io_processing */
8620 /* Oh Shi- the thread is messing with the Job:
8622 * Probably it's accessing the object if this is a
8623 * PREPARE_SWAP or DO_SWAP job.
8624 * If it's a LOAD job it may be reading from disk and
8625 * if we don't wait for the job to terminate before to
8626 * cancel it, maybe in a few microseconds data can be
8627 * corrupted in this pages. So the short story is:
8629 * Better to wait for the job to move into the
8630 * next queue (processed)... */
8632 /* We try again and again until the job is completed. */
8634 /* But let's wait some time for the I/O thread
8635 * to finish with this job. After all this condition
8636 * should be very rare. */
8639 case 2: /* io_processed */
8640 /* The job was already processed, that's easy...
8641 * just mark it as canceled so that we'll ignore it
8642 * when processing completed jobs. */
8646 /* Finally we have to adjust the storage type of the object
8647 * in order to "UNDO" the operaiton. */
8648 if (o
->storage
== REDIS_VM_LOADING
)
8649 o
->storage
= REDIS_VM_SWAPPED
;
8650 else if (o
->storage
== REDIS_VM_SWAPPING
)
8651 o
->storage
= REDIS_VM_MEMORY
;
8658 assert(1 != 1); /* We should never reach this */
8661 static void *IOThreadEntryPoint(void *arg
) {
8666 pthread_detach(pthread_self());
8668 /* Get a new job to process */
8670 if (listLength(server
.io_newjobs
) == 0) {
8671 /* No new jobs in queue, exit. */
8672 redisLog(REDIS_DEBUG
,"Thread %ld exiting, nothing to do",
8673 (long) pthread_self());
8674 server
.io_active_threads
--;
8678 ln
= listFirst(server
.io_newjobs
);
8680 listDelNode(server
.io_newjobs
,ln
);
8681 /* Add the job in the processing queue */
8682 j
->thread
= pthread_self();
8683 listAddNodeTail(server
.io_processing
,j
);
8684 ln
= listLast(server
.io_processing
); /* We use ln later to remove it */
8686 redisLog(REDIS_DEBUG
,"Thread %ld got a new job (type %d): %p about key '%s'",
8687 (long) pthread_self(), j
->type
, (void*)j
, (char*)j
->key
->ptr
);
8689 /* Process the Job */
8690 if (j
->type
== REDIS_IOJOB_LOAD
) {
8691 j
->val
= vmReadObjectFromSwap(j
->page
,j
->key
->vtype
);
8692 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
8693 FILE *fp
= fopen("/dev/null","w+");
8694 j
->pages
= rdbSavedObjectPages(j
->val
,fp
);
8696 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
8697 if (vmWriteObjectOnSwap(j
->val
,j
->page
) == REDIS_ERR
)
8701 /* Done: insert the job into the processed queue */
8702 redisLog(REDIS_DEBUG
,"Thread %ld completed the job: %p (key %s)",
8703 (long) pthread_self(), (void*)j
, (char*)j
->key
->ptr
);
8705 listDelNode(server
.io_processing
,ln
);
8706 listAddNodeTail(server
.io_processed
,j
);
8709 /* Signal the main thread there is new stuff to process */
8710 assert(write(server
.io_ready_pipe_write
,"x",1) == 1);
8712 return NULL
; /* never reached */
8715 static void spawnIOThread(void) {
8717 sigset_t mask
, omask
;
8720 sigaddset(&mask
,SIGCHLD
);
8721 sigaddset(&mask
,SIGHUP
);
8722 sigaddset(&mask
,SIGPIPE
);
8723 pthread_sigmask(SIG_SETMASK
, &mask
, &omask
);
8724 pthread_create(&thread
,&server
.io_threads_attr
,IOThreadEntryPoint
,NULL
);
8725 pthread_sigmask(SIG_SETMASK
, &omask
, NULL
);
8726 server
.io_active_threads
++;
8729 /* We need to wait for the last thread to exit before we are able to
8730 * fork() in order to BGSAVE or BGREWRITEAOF. */
8731 static void waitEmptyIOJobsQueue(void) {
8733 int io_processed_len
;
8736 if (listLength(server
.io_newjobs
) == 0 &&
8737 listLength(server
.io_processing
) == 0 &&
8738 server
.io_active_threads
== 0)
8743 /* While waiting for empty jobs queue condition we post-process some
8744 * finshed job, as I/O threads may be hanging trying to write against
8745 * the io_ready_pipe_write FD but there are so much pending jobs that
8747 io_processed_len
= listLength(server
.io_processed
);
8749 if (io_processed_len
) {
8750 vmThreadedIOCompletedJob(NULL
,server
.io_ready_pipe_read
,NULL
,0);
8751 usleep(1000); /* 1 millisecond */
8753 usleep(10000); /* 10 milliseconds */
8758 static void vmReopenSwapFile(void) {
8759 /* Note: we don't close the old one as we are in the child process
8760 * and don't want to mess at all with the original file object. */
8761 server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b");
8762 if (server
.vm_fp
== NULL
) {
8763 redisLog(REDIS_WARNING
,"Can't re-open the VM swap file: %s. Exiting.",
8764 server
.vm_swap_file
);
8767 server
.vm_fd
= fileno(server
.vm_fp
);
8770 /* This function must be called while with threaded IO locked */
8771 static void queueIOJob(iojob
*j
) {
8772 redisLog(REDIS_DEBUG
,"Queued IO Job %p type %d about key '%s'\n",
8773 (void*)j
, j
->type
, (char*)j
->key
->ptr
);
8774 listAddNodeTail(server
.io_newjobs
,j
);
8775 if (server
.io_active_threads
< server
.vm_max_threads
)
8779 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
) {
8782 assert(key
->storage
== REDIS_VM_MEMORY
);
8783 assert(key
->refcount
== 1);
8785 j
= zmalloc(sizeof(*j
));
8786 j
->type
= REDIS_IOJOB_PREPARE_SWAP
;
8788 j
->key
= dupStringObject(key
);
8792 j
->thread
= (pthread_t
) -1;
8793 key
->storage
= REDIS_VM_SWAPPING
;
8801 /* ============ Virtual Memory - Blocking clients on missing keys =========== */
8803 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
8804 * If there is not already a job loading the key, it is craeted.
8805 * The key is added to the io_keys list in the client structure, and also
8806 * in the hash table mapping swapped keys to waiting clients, that is,
8807 * server.io_waited_keys. */
8808 static int waitForSwappedKey(redisClient
*c
, robj
*key
) {
8809 struct dictEntry
*de
;
8813 /* If the key does not exist or is already in RAM we don't need to
8814 * block the client at all. */
8815 de
= dictFind(c
->db
->dict
,key
);
8816 if (de
== NULL
) return 0;
8817 o
= dictGetEntryKey(de
);
8818 if (o
->storage
== REDIS_VM_MEMORY
) {
8820 } else if (o
->storage
== REDIS_VM_SWAPPING
) {
8821 /* We were swapping the key, undo it! */
8822 vmCancelThreadedIOJob(o
);
8826 /* OK: the key is either swapped, or being loaded just now. */
8828 /* Add the key to the list of keys this client is waiting for.
8829 * This maps clients to keys they are waiting for. */
8830 listAddNodeTail(c
->io_keys
,key
);
8833 /* Add the client to the swapped keys => clients waiting map. */
8834 de
= dictFind(c
->db
->io_keys
,key
);
8838 /* For every key we take a list of clients blocked for it */
8840 retval
= dictAdd(c
->db
->io_keys
,key
,l
);
8842 assert(retval
== DICT_OK
);
8844 l
= dictGetEntryVal(de
);
8846 listAddNodeTail(l
,c
);
8848 /* Are we already loading the key from disk? If not create a job */
8849 if (o
->storage
== REDIS_VM_SWAPPED
) {
8852 o
->storage
= REDIS_VM_LOADING
;
8853 j
= zmalloc(sizeof(*j
));
8854 j
->type
= REDIS_IOJOB_LOAD
;
8856 j
->key
= dupStringObject(key
);
8857 j
->key
->vtype
= o
->vtype
;
8858 j
->page
= o
->vm
.page
;
8861 j
->thread
= (pthread_t
) -1;
8869 /* Is this client attempting to run a command against swapped keys?
8870 * If so, block it ASAP, load the keys in background, then resume it.
8872 * The important idea about this function is that it can fail! If keys will
8873 * still be swapped when the client is resumed, this key lookups will
8874 * just block loading keys from disk. In practical terms this should only
8875 * happen with SORT BY command or if there is a bug in this function.
8877 * Return 1 if the client is marked as blocked, 0 if the client can
8878 * continue as the keys it is going to access appear to be in memory. */
8879 static int blockClientOnSwappedKeys(struct redisCommand
*cmd
, redisClient
*c
) {
8882 if (cmd
->vm_firstkey
== 0) return 0;
8883 last
= cmd
->vm_lastkey
;
8884 if (last
< 0) last
= c
->argc
+last
;
8885 for (j
= cmd
->vm_firstkey
; j
<= last
; j
+= cmd
->vm_keystep
)
8886 waitForSwappedKey(c
,c
->argv
[j
]);
8887 /* If the client was blocked for at least one key, mark it as blocked. */
8888 if (listLength(c
->io_keys
)) {
8889 c
->flags
|= REDIS_IO_WAIT
;
8890 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
8891 server
.vm_blocked_clients
++;
8898 /* Remove the 'key' from the list of blocked keys for a given client.
8900 * The function returns 1 when there are no longer blocking keys after
8901 * the current one was removed (and the client can be unblocked). */
8902 static int dontWaitForSwappedKey(redisClient
*c
, robj
*key
) {
8906 struct dictEntry
*de
;
8908 /* Remove the key from the list of keys this client is waiting for. */
8909 listRewind(c
->io_keys
,&li
);
8910 while ((ln
= listNext(&li
)) != NULL
) {
8911 if (compareStringObjects(ln
->value
,key
) == 0) {
8912 listDelNode(c
->io_keys
,ln
);
8918 /* Remove the client form the key => waiting clients map. */
8919 de
= dictFind(c
->db
->io_keys
,key
);
8921 l
= dictGetEntryVal(de
);
8922 ln
= listSearchKey(l
,c
);
8925 if (listLength(l
) == 0)
8926 dictDelete(c
->db
->io_keys
,key
);
8928 return listLength(c
->io_keys
) == 0;
8931 static void handleClientsBlockedOnSwappedKey(redisDb
*db
, robj
*key
) {
8932 struct dictEntry
*de
;
8937 de
= dictFind(db
->io_keys
,key
);
8940 l
= dictGetEntryVal(de
);
8941 len
= listLength(l
);
8942 /* Note: we can't use something like while(listLength(l)) as the list
8943 * can be freed by the calling function when we remove the last element. */
8946 redisClient
*c
= ln
->value
;
8948 if (dontWaitForSwappedKey(c
,key
)) {
8949 /* Put the client in the list of clients ready to go as we
8950 * loaded all the keys about it. */
8951 listAddNodeTail(server
.io_ready_clients
,c
);
8956 /* ================================= Debugging ============================== */
8958 static void debugCommand(redisClient
*c
) {
8959 if (!strcasecmp(c
->argv
[1]->ptr
,"segfault")) {
8961 } else if (!strcasecmp(c
->argv
[1]->ptr
,"reload")) {
8962 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
8963 addReply(c
,shared
.err
);
8967 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
8968 addReply(c
,shared
.err
);
8971 redisLog(REDIS_WARNING
,"DB reloaded by DEBUG RELOAD");
8972 addReply(c
,shared
.ok
);
8973 } else if (!strcasecmp(c
->argv
[1]->ptr
,"loadaof")) {
8975 if (loadAppendOnlyFile(server
.appendfilename
) != REDIS_OK
) {
8976 addReply(c
,shared
.err
);
8979 redisLog(REDIS_WARNING
,"Append Only File loaded by DEBUG LOADAOF");
8980 addReply(c
,shared
.ok
);
8981 } else if (!strcasecmp(c
->argv
[1]->ptr
,"object") && c
->argc
== 3) {
8982 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
8986 addReply(c
,shared
.nokeyerr
);
8989 key
= dictGetEntryKey(de
);
8990 val
= dictGetEntryVal(de
);
8991 if (!server
.vm_enabled
|| (key
->storage
== REDIS_VM_MEMORY
||
8992 key
->storage
== REDIS_VM_SWAPPING
)) {
8996 if (val
->encoding
< (sizeof(strencoding
)/sizeof(char*))) {
8997 strenc
= strencoding
[val
->encoding
];
8999 snprintf(buf
,64,"unknown encoding %d\n", val
->encoding
);
9002 addReplySds(c
,sdscatprintf(sdsempty(),
9003 "+Key at:%p refcount:%d, value at:%p refcount:%d "
9004 "encoding:%s serializedlength:%lld\r\n",
9005 (void*)key
, key
->refcount
, (void*)val
, val
->refcount
,
9006 strenc
, (long long) rdbSavedObjectLen(val
,NULL
)));
9008 addReplySds(c
,sdscatprintf(sdsempty(),
9009 "+Key at:%p refcount:%d, value swapped at: page %llu "
9010 "using %llu pages\r\n",
9011 (void*)key
, key
->refcount
, (unsigned long long) key
->vm
.page
,
9012 (unsigned long long) key
->vm
.usedpages
));
9014 } else if (!strcasecmp(c
->argv
[1]->ptr
,"swapout") && c
->argc
== 3) {
9015 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
9018 if (!server
.vm_enabled
) {
9019 addReplySds(c
,sdsnew("-ERR Virtual Memory is disabled\r\n"));
9023 addReply(c
,shared
.nokeyerr
);
9026 key
= dictGetEntryKey(de
);
9027 val
= dictGetEntryVal(de
);
9028 /* If the key is shared we want to create a copy */
9029 if (key
->refcount
> 1) {
9030 robj
*newkey
= dupStringObject(key
);
9032 key
= dictGetEntryKey(de
) = newkey
;
9035 if (key
->storage
!= REDIS_VM_MEMORY
) {
9036 addReplySds(c
,sdsnew("-ERR This key is not in memory\r\n"));
9037 } else if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
9038 dictGetEntryVal(de
) = NULL
;
9039 addReply(c
,shared
.ok
);
9041 addReply(c
,shared
.err
);
9044 addReplySds(c
,sdsnew(
9045 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPOUT <key>|RELOAD]\r\n"));
9049 static void _redisAssert(char *estr
, char *file
, int line
) {
9050 redisLog(REDIS_WARNING
,"=== ASSERTION FAILED ===");
9051 redisLog(REDIS_WARNING
,"==> %s:%d '%s' is not true\n",file
,line
,estr
);
9052 #ifdef HAVE_BACKTRACE
9053 redisLog(REDIS_WARNING
,"(forcing SIGSEGV in order to print the stack trace)");
9058 /* =================================== Main! ================================ */
9061 int linuxOvercommitMemoryValue(void) {
9062 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
9066 if (fgets(buf
,64,fp
) == NULL
) {
9075 void linuxOvercommitMemoryWarning(void) {
9076 if (linuxOvercommitMemoryValue() == 0) {
9077 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.");
9080 #endif /* __linux__ */
9082 static void daemonize(void) {
9086 if (fork() != 0) exit(0); /* parent exits */
9087 setsid(); /* create a new session */
9089 /* Every output goes to /dev/null. If Redis is daemonized but
9090 * the 'logfile' is set to 'stdout' in the configuration file
9091 * it will not log at all. */
9092 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
9093 dup2(fd
, STDIN_FILENO
);
9094 dup2(fd
, STDOUT_FILENO
);
9095 dup2(fd
, STDERR_FILENO
);
9096 if (fd
> STDERR_FILENO
) close(fd
);
9098 /* Try to write the pid file */
9099 fp
= fopen(server
.pidfile
,"w");
9101 fprintf(fp
,"%d\n",getpid());
9106 int main(int argc
, char **argv
) {
9111 resetServerSaveParams();
9112 loadServerConfig(argv
[1]);
9113 } else if (argc
> 2) {
9114 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
9117 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'");
9119 if (server
.daemonize
) daemonize();
9121 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
9123 linuxOvercommitMemoryWarning();
9126 if (server
.appendonly
) {
9127 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
9128 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %ld seconds",time(NULL
)-start
);
9130 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
9131 redisLog(REDIS_NOTICE
,"DB loaded from disk: %ld seconds",time(NULL
)-start
);
9133 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
9134 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
9136 aeDeleteEventLoop(server
.el
);
9140 /* ============================= Backtrace support ========================= */
9142 #ifdef HAVE_BACKTRACE
9143 static char *findFuncName(void *pointer
, unsigned long *offset
);
9145 static void *getMcontextEip(ucontext_t
*uc
) {
9146 #if defined(__FreeBSD__)
9147 return (void*) uc
->uc_mcontext
.mc_eip
;
9148 #elif defined(__dietlibc__)
9149 return (void*) uc
->uc_mcontext
.eip
;
9150 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
9152 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
9154 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
9156 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
9157 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
9158 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
9160 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
9162 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
9163 return (void*) uc
->uc_mcontext
.gregs
[REG_EIP
]; /* Linux 32/64 bit */
9164 #elif defined(__ia64__) /* Linux IA64 */
9165 return (void*) uc
->uc_mcontext
.sc_ip
;
9171 static void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
9173 char **messages
= NULL
;
9174 int i
, trace_size
= 0;
9175 unsigned long offset
=0;
9176 ucontext_t
*uc
= (ucontext_t
*) secret
;
9178 REDIS_NOTUSED(info
);
9180 redisLog(REDIS_WARNING
,
9181 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
9182 infostring
= genRedisInfoString();
9183 redisLog(REDIS_WARNING
, "%s",infostring
);
9184 /* It's not safe to sdsfree() the returned string under memory
9185 * corruption conditions. Let it leak as we are going to abort */
9187 trace_size
= backtrace(trace
, 100);
9188 /* overwrite sigaction with caller's address */
9189 if (getMcontextEip(uc
) != NULL
) {
9190 trace
[1] = getMcontextEip(uc
);
9192 messages
= backtrace_symbols(trace
, trace_size
);
9194 for (i
=1; i
<trace_size
; ++i
) {
9195 char *fn
= findFuncName(trace
[i
], &offset
), *p
;
9197 p
= strchr(messages
[i
],'+');
9198 if (!fn
|| (p
&& ((unsigned long)strtol(p
+1,NULL
,10)) < offset
)) {
9199 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
9201 redisLog(REDIS_WARNING
,"%d redis-server %p %s + %d", i
, trace
[i
], fn
, (unsigned int)offset
);
9204 /* free(messages); Don't call free() with possibly corrupted memory. */
9208 static void setupSigSegvAction(void) {
9209 struct sigaction act
;
9211 sigemptyset (&act
.sa_mask
);
9212 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
9213 * is used. Otherwise, sa_handler is used */
9214 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
9215 act
.sa_sigaction
= segvHandler
;
9216 sigaction (SIGSEGV
, &act
, NULL
);
9217 sigaction (SIGBUS
, &act
, NULL
);
9218 sigaction (SIGFPE
, &act
, NULL
);
9219 sigaction (SIGILL
, &act
, NULL
);
9220 sigaction (SIGBUS
, &act
, NULL
);
9224 #include "staticsymbols.h"
9225 /* This function try to convert a pointer into a function name. It's used in
9226 * oreder to provide a backtrace under segmentation fault that's able to
9227 * display functions declared as static (otherwise the backtrace is useless). */
9228 static char *findFuncName(void *pointer
, unsigned long *offset
){
9230 unsigned long off
, minoff
= 0;
9232 /* Try to match against the Symbol with the smallest offset */
9233 for (i
=0; symsTable
[i
].pointer
; i
++) {
9234 unsigned long lp
= (unsigned long) pointer
;
9236 if (lp
!= (unsigned long)-1 && lp
>= symsTable
[i
].pointer
) {
9237 off
=lp
-symsTable
[i
].pointer
;
9238 if (ret
< 0 || off
< minoff
) {
9244 if (ret
== -1) return NULL
;
9246 return symsTable
[ret
].name
;
9248 #else /* HAVE_BACKTRACE */
9249 static void setupSigSegvAction(void) {
9251 #endif /* HAVE_BACKTRACE */