2 * Copyright (c) 2006-2009, 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.2"
40 #define __USE_POSIX199309
46 #endif /* HAVE_BACKTRACE */
54 #include <arpa/inet.h>
58 #include <sys/resource.h>
65 #include "solarisfixes.h"
69 #include "ae.h" /* Event driven programming library */
70 #include "sds.h" /* Dynamic safe strings */
71 #include "anet.h" /* Networking the easy way */
72 #include "dict.h" /* Hash tables */
73 #include "adlist.h" /* Linked lists */
74 #include "zmalloc.h" /* total memory usage aware version of malloc/free */
75 #include "lzf.h" /* LZF compression library */
76 #include "pqsort.h" /* Partial qsort for SORT+LIMIT */
78 /* #define REDIS_HELGRIND_FRIENDLY */
79 #if defined(__GNUC__) && defined(REDIS_HELGRIND_FRIENDLY)
80 #warning "Remember to undef REDIS_HELGRIND_FRIENDLY before to commit"
87 /* Static server configuration */
88 #define REDIS_SERVERPORT 6379 /* TCP port */
89 #define REDIS_MAXIDLETIME (60*5) /* default client timeout */
90 #define REDIS_IOBUF_LEN 1024
91 #define REDIS_LOADBUF_LEN 1024
92 #define REDIS_STATIC_ARGS 4
93 #define REDIS_DEFAULT_DBNUM 16
94 #define REDIS_CONFIGLINE_MAX 1024
95 #define REDIS_OBJFREELIST_MAX 1000000 /* Max number of objects to cache */
96 #define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
97 #define REDIS_EXPIRELOOKUPS_PER_CRON 100 /* try to expire 100 keys/second */
98 #define REDIS_MAX_WRITE_PER_EVENT (1024*64)
99 #define REDIS_REQUEST_MAX_SIZE (1024*1024*256) /* max bytes in inline command */
101 /* If more then REDIS_WRITEV_THRESHOLD write packets are pending use writev */
102 #define REDIS_WRITEV_THRESHOLD 3
103 /* Max number of iovecs used for each writev call */
104 #define REDIS_WRITEV_IOVEC_COUNT 256
106 /* Hash table parameters */
107 #define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
110 #define REDIS_CMD_BULK 1 /* Bulk write command */
111 #define REDIS_CMD_INLINE 2 /* Inline command */
112 /* REDIS_CMD_DENYOOM reserves a longer comment: all the commands marked with
113 this flags will return an error when the 'maxmemory' option is set in the
114 config file and the server is using more than maxmemory bytes of memory.
115 In short this commands are denied on low memory conditions. */
116 #define REDIS_CMD_DENYOOM 4
119 #define REDIS_STRING 0
125 /* Objects encoding */
126 #define REDIS_ENCODING_RAW 0 /* Raw representation */
127 #define REDIS_ENCODING_INT 1 /* Encoded as integer */
129 /* Object types only used for dumping to disk */
130 #define REDIS_EXPIRETIME 253
131 #define REDIS_SELECTDB 254
132 #define REDIS_EOF 255
134 /* Defines related to the dump file format. To store 32 bits lengths for short
135 * keys requires a lot of space, so we check the most significant 2 bits of
136 * the first byte to interpreter the length:
138 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
139 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
140 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
141 * 11|000000 this means: specially encoded object will follow. The six bits
142 * number specify the kind of object that follows.
143 * See the REDIS_RDB_ENC_* defines.
145 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
146 * values, will fit inside. */
147 #define REDIS_RDB_6BITLEN 0
148 #define REDIS_RDB_14BITLEN 1
149 #define REDIS_RDB_32BITLEN 2
150 #define REDIS_RDB_ENCVAL 3
151 #define REDIS_RDB_LENERR UINT_MAX
153 /* When a length of a string object stored on disk has the first two bits
154 * set, the remaining two bits specify a special encoding for the object
155 * accordingly to the following defines: */
156 #define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
157 #define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
158 #define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
159 #define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
161 /* Virtual memory object->where field. */
162 #define REDIS_VM_MEMORY 0 /* The object is on memory */
163 #define REDIS_VM_SWAPPED 1 /* The object is on disk */
164 #define REDIS_VM_SWAPPING 2 /* Redis is swapping this object on disk */
165 #define REDIS_VM_LOADING 3 /* Redis is loading this object from disk */
167 /* Virtual memory static configuration stuff.
168 * Check vmFindContiguousPages() to know more about this magic numbers. */
169 #define REDIS_VM_MAX_NEAR_PAGES 65536
170 #define REDIS_VM_MAX_RANDOM_JUMP 4096
171 #define REDIS_VM_MAX_THREADS 32
172 #define REDIS_THREAD_STACK_SIZE (1024*1024*4)
173 /* The following is the number of completed I/O jobs to process when the
174 * handelr is called. 1 is the minimum, and also the default, as it allows
175 * to block as little as possible other accessing clients. While Virtual
176 * Memory I/O operations are performed by threads, this operations must
177 * be processed by the main thread when completed to take effect. */
178 #define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
181 #define REDIS_CLOSE 1 /* This client connection should be closed ASAP */
182 #define REDIS_SLAVE 2 /* This client is a slave server */
183 #define REDIS_MASTER 4 /* This client is a master server */
184 #define REDIS_MONITOR 8 /* This client is a slave monitor, see MONITOR */
185 #define REDIS_MULTI 16 /* This client is in a MULTI context */
186 #define REDIS_BLOCKED 32 /* The client is waiting in a blocking operation */
187 #define REDIS_IO_WAIT 64 /* The client is waiting for Virtual Memory I/O */
189 /* Slave replication state - slave side */
190 #define REDIS_REPL_NONE 0 /* No active replication */
191 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
192 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
194 /* Slave replication state - from the point of view of master
195 * Note that in SEND_BULK and ONLINE state the slave receives new updates
196 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
197 * to start the next background saving in order to send updates to it. */
198 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
199 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
200 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
201 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
203 /* List related stuff */
207 /* Sort operations */
208 #define REDIS_SORT_GET 0
209 #define REDIS_SORT_ASC 1
210 #define REDIS_SORT_DESC 2
211 #define REDIS_SORTKEY_MAX 1024
214 #define REDIS_DEBUG 0
215 #define REDIS_VERBOSE 1
216 #define REDIS_NOTICE 2
217 #define REDIS_WARNING 3
219 /* Anti-warning macro... */
220 #define REDIS_NOTUSED(V) ((void) V)
222 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
223 #define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
225 /* Append only defines */
226 #define APPENDFSYNC_NO 0
227 #define APPENDFSYNC_ALWAYS 1
228 #define APPENDFSYNC_EVERYSEC 2
230 /* We can print the stacktrace, so our assert is defined this way: */
231 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),exit(1)))
232 static void _redisAssert(char *estr
, char *file
, int line
);
234 /*================================= Data types ============================== */
236 /* A redis object, that is a type able to hold a string / list / set */
238 /* The VM object structure */
239 struct redisObjectVM
{
240 off_t page
; /* the page at witch the object is stored on disk */
241 off_t usedpages
; /* number of pages used on disk */
242 time_t atime
; /* Last access time */
245 /* The actual Redis Object */
246 typedef struct redisObject
{
249 unsigned char encoding
;
250 unsigned char storage
; /* If this object is a key, where is the value?
251 * REDIS_VM_MEMORY, REDIS_VM_SWAPPED, ... */
252 unsigned char vtype
; /* If this object is a key, and value is swapped out,
253 * this is the type of the swapped out object. */
255 /* VM fields, this are only allocated if VM is active, otherwise the
256 * object allocation function will just allocate
257 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
258 * Redis without VM active will not have any overhead. */
259 struct redisObjectVM vm
;
262 /* Macro used to initalize a Redis object allocated on the stack.
263 * Note that this macro is taken near the structure definition to make sure
264 * we'll update it when the structure is changed, to avoid bugs like
265 * bug #85 introduced exactly in this way. */
266 #define initStaticStringObject(_var,_ptr) do { \
268 _var.type = REDIS_STRING; \
269 _var.encoding = REDIS_ENCODING_RAW; \
271 if (server.vm_enabled) _var.storage = REDIS_VM_MEMORY; \
274 typedef struct redisDb
{
275 dict
*dict
; /* The keyspace for this DB */
276 dict
*expires
; /* Timeout of keys with a timeout set */
277 dict
*blockingkeys
; /* Keys with clients waiting for data (BLPOP) */
281 /* Client MULTI/EXEC state */
282 typedef struct multiCmd
{
285 struct redisCommand
*cmd
;
288 typedef struct multiState
{
289 multiCmd
*commands
; /* Array of MULTI commands */
290 int count
; /* Total number of MULTI commands */
293 /* With multiplexing we need to take per-clinet state.
294 * Clients are taken in a liked list. */
295 typedef struct redisClient
{
300 robj
**argv
, **mbargv
;
302 int bulklen
; /* bulk read len. -1 if not in bulk read mode */
303 int multibulk
; /* multi bulk command format active */
306 time_t lastinteraction
; /* time of the last interaction, used for timeout */
307 int flags
; /* REDIS_CLOSE | REDIS_SLAVE | REDIS_MONITOR */
309 int slaveseldb
; /* slave selected db, if this client is a slave */
310 int authenticated
; /* when requirepass is non-NULL */
311 int replstate
; /* replication state if this is a slave */
312 int repldbfd
; /* replication DB file descriptor */
313 long repldboff
; /* replication DB file offset */
314 off_t repldbsize
; /* replication DB file size */
315 multiState mstate
; /* MULTI/EXEC state */
316 robj
**blockingkeys
; /* The key we waiting to terminate a blocking
317 * operation such as BLPOP. Otherwise NULL. */
318 int blockingkeysnum
; /* Number of blocking keys */
319 time_t blockingto
; /* Blocking operation timeout. If UNIX current time
320 * is >= blockingto then the operation timed out. */
321 list
*io_keys
; /* Keys this client is waiting to be loaded from the
322 * swap file in order to continue. */
330 /* Global server state structure */
335 dict
*sharingpool
; /* Poll used for object sharing */
336 unsigned int sharingpoolsize
;
337 long long dirty
; /* changes to DB from the last save */
339 list
*slaves
, *monitors
;
340 char neterr
[ANET_ERR_LEN
];
342 int cronloops
; /* number of times the cron function run */
343 list
*objfreelist
; /* A list of freed objects to avoid malloc() */
344 time_t lastsave
; /* Unix time of last save succeeede */
345 size_t usedmemory
; /* Used memory in megabytes */
346 /* Fields used only for stats */
347 time_t stat_starttime
; /* server start time */
348 long long stat_numcommands
; /* number of processed commands */
349 long long stat_numconnections
; /* number of connections received */
362 pid_t bgsavechildpid
;
363 pid_t bgrewritechildpid
;
364 sds bgrewritebuf
; /* buffer taken by parent during oppend only rewrite */
365 struct saveparam
*saveparams
;
370 char *appendfilename
;
374 /* Replication related */
379 redisClient
*master
; /* client that is master for this slave */
381 unsigned int maxclients
;
382 unsigned long long maxmemory
;
383 unsigned int blockedclients
;
384 /* Sort parameters - qsort_r() is only available under BSD so we
385 * have to take this state global, in order to pass it to sortCompare() */
389 /* Virtual memory configuration */
393 unsigned long long vm_max_memory
;
394 /* Virtual memory state */
397 off_t vm_next_page
; /* Next probably empty page */
398 off_t vm_near_pages
; /* Number of pages allocated sequentially */
399 unsigned char *vm_bitmap
; /* Bitmap of free/used pages */
400 time_t unixtime
; /* Unix time sampled every second. */
401 /* Virtual memory I/O threads stuff */
402 /* An I/O thread process an element taken from the io_jobs queue and
403 * put the result of the operation in the io_done list. While the
404 * job is being processed, it's put on io_processing queue. */
405 list
*io_newjobs
; /* List of VM I/O jobs yet to be processed */
406 list
*io_processing
; /* List of VM I/O jobs being processed */
407 list
*io_processed
; /* List of VM I/O jobs already processed */
408 list
*io_clients
; /* All the clients waiting for SWAP I/O operations */
409 pthread_mutex_t io_mutex
; /* lock to access io_jobs/io_done/io_thread_job */
410 pthread_mutex_t obj_freelist_mutex
; /* safe redis objects creation/free */
411 pthread_mutex_t io_swapfile_mutex
; /* So we can lseek + write */
412 pthread_attr_t io_threads_attr
; /* attributes for threads creation */
413 int io_active_threads
; /* Number of running I/O threads */
414 int vm_max_threads
; /* Max number of I/O threads running at the same time */
415 /* Our main thread is blocked on the event loop, locking for sockets ready
416 * to be read or written, so when a threaded I/O operation is ready to be
417 * processed by the main thread, the I/O thread will use a unix pipe to
418 * awake the main thread. The followings are the two pipe FDs. */
419 int io_ready_pipe_read
;
420 int io_ready_pipe_write
;
421 /* Virtual memory stats */
422 unsigned long long vm_stats_used_pages
;
423 unsigned long long vm_stats_swapped_objects
;
424 unsigned long long vm_stats_swapouts
;
425 unsigned long long vm_stats_swapins
;
429 typedef void redisCommandProc(redisClient
*c
);
430 struct redisCommand
{
432 redisCommandProc
*proc
;
437 struct redisFunctionSym
{
439 unsigned long pointer
;
442 typedef struct _redisSortObject
{
450 typedef struct _redisSortOperation
{
453 } redisSortOperation
;
455 /* ZSETs use a specialized version of Skiplists */
457 typedef struct zskiplistNode
{
458 struct zskiplistNode
**forward
;
459 struct zskiplistNode
*backward
;
464 typedef struct zskiplist
{
465 struct zskiplistNode
*header
, *tail
;
466 unsigned long length
;
470 typedef struct zset
{
475 /* Our shared "common" objects */
477 struct sharedObjectsStruct
{
478 robj
*crlf
, *ok
, *err
, *emptybulk
, *czero
, *cone
, *pong
, *space
,
479 *colon
, *nullbulk
, *nullmultibulk
, *queued
,
480 *emptymultibulk
, *wrongtypeerr
, *nokeyerr
, *syntaxerr
, *sameobjecterr
,
481 *outofrangeerr
, *plus
,
482 *select0
, *select1
, *select2
, *select3
, *select4
,
483 *select5
, *select6
, *select7
, *select8
, *select9
;
486 /* Global vars that are actally used as constants. The following double
487 * values are used for double on-disk serialization, and are initialized
488 * at runtime to avoid strange compiler optimizations. */
490 static double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
;
492 /* VM threaded I/O request message */
493 #define REDIS_IOJOB_LOAD 0 /* Load from disk to memory */
494 #define REDIS_IOJOB_PREPARE_SWAP 1 /* Compute needed pages */
495 #define REDIS_IOJOB_DO_SWAP 2 /* Swap from memory to disk */
496 typedef struct iojon
{
497 int type
; /* Request type, REDIS_IOJOB_* */
498 redisDb
*db
;/* Redis database */
499 robj
*key
; /* This I/O request is about swapping this key */
500 robj
*val
; /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
501 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
502 off_t page
; /* Swap page where to read/write the object */
503 off_t pages
; /* Swap pages needed to safe object. PREPARE_SWAP return val */
504 int canceled
; /* True if this command was canceled by blocking side of VM */
505 pthread_t thread
; /* ID of the thread processing this entry */
508 /*================================ Prototypes =============================== */
510 static void freeStringObject(robj
*o
);
511 static void freeListObject(robj
*o
);
512 static void freeSetObject(robj
*o
);
513 static void decrRefCount(void *o
);
514 static robj
*createObject(int type
, void *ptr
);
515 static void freeClient(redisClient
*c
);
516 static int rdbLoad(char *filename
);
517 static void addReply(redisClient
*c
, robj
*obj
);
518 static void addReplySds(redisClient
*c
, sds s
);
519 static void incrRefCount(robj
*o
);
520 static int rdbSaveBackground(char *filename
);
521 static robj
*createStringObject(char *ptr
, size_t len
);
522 static robj
*dupStringObject(robj
*o
);
523 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
524 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
525 static int syncWithMaster(void);
526 static robj
*tryObjectSharing(robj
*o
);
527 static int tryObjectEncoding(robj
*o
);
528 static robj
*getDecodedObject(robj
*o
);
529 static int removeExpire(redisDb
*db
, robj
*key
);
530 static int expireIfNeeded(redisDb
*db
, robj
*key
);
531 static int deleteIfVolatile(redisDb
*db
, robj
*key
);
532 static int deleteIfSwapped(redisDb
*db
, robj
*key
);
533 static int deleteKey(redisDb
*db
, robj
*key
);
534 static time_t getExpire(redisDb
*db
, robj
*key
);
535 static int setExpire(redisDb
*db
, robj
*key
, time_t when
);
536 static void updateSlavesWaitingBgsave(int bgsaveerr
);
537 static void freeMemoryIfNeeded(void);
538 static int processCommand(redisClient
*c
);
539 static void setupSigSegvAction(void);
540 static void rdbRemoveTempFile(pid_t childpid
);
541 static void aofRemoveTempFile(pid_t childpid
);
542 static size_t stringObjectLen(robj
*o
);
543 static void processInputBuffer(redisClient
*c
);
544 static zskiplist
*zslCreate(void);
545 static void zslFree(zskiplist
*zsl
);
546 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
);
547 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
548 static void initClientMultiState(redisClient
*c
);
549 static void freeClientMultiState(redisClient
*c
);
550 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
);
551 static void unblockClient(redisClient
*c
);
552 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
);
553 static void vmInit(void);
554 static void vmMarkPagesFree(off_t page
, off_t count
);
555 static robj
*vmLoadObject(robj
*key
);
556 static robj
*vmPreviewObject(robj
*key
);
557 static int vmSwapOneObjectBlocking(void);
558 static int vmSwapOneObjectThreaded(void);
559 static int vmCanSwapOut(void);
560 static int tryFreeOneObjectFromFreelist(void);
561 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
562 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
563 static void vmCancelThreadedIOJob(robj
*o
);
564 static void lockThreadedIO(void);
565 static void unlockThreadedIO(void);
566 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
);
567 static void freeIOJob(iojob
*j
);
568 static void queueIOJob(iojob
*j
);
569 static int vmWriteObjectOnSwap(robj
*o
, off_t page
);
570 static robj
*vmReadObjectFromSwap(off_t page
, int type
);
571 static void waitZeroActiveThreads(void);
573 static void authCommand(redisClient
*c
);
574 static void pingCommand(redisClient
*c
);
575 static void echoCommand(redisClient
*c
);
576 static void setCommand(redisClient
*c
);
577 static void setnxCommand(redisClient
*c
);
578 static void getCommand(redisClient
*c
);
579 static void delCommand(redisClient
*c
);
580 static void existsCommand(redisClient
*c
);
581 static void incrCommand(redisClient
*c
);
582 static void decrCommand(redisClient
*c
);
583 static void incrbyCommand(redisClient
*c
);
584 static void decrbyCommand(redisClient
*c
);
585 static void selectCommand(redisClient
*c
);
586 static void randomkeyCommand(redisClient
*c
);
587 static void keysCommand(redisClient
*c
);
588 static void dbsizeCommand(redisClient
*c
);
589 static void lastsaveCommand(redisClient
*c
);
590 static void saveCommand(redisClient
*c
);
591 static void bgsaveCommand(redisClient
*c
);
592 static void bgrewriteaofCommand(redisClient
*c
);
593 static void shutdownCommand(redisClient
*c
);
594 static void moveCommand(redisClient
*c
);
595 static void renameCommand(redisClient
*c
);
596 static void renamenxCommand(redisClient
*c
);
597 static void lpushCommand(redisClient
*c
);
598 static void rpushCommand(redisClient
*c
);
599 static void lpopCommand(redisClient
*c
);
600 static void rpopCommand(redisClient
*c
);
601 static void llenCommand(redisClient
*c
);
602 static void lindexCommand(redisClient
*c
);
603 static void lrangeCommand(redisClient
*c
);
604 static void ltrimCommand(redisClient
*c
);
605 static void typeCommand(redisClient
*c
);
606 static void lsetCommand(redisClient
*c
);
607 static void saddCommand(redisClient
*c
);
608 static void sremCommand(redisClient
*c
);
609 static void smoveCommand(redisClient
*c
);
610 static void sismemberCommand(redisClient
*c
);
611 static void scardCommand(redisClient
*c
);
612 static void spopCommand(redisClient
*c
);
613 static void srandmemberCommand(redisClient
*c
);
614 static void sinterCommand(redisClient
*c
);
615 static void sinterstoreCommand(redisClient
*c
);
616 static void sunionCommand(redisClient
*c
);
617 static void sunionstoreCommand(redisClient
*c
);
618 static void sdiffCommand(redisClient
*c
);
619 static void sdiffstoreCommand(redisClient
*c
);
620 static void syncCommand(redisClient
*c
);
621 static void flushdbCommand(redisClient
*c
);
622 static void flushallCommand(redisClient
*c
);
623 static void sortCommand(redisClient
*c
);
624 static void lremCommand(redisClient
*c
);
625 static void rpoplpushcommand(redisClient
*c
);
626 static void infoCommand(redisClient
*c
);
627 static void mgetCommand(redisClient
*c
);
628 static void monitorCommand(redisClient
*c
);
629 static void expireCommand(redisClient
*c
);
630 static void expireatCommand(redisClient
*c
);
631 static void getsetCommand(redisClient
*c
);
632 static void ttlCommand(redisClient
*c
);
633 static void slaveofCommand(redisClient
*c
);
634 static void debugCommand(redisClient
*c
);
635 static void msetCommand(redisClient
*c
);
636 static void msetnxCommand(redisClient
*c
);
637 static void zaddCommand(redisClient
*c
);
638 static void zincrbyCommand(redisClient
*c
);
639 static void zrangeCommand(redisClient
*c
);
640 static void zrangebyscoreCommand(redisClient
*c
);
641 static void zrevrangeCommand(redisClient
*c
);
642 static void zcardCommand(redisClient
*c
);
643 static void zremCommand(redisClient
*c
);
644 static void zscoreCommand(redisClient
*c
);
645 static void zremrangebyscoreCommand(redisClient
*c
);
646 static void multiCommand(redisClient
*c
);
647 static void execCommand(redisClient
*c
);
648 static void blpopCommand(redisClient
*c
);
649 static void brpopCommand(redisClient
*c
);
651 /*================================= Globals ================================= */
654 static struct redisServer server
; /* server global state */
655 static struct redisCommand cmdTable
[] = {
656 {"get",getCommand
,2,REDIS_CMD_INLINE
},
657 {"set",setCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
658 {"setnx",setnxCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
659 {"del",delCommand
,-2,REDIS_CMD_INLINE
},
660 {"exists",existsCommand
,2,REDIS_CMD_INLINE
},
661 {"incr",incrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
662 {"decr",decrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
663 {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
},
664 {"rpush",rpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
665 {"lpush",lpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
666 {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
},
667 {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
},
668 {"brpop",brpopCommand
,-3,REDIS_CMD_INLINE
},
669 {"blpop",blpopCommand
,-3,REDIS_CMD_INLINE
},
670 {"llen",llenCommand
,2,REDIS_CMD_INLINE
},
671 {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
},
672 {"lset",lsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
673 {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
},
674 {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
},
675 {"lrem",lremCommand
,4,REDIS_CMD_BULK
},
676 {"rpoplpush",rpoplpushcommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
677 {"sadd",saddCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
678 {"srem",sremCommand
,3,REDIS_CMD_BULK
},
679 {"smove",smoveCommand
,4,REDIS_CMD_BULK
},
680 {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
},
681 {"scard",scardCommand
,2,REDIS_CMD_INLINE
},
682 {"spop",spopCommand
,2,REDIS_CMD_INLINE
},
683 {"srandmember",srandmemberCommand
,2,REDIS_CMD_INLINE
},
684 {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
685 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
686 {"sunion",sunionCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
687 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
688 {"sdiff",sdiffCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
689 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
690 {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
},
691 {"zadd",zaddCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
692 {"zincrby",zincrbyCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
693 {"zrem",zremCommand
,3,REDIS_CMD_BULK
},
694 {"zremrangebyscore",zremrangebyscoreCommand
,4,REDIS_CMD_INLINE
},
695 {"zrange",zrangeCommand
,-4,REDIS_CMD_INLINE
},
696 {"zrangebyscore",zrangebyscoreCommand
,-4,REDIS_CMD_INLINE
},
697 {"zrevrange",zrevrangeCommand
,-4,REDIS_CMD_INLINE
},
698 {"zcard",zcardCommand
,2,REDIS_CMD_INLINE
},
699 {"zscore",zscoreCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
700 {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
701 {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
702 {"getset",getsetCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
703 {"mset",msetCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
704 {"msetnx",msetnxCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
705 {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
},
706 {"select",selectCommand
,2,REDIS_CMD_INLINE
},
707 {"move",moveCommand
,3,REDIS_CMD_INLINE
},
708 {"rename",renameCommand
,3,REDIS_CMD_INLINE
},
709 {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
},
710 {"expire",expireCommand
,3,REDIS_CMD_INLINE
},
711 {"expireat",expireatCommand
,3,REDIS_CMD_INLINE
},
712 {"keys",keysCommand
,2,REDIS_CMD_INLINE
},
713 {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
},
714 {"auth",authCommand
,2,REDIS_CMD_INLINE
},
715 {"ping",pingCommand
,1,REDIS_CMD_INLINE
},
716 {"echo",echoCommand
,2,REDIS_CMD_BULK
},
717 {"save",saveCommand
,1,REDIS_CMD_INLINE
},
718 {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
},
719 {"bgrewriteaof",bgrewriteaofCommand
,1,REDIS_CMD_INLINE
},
720 {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
},
721 {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
},
722 {"type",typeCommand
,2,REDIS_CMD_INLINE
},
723 {"multi",multiCommand
,1,REDIS_CMD_INLINE
},
724 {"exec",execCommand
,1,REDIS_CMD_INLINE
},
725 {"sync",syncCommand
,1,REDIS_CMD_INLINE
},
726 {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
},
727 {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
},
728 {"sort",sortCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
729 {"info",infoCommand
,1,REDIS_CMD_INLINE
},
730 {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
},
731 {"ttl",ttlCommand
,2,REDIS_CMD_INLINE
},
732 {"slaveof",slaveofCommand
,3,REDIS_CMD_INLINE
},
733 {"debug",debugCommand
,-2,REDIS_CMD_INLINE
},
737 /*============================ Utility functions ============================ */
739 /* Glob-style pattern matching. */
740 int stringmatchlen(const char *pattern
, int patternLen
,
741 const char *string
, int stringLen
, int nocase
)
746 while (pattern
[1] == '*') {
751 return 1; /* match */
753 if (stringmatchlen(pattern
+1, patternLen
-1,
754 string
, stringLen
, nocase
))
755 return 1; /* match */
759 return 0; /* no match */
763 return 0; /* no match */
773 not = pattern
[0] == '^';
780 if (pattern
[0] == '\\') {
783 if (pattern
[0] == string
[0])
785 } else if (pattern
[0] == ']') {
787 } else if (patternLen
== 0) {
791 } else if (pattern
[1] == '-' && patternLen
>= 3) {
792 int start
= pattern
[0];
793 int end
= pattern
[2];
801 start
= tolower(start
);
807 if (c
>= start
&& c
<= end
)
811 if (pattern
[0] == string
[0])
814 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
824 return 0; /* no match */
830 if (patternLen
>= 2) {
837 if (pattern
[0] != string
[0])
838 return 0; /* no match */
840 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
841 return 0; /* no match */
849 if (stringLen
== 0) {
850 while(*pattern
== '*') {
857 if (patternLen
== 0 && stringLen
== 0)
862 static void redisLog(int level
, const char *fmt
, ...) {
866 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
870 if (level
>= server
.verbosity
) {
876 strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
));
877 fprintf(fp
,"%s %c ",buf
,c
[level
]);
878 vfprintf(fp
, fmt
, ap
);
884 if (server
.logfile
) fclose(fp
);
887 /*====================== Hash table type implementation ==================== */
889 /* This is an hash table type that uses the SDS dynamic strings libary as
890 * keys and radis objects as values (objects can hold SDS strings,
893 static void dictVanillaFree(void *privdata
, void *val
)
895 DICT_NOTUSED(privdata
);
899 static void dictListDestructor(void *privdata
, void *val
)
901 DICT_NOTUSED(privdata
);
902 listRelease((list
*)val
);
905 static int sdsDictKeyCompare(void *privdata
, const void *key1
,
909 DICT_NOTUSED(privdata
);
911 l1
= sdslen((sds
)key1
);
912 l2
= sdslen((sds
)key2
);
913 if (l1
!= l2
) return 0;
914 return memcmp(key1
, key2
, l1
) == 0;
917 static void dictRedisObjectDestructor(void *privdata
, void *val
)
919 DICT_NOTUSED(privdata
);
921 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
925 static int dictObjKeyCompare(void *privdata
, const void *key1
,
928 const robj
*o1
= key1
, *o2
= key2
;
929 return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
932 static unsigned int dictObjHash(const void *key
) {
934 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
937 static int dictEncObjKeyCompare(void *privdata
, const void *key1
,
940 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
943 o1
= getDecodedObject(o1
);
944 o2
= getDecodedObject(o2
);
945 cmp
= sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
951 static unsigned int dictEncObjHash(const void *key
) {
952 robj
*o
= (robj
*) key
;
954 o
= getDecodedObject(o
);
955 unsigned int hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
960 /* Sets type and expires */
961 static dictType setDictType
= {
962 dictEncObjHash
, /* hash function */
965 dictEncObjKeyCompare
, /* key compare */
966 dictRedisObjectDestructor
, /* key destructor */
967 NULL
/* val destructor */
970 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
971 static dictType zsetDictType
= {
972 dictEncObjHash
, /* hash function */
975 dictEncObjKeyCompare
, /* key compare */
976 dictRedisObjectDestructor
, /* key destructor */
977 dictVanillaFree
/* val destructor of malloc(sizeof(double)) */
981 static dictType hashDictType
= {
982 dictObjHash
, /* hash function */
985 dictObjKeyCompare
, /* key compare */
986 dictRedisObjectDestructor
, /* key destructor */
987 dictRedisObjectDestructor
/* val destructor */
991 static dictType keyptrDictType
= {
992 dictObjHash
, /* hash function */
995 dictObjKeyCompare
, /* key compare */
996 dictRedisObjectDestructor
, /* key destructor */
997 NULL
/* val destructor */
1000 /* Keylist hash table type has unencoded redis objects as keys and
1001 * lists as values. It's used for blocking operations (BLPOP) */
1002 static dictType keylistDictType
= {
1003 dictObjHash
, /* hash function */
1006 dictObjKeyCompare
, /* key compare */
1007 dictRedisObjectDestructor
, /* key destructor */
1008 dictListDestructor
/* val destructor */
1011 /* ========================= Random utility functions ======================= */
1013 /* Redis generally does not try to recover from out of memory conditions
1014 * when allocating objects or strings, it is not clear if it will be possible
1015 * to report this condition to the client since the networking layer itself
1016 * is based on heap allocation for send buffers, so we simply abort.
1017 * At least the code will be simpler to read... */
1018 static void oom(const char *msg
) {
1019 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
1024 /* ====================== Redis server networking stuff ===================== */
1025 static void closeTimedoutClients(void) {
1028 time_t now
= time(NULL
);
1031 listRewind(server
.clients
,&li
);
1032 while ((ln
= listNext(&li
)) != NULL
) {
1033 c
= listNodeValue(ln
);
1034 if (server
.maxidletime
&&
1035 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
1036 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
1037 (now
- c
->lastinteraction
> server
.maxidletime
))
1039 redisLog(REDIS_VERBOSE
,"Closing idle client");
1041 } else if (c
->flags
& REDIS_BLOCKED
) {
1042 if (c
->blockingto
!= 0 && c
->blockingto
< now
) {
1043 addReply(c
,shared
.nullmultibulk
);
1050 static int htNeedsResize(dict
*dict
) {
1051 long long size
, used
;
1053 size
= dictSlots(dict
);
1054 used
= dictSize(dict
);
1055 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
1056 (used
*100/size
< REDIS_HT_MINFILL
));
1059 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
1060 * we resize the hash table to save memory */
1061 static void tryResizeHashTables(void) {
1064 for (j
= 0; j
< server
.dbnum
; j
++) {
1065 if (htNeedsResize(server
.db
[j
].dict
)) {
1066 redisLog(REDIS_VERBOSE
,"The hash table %d is too sparse, resize it...",j
);
1067 dictResize(server
.db
[j
].dict
);
1068 redisLog(REDIS_VERBOSE
,"Hash table %d resized.",j
);
1070 if (htNeedsResize(server
.db
[j
].expires
))
1071 dictResize(server
.db
[j
].expires
);
1075 /* A background saving child (BGSAVE) terminated its work. Handle this. */
1076 void backgroundSaveDoneHandler(int statloc
) {
1077 int exitcode
= WEXITSTATUS(statloc
);
1078 int bysignal
= WIFSIGNALED(statloc
);
1080 if (!bysignal
&& exitcode
== 0) {
1081 redisLog(REDIS_NOTICE
,
1082 "Background saving terminated with success");
1084 server
.lastsave
= time(NULL
);
1085 } else if (!bysignal
&& exitcode
!= 0) {
1086 redisLog(REDIS_WARNING
, "Background saving error");
1088 redisLog(REDIS_WARNING
,
1089 "Background saving terminated by signal");
1090 rdbRemoveTempFile(server
.bgsavechildpid
);
1092 server
.bgsavechildpid
= -1;
1093 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1094 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1095 updateSlavesWaitingBgsave(exitcode
== 0 ? REDIS_OK
: REDIS_ERR
);
1098 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1100 void backgroundRewriteDoneHandler(int statloc
) {
1101 int exitcode
= WEXITSTATUS(statloc
);
1102 int bysignal
= WIFSIGNALED(statloc
);
1104 if (!bysignal
&& exitcode
== 0) {
1108 redisLog(REDIS_NOTICE
,
1109 "Background append only file rewriting terminated with success");
1110 /* Now it's time to flush the differences accumulated by the parent */
1111 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) server
.bgrewritechildpid
);
1112 fd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
1114 redisLog(REDIS_WARNING
, "Not able to open the temp append only file produced by the child: %s", strerror(errno
));
1117 /* Flush our data... */
1118 if (write(fd
,server
.bgrewritebuf
,sdslen(server
.bgrewritebuf
)) !=
1119 (signed) sdslen(server
.bgrewritebuf
)) {
1120 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
));
1124 redisLog(REDIS_NOTICE
,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server
.bgrewritebuf
));
1125 /* Now our work is to rename the temp file into the stable file. And
1126 * switch the file descriptor used by the server for append only. */
1127 if (rename(tmpfile
,server
.appendfilename
) == -1) {
1128 redisLog(REDIS_WARNING
,"Can't rename the temp append only file into the stable one: %s", strerror(errno
));
1132 /* Mission completed... almost */
1133 redisLog(REDIS_NOTICE
,"Append only file successfully rewritten.");
1134 if (server
.appendfd
!= -1) {
1135 /* If append only is actually enabled... */
1136 close(server
.appendfd
);
1137 server
.appendfd
= fd
;
1139 server
.appendseldb
= -1; /* Make sure it will issue SELECT */
1140 redisLog(REDIS_NOTICE
,"The new append only file was selected for future appends.");
1142 /* If append only is disabled we just generate a dump in this
1143 * format. Why not? */
1146 } else if (!bysignal
&& exitcode
!= 0) {
1147 redisLog(REDIS_WARNING
, "Background append only file rewriting error");
1149 redisLog(REDIS_WARNING
,
1150 "Background append only file rewriting terminated by signal");
1153 sdsfree(server
.bgrewritebuf
);
1154 server
.bgrewritebuf
= sdsempty();
1155 aofRemoveTempFile(server
.bgrewritechildpid
);
1156 server
.bgrewritechildpid
= -1;
1159 static int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
1160 int j
, loops
= server
.cronloops
++;
1161 REDIS_NOTUSED(eventLoop
);
1163 REDIS_NOTUSED(clientData
);
1165 /* We take a cached value of the unix time in the global state because
1166 * with virtual memory and aging there is to store the current time
1167 * in objects at every object access, and accuracy is not needed.
1168 * To access a global var is faster than calling time(NULL) */
1169 server
.unixtime
= time(NULL
);
1171 /* Update the global state with the amount of used memory */
1172 server
.usedmemory
= zmalloc_used_memory();
1174 /* Show some info about non-empty databases */
1175 for (j
= 0; j
< server
.dbnum
; j
++) {
1176 long long size
, used
, vkeys
;
1178 size
= dictSlots(server
.db
[j
].dict
);
1179 used
= dictSize(server
.db
[j
].dict
);
1180 vkeys
= dictSize(server
.db
[j
].expires
);
1181 if (!(loops
% 5) && (used
|| vkeys
)) {
1182 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
1183 /* dictPrintStats(server.dict); */
1187 /* We don't want to resize the hash tables while a bacground saving
1188 * is in progress: the saving child is created using fork() that is
1189 * implemented with a copy-on-write semantic in most modern systems, so
1190 * if we resize the HT while there is the saving child at work actually
1191 * a lot of memory movements in the parent will cause a lot of pages
1193 if (server
.bgsavechildpid
== -1) tryResizeHashTables();
1195 /* Show information about connected clients */
1197 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use, %d shared objects",
1198 listLength(server
.clients
)-listLength(server
.slaves
),
1199 listLength(server
.slaves
),
1201 dictSize(server
.sharingpool
));
1204 /* Close connections of timedout clients */
1205 if ((server
.maxidletime
&& !(loops
% 10)) || server
.blockedclients
)
1206 closeTimedoutClients();
1208 /* Check if a background saving or AOF rewrite in progress terminated */
1209 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
1213 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
1214 if (pid
== server
.bgsavechildpid
) {
1215 backgroundSaveDoneHandler(statloc
);
1217 backgroundRewriteDoneHandler(statloc
);
1221 /* If there is not a background saving in progress check if
1222 * we have to save now */
1223 time_t now
= time(NULL
);
1224 for (j
= 0; j
< server
.saveparamslen
; j
++) {
1225 struct saveparam
*sp
= server
.saveparams
+j
;
1227 if (server
.dirty
>= sp
->changes
&&
1228 now
-server
.lastsave
> sp
->seconds
) {
1229 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
1230 sp
->changes
, sp
->seconds
);
1231 rdbSaveBackground(server
.dbfilename
);
1237 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1238 * will use few CPU cycles if there are few expiring keys, otherwise
1239 * it will get more aggressive to avoid that too much memory is used by
1240 * keys that can be removed from the keyspace. */
1241 for (j
= 0; j
< server
.dbnum
; j
++) {
1243 redisDb
*db
= server
.db
+j
;
1245 /* Continue to expire if at the end of the cycle more than 25%
1246 * of the keys were expired. */
1248 long num
= dictSize(db
->expires
);
1249 time_t now
= time(NULL
);
1252 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
1253 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
1258 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
1259 t
= (time_t) dictGetEntryVal(de
);
1261 deleteKey(db
,dictGetEntryKey(de
));
1265 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
1268 /* Swap a few keys on disk if we are over the memory limit and VM
1269 * is enbled. Try to free objects from the free list first. */
1270 if (vmCanSwapOut()) {
1271 while (server
.vm_enabled
&& zmalloc_used_memory() >
1272 server
.vm_max_memory
)
1276 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
1277 retval
= (server
.vm_max_threads
== 0) ?
1278 vmSwapOneObjectBlocking() :
1279 vmSwapOneObjectThreaded();
1280 if (retval
== REDIS_ERR
&& (loops
% 30) == 0 &&
1281 zmalloc_used_memory() >
1282 (server
.vm_max_memory
+server
.vm_max_memory
/10))
1284 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
1286 /* Note that when using threade I/O we free just one object,
1287 * because anyway when the I/O thread in charge to swap this
1288 * object out will finish, the handler of completed jobs
1289 * will try to swap more objects if we are still out of memory. */
1290 if (retval
== REDIS_ERR
|| server
.vm_max_threads
> 0) break;
1294 /* Check if we should connect to a MASTER */
1295 if (server
.replstate
== REDIS_REPL_CONNECT
) {
1296 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
1297 if (syncWithMaster() == REDIS_OK
) {
1298 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
1304 static void createSharedObjects(void) {
1305 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
1306 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
1307 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
1308 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
1309 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
1310 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
1311 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
1312 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
1313 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
1314 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
1315 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
1316 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
1317 "-ERR Operation against a key holding the wrong kind of value\r\n"));
1318 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
1319 "-ERR no such key\r\n"));
1320 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
1321 "-ERR syntax error\r\n"));
1322 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
1323 "-ERR source and destination objects are the same\r\n"));
1324 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
1325 "-ERR index out of range\r\n"));
1326 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
1327 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
1328 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
1329 shared
.select0
= createStringObject("select 0\r\n",10);
1330 shared
.select1
= createStringObject("select 1\r\n",10);
1331 shared
.select2
= createStringObject("select 2\r\n",10);
1332 shared
.select3
= createStringObject("select 3\r\n",10);
1333 shared
.select4
= createStringObject("select 4\r\n",10);
1334 shared
.select5
= createStringObject("select 5\r\n",10);
1335 shared
.select6
= createStringObject("select 6\r\n",10);
1336 shared
.select7
= createStringObject("select 7\r\n",10);
1337 shared
.select8
= createStringObject("select 8\r\n",10);
1338 shared
.select9
= createStringObject("select 9\r\n",10);
1341 static void appendServerSaveParams(time_t seconds
, int changes
) {
1342 server
.saveparams
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1));
1343 server
.saveparams
[server
.saveparamslen
].seconds
= seconds
;
1344 server
.saveparams
[server
.saveparamslen
].changes
= changes
;
1345 server
.saveparamslen
++;
1348 static void resetServerSaveParams() {
1349 zfree(server
.saveparams
);
1350 server
.saveparams
= NULL
;
1351 server
.saveparamslen
= 0;
1354 static void initServerConfig() {
1355 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
1356 server
.port
= REDIS_SERVERPORT
;
1357 server
.verbosity
= REDIS_VERBOSE
;
1358 server
.maxidletime
= REDIS_MAXIDLETIME
;
1359 server
.saveparams
= NULL
;
1360 server
.logfile
= NULL
; /* NULL = log on standard output */
1361 server
.bindaddr
= NULL
;
1362 server
.glueoutputbuf
= 1;
1363 server
.daemonize
= 0;
1364 server
.appendonly
= 0;
1365 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1366 server
.lastfsync
= time(NULL
);
1367 server
.appendfd
= -1;
1368 server
.appendseldb
= -1; /* Make sure the first time will not match */
1369 server
.pidfile
= "/var/run/redis.pid";
1370 server
.dbfilename
= "dump.rdb";
1371 server
.appendfilename
= "appendonly.aof";
1372 server
.requirepass
= NULL
;
1373 server
.shareobjects
= 0;
1374 server
.rdbcompression
= 1;
1375 server
.sharingpoolsize
= 1024;
1376 server
.maxclients
= 0;
1377 server
.blockedclients
= 0;
1378 server
.maxmemory
= 0;
1379 server
.vm_enabled
= 0;
1380 server
.vm_page_size
= 256; /* 256 bytes per page */
1381 server
.vm_pages
= 1024*1024*100; /* 104 millions of pages */
1382 server
.vm_max_memory
= 1024LL*1024*1024*1; /* 1 GB of RAM */
1383 server
.vm_max_threads
= 4;
1385 resetServerSaveParams();
1387 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1388 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1389 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1390 /* Replication related */
1392 server
.masterauth
= NULL
;
1393 server
.masterhost
= NULL
;
1394 server
.masterport
= 6379;
1395 server
.master
= NULL
;
1396 server
.replstate
= REDIS_REPL_NONE
;
1398 /* Double constants initialization */
1400 R_PosInf
= 1.0/R_Zero
;
1401 R_NegInf
= -1.0/R_Zero
;
1402 R_Nan
= R_Zero
/R_Zero
;
1405 static void initServer() {
1408 signal(SIGHUP
, SIG_IGN
);
1409 signal(SIGPIPE
, SIG_IGN
);
1410 setupSigSegvAction();
1412 server
.devnull
= fopen("/dev/null","w");
1413 if (server
.devnull
== NULL
) {
1414 redisLog(REDIS_WARNING
, "Can't open /dev/null: %s", server
.neterr
);
1417 server
.clients
= listCreate();
1418 server
.slaves
= listCreate();
1419 server
.monitors
= listCreate();
1420 server
.objfreelist
= listCreate();
1421 createSharedObjects();
1422 server
.el
= aeCreateEventLoop();
1423 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
1424 server
.sharingpool
= dictCreate(&setDictType
,NULL
);
1425 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
1426 if (server
.fd
== -1) {
1427 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
1430 for (j
= 0; j
< server
.dbnum
; j
++) {
1431 server
.db
[j
].dict
= dictCreate(&hashDictType
,NULL
);
1432 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
1433 server
.db
[j
].blockingkeys
= dictCreate(&keylistDictType
,NULL
);
1434 server
.db
[j
].id
= j
;
1436 server
.cronloops
= 0;
1437 server
.bgsavechildpid
= -1;
1438 server
.bgrewritechildpid
= -1;
1439 server
.bgrewritebuf
= sdsempty();
1440 server
.lastsave
= time(NULL
);
1442 server
.usedmemory
= 0;
1443 server
.stat_numcommands
= 0;
1444 server
.stat_numconnections
= 0;
1445 server
.stat_starttime
= time(NULL
);
1446 server
.unixtime
= time(NULL
);
1447 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
1448 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
1449 acceptHandler
, NULL
) == AE_ERR
) oom("creating file event");
1451 if (server
.appendonly
) {
1452 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
1453 if (server
.appendfd
== -1) {
1454 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
1460 if (server
.vm_enabled
) vmInit();
1463 /* Empty the whole database */
1464 static long long emptyDb() {
1466 long long removed
= 0;
1468 for (j
= 0; j
< server
.dbnum
; j
++) {
1469 removed
+= dictSize(server
.db
[j
].dict
);
1470 dictEmpty(server
.db
[j
].dict
);
1471 dictEmpty(server
.db
[j
].expires
);
1476 static int yesnotoi(char *s
) {
1477 if (!strcasecmp(s
,"yes")) return 1;
1478 else if (!strcasecmp(s
,"no")) return 0;
1482 /* I agree, this is a very rudimental way to load a configuration...
1483 will improve later if the config gets more complex */
1484 static void loadServerConfig(char *filename
) {
1486 char buf
[REDIS_CONFIGLINE_MAX
+1], *err
= NULL
;
1490 if (filename
[0] == '-' && filename
[1] == '\0')
1493 if ((fp
= fopen(filename
,"r")) == NULL
) {
1494 redisLog(REDIS_WARNING
,"Fatal error, can't open config file");
1499 while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) {
1505 line
= sdstrim(line
," \t\r\n");
1507 /* Skip comments and blank lines*/
1508 if (line
[0] == '#' || line
[0] == '\0') {
1513 /* Split into arguments */
1514 argv
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
);
1515 sdstolower(argv
[0]);
1517 /* Execute config directives */
1518 if (!strcasecmp(argv
[0],"timeout") && argc
== 2) {
1519 server
.maxidletime
= atoi(argv
[1]);
1520 if (server
.maxidletime
< 0) {
1521 err
= "Invalid timeout value"; goto loaderr
;
1523 } else if (!strcasecmp(argv
[0],"port") && argc
== 2) {
1524 server
.port
= atoi(argv
[1]);
1525 if (server
.port
< 1 || server
.port
> 65535) {
1526 err
= "Invalid port"; goto loaderr
;
1528 } else if (!strcasecmp(argv
[0],"bind") && argc
== 2) {
1529 server
.bindaddr
= zstrdup(argv
[1]);
1530 } else if (!strcasecmp(argv
[0],"save") && argc
== 3) {
1531 int seconds
= atoi(argv
[1]);
1532 int changes
= atoi(argv
[2]);
1533 if (seconds
< 1 || changes
< 0) {
1534 err
= "Invalid save parameters"; goto loaderr
;
1536 appendServerSaveParams(seconds
,changes
);
1537 } else if (!strcasecmp(argv
[0],"dir") && argc
== 2) {
1538 if (chdir(argv
[1]) == -1) {
1539 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s",
1540 argv
[1], strerror(errno
));
1543 } else if (!strcasecmp(argv
[0],"loglevel") && argc
== 2) {
1544 if (!strcasecmp(argv
[1],"debug")) server
.verbosity
= REDIS_DEBUG
;
1545 else if (!strcasecmp(argv
[1],"verbose")) server
.verbosity
= REDIS_VERBOSE
;
1546 else if (!strcasecmp(argv
[1],"notice")) server
.verbosity
= REDIS_NOTICE
;
1547 else if (!strcasecmp(argv
[1],"warning")) server
.verbosity
= REDIS_WARNING
;
1549 err
= "Invalid log level. Must be one of debug, notice, warning";
1552 } else if (!strcasecmp(argv
[0],"logfile") && argc
== 2) {
1555 server
.logfile
= zstrdup(argv
[1]);
1556 if (!strcasecmp(server
.logfile
,"stdout")) {
1557 zfree(server
.logfile
);
1558 server
.logfile
= NULL
;
1560 if (server
.logfile
) {
1561 /* Test if we are able to open the file. The server will not
1562 * be able to abort just for this problem later... */
1563 logfp
= fopen(server
.logfile
,"a");
1564 if (logfp
== NULL
) {
1565 err
= sdscatprintf(sdsempty(),
1566 "Can't open the log file: %s", strerror(errno
));
1571 } else if (!strcasecmp(argv
[0],"databases") && argc
== 2) {
1572 server
.dbnum
= atoi(argv
[1]);
1573 if (server
.dbnum
< 1) {
1574 err
= "Invalid number of databases"; goto loaderr
;
1576 } else if (!strcasecmp(argv
[0],"maxclients") && argc
== 2) {
1577 server
.maxclients
= atoi(argv
[1]);
1578 } else if (!strcasecmp(argv
[0],"maxmemory") && argc
== 2) {
1579 server
.maxmemory
= strtoll(argv
[1], NULL
, 10);
1580 } else if (!strcasecmp(argv
[0],"slaveof") && argc
== 3) {
1581 server
.masterhost
= sdsnew(argv
[1]);
1582 server
.masterport
= atoi(argv
[2]);
1583 server
.replstate
= REDIS_REPL_CONNECT
;
1584 } else if (!strcasecmp(argv
[0],"masterauth") && argc
== 2) {
1585 server
.masterauth
= zstrdup(argv
[1]);
1586 } else if (!strcasecmp(argv
[0],"glueoutputbuf") && argc
== 2) {
1587 if ((server
.glueoutputbuf
= yesnotoi(argv
[1])) == -1) {
1588 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1590 } else if (!strcasecmp(argv
[0],"shareobjects") && argc
== 2) {
1591 if ((server
.shareobjects
= yesnotoi(argv
[1])) == -1) {
1592 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1594 } else if (!strcasecmp(argv
[0],"rdbcompression") && argc
== 2) {
1595 if ((server
.rdbcompression
= yesnotoi(argv
[1])) == -1) {
1596 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1598 } else if (!strcasecmp(argv
[0],"shareobjectspoolsize") && argc
== 2) {
1599 server
.sharingpoolsize
= atoi(argv
[1]);
1600 if (server
.sharingpoolsize
< 1) {
1601 err
= "invalid object sharing pool size"; goto loaderr
;
1603 } else if (!strcasecmp(argv
[0],"daemonize") && argc
== 2) {
1604 if ((server
.daemonize
= yesnotoi(argv
[1])) == -1) {
1605 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1607 } else if (!strcasecmp(argv
[0],"appendonly") && argc
== 2) {
1608 if ((server
.appendonly
= yesnotoi(argv
[1])) == -1) {
1609 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1611 } else if (!strcasecmp(argv
[0],"appendfsync") && argc
== 2) {
1612 if (!strcasecmp(argv
[1],"no")) {
1613 server
.appendfsync
= APPENDFSYNC_NO
;
1614 } else if (!strcasecmp(argv
[1],"always")) {
1615 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1616 } else if (!strcasecmp(argv
[1],"everysec")) {
1617 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
1619 err
= "argument must be 'no', 'always' or 'everysec'";
1622 } else if (!strcasecmp(argv
[0],"requirepass") && argc
== 2) {
1623 server
.requirepass
= zstrdup(argv
[1]);
1624 } else if (!strcasecmp(argv
[0],"pidfile") && argc
== 2) {
1625 server
.pidfile
= zstrdup(argv
[1]);
1626 } else if (!strcasecmp(argv
[0],"dbfilename") && argc
== 2) {
1627 server
.dbfilename
= zstrdup(argv
[1]);
1628 } else if (!strcasecmp(argv
[0],"vm-enabled") && argc
== 2) {
1629 if ((server
.vm_enabled
= yesnotoi(argv
[1])) == -1) {
1630 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1632 } else if (!strcasecmp(argv
[0],"vm-max-memory") && argc
== 2) {
1633 server
.vm_max_memory
= strtoll(argv
[1], NULL
, 10);
1634 } else if (!strcasecmp(argv
[0],"vm-page-size") && argc
== 2) {
1635 server
.vm_page_size
= strtoll(argv
[1], NULL
, 10);
1636 } else if (!strcasecmp(argv
[0],"vm-pages") && argc
== 2) {
1637 server
.vm_pages
= strtoll(argv
[1], NULL
, 10);
1638 } else if (!strcasecmp(argv
[0],"vm-max-threads") && argc
== 2) {
1639 server
.vm_max_threads
= strtoll(argv
[1], NULL
, 10);
1641 err
= "Bad directive or wrong number of arguments"; goto loaderr
;
1643 for (j
= 0; j
< argc
; j
++)
1648 if (fp
!= stdin
) fclose(fp
);
1652 fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n");
1653 fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
);
1654 fprintf(stderr
, ">>> '%s'\n", line
);
1655 fprintf(stderr
, "%s\n", err
);
1659 static void freeClientArgv(redisClient
*c
) {
1662 for (j
= 0; j
< c
->argc
; j
++)
1663 decrRefCount(c
->argv
[j
]);
1664 for (j
= 0; j
< c
->mbargc
; j
++)
1665 decrRefCount(c
->mbargv
[j
]);
1670 static void freeClient(redisClient
*c
) {
1673 /* Note that if the client we are freeing is blocked into a blocking
1674 * call, we have to set querybuf to NULL *before* to call unblockClient()
1675 * to avoid processInputBuffer() will get called. Also it is important
1676 * to remove the file events after this, because this call adds
1677 * the READABLE event. */
1678 sdsfree(c
->querybuf
);
1680 if (c
->flags
& REDIS_BLOCKED
)
1683 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
1684 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1685 listRelease(c
->reply
);
1688 /* Remove from the list of clients */
1689 ln
= listSearchKey(server
.clients
,c
);
1690 redisAssert(ln
!= NULL
);
1691 listDelNode(server
.clients
,ln
);
1692 /* Remove from the list of clients waiting for VM operations */
1693 if (server
.vm_enabled
&& listLength(c
->io_keys
)) {
1694 ln
= listSearchKey(server
.io_clients
,c
);
1695 if (ln
) listDelNode(server
.io_clients
,ln
);
1696 listRelease(c
->io_keys
);
1698 listRelease(c
->io_keys
);
1700 if (c
->flags
& REDIS_SLAVE
) {
1701 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
1703 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
1704 ln
= listSearchKey(l
,c
);
1705 redisAssert(ln
!= NULL
);
1708 if (c
->flags
& REDIS_MASTER
) {
1709 server
.master
= NULL
;
1710 server
.replstate
= REDIS_REPL_CONNECT
;
1714 freeClientMultiState(c
);
1718 #define GLUEREPLY_UP_TO (1024)
1719 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
1721 char buf
[GLUEREPLY_UP_TO
];
1726 listRewind(c
->reply
,&li
);
1727 while((ln
= listNext(&li
))) {
1731 objlen
= sdslen(o
->ptr
);
1732 if (copylen
+ objlen
<= GLUEREPLY_UP_TO
) {
1733 memcpy(buf
+copylen
,o
->ptr
,objlen
);
1735 listDelNode(c
->reply
,ln
);
1737 if (copylen
== 0) return;
1741 /* Now the output buffer is empty, add the new single element */
1742 o
= createObject(REDIS_STRING
,sdsnewlen(buf
,copylen
));
1743 listAddNodeHead(c
->reply
,o
);
1746 static void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1747 redisClient
*c
= privdata
;
1748 int nwritten
= 0, totwritten
= 0, objlen
;
1751 REDIS_NOTUSED(mask
);
1753 /* Use writev() if we have enough buffers to send */
1754 if (!server
.glueoutputbuf
&&
1755 listLength(c
->reply
) > REDIS_WRITEV_THRESHOLD
&&
1756 !(c
->flags
& REDIS_MASTER
))
1758 sendReplyToClientWritev(el
, fd
, privdata
, mask
);
1762 while(listLength(c
->reply
)) {
1763 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
1764 glueReplyBuffersIfNeeded(c
);
1766 o
= listNodeValue(listFirst(c
->reply
));
1767 objlen
= sdslen(o
->ptr
);
1770 listDelNode(c
->reply
,listFirst(c
->reply
));
1774 if (c
->flags
& REDIS_MASTER
) {
1775 /* Don't reply to a master */
1776 nwritten
= objlen
- c
->sentlen
;
1778 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen
- c
->sentlen
);
1779 if (nwritten
<= 0) break;
1781 c
->sentlen
+= nwritten
;
1782 totwritten
+= nwritten
;
1783 /* If we fully sent the object on head go to the next one */
1784 if (c
->sentlen
== objlen
) {
1785 listDelNode(c
->reply
,listFirst(c
->reply
));
1788 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
1789 * bytes, in a single threaded server it's a good idea to serve
1790 * other clients as well, even if a very large request comes from
1791 * super fast link that is always able to accept data (in real world
1792 * scenario think about 'KEYS *' against the loopback interfae) */
1793 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
) break;
1795 if (nwritten
== -1) {
1796 if (errno
== EAGAIN
) {
1799 redisLog(REDIS_VERBOSE
,
1800 "Error writing to client: %s", strerror(errno
));
1805 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
1806 if (listLength(c
->reply
) == 0) {
1808 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1812 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
)
1814 redisClient
*c
= privdata
;
1815 int nwritten
= 0, totwritten
= 0, objlen
, willwrite
;
1817 struct iovec iov
[REDIS_WRITEV_IOVEC_COUNT
];
1818 int offset
, ion
= 0;
1820 REDIS_NOTUSED(mask
);
1823 while (listLength(c
->reply
)) {
1824 offset
= c
->sentlen
;
1828 /* fill-in the iov[] array */
1829 for(node
= listFirst(c
->reply
); node
; node
= listNextNode(node
)) {
1830 o
= listNodeValue(node
);
1831 objlen
= sdslen(o
->ptr
);
1833 if (totwritten
+ objlen
- offset
> REDIS_MAX_WRITE_PER_EVENT
)
1836 if(ion
== REDIS_WRITEV_IOVEC_COUNT
)
1837 break; /* no more iovecs */
1839 iov
[ion
].iov_base
= ((char*)o
->ptr
) + offset
;
1840 iov
[ion
].iov_len
= objlen
- offset
;
1841 willwrite
+= objlen
- offset
;
1842 offset
= 0; /* just for the first item */
1849 /* write all collected blocks at once */
1850 if((nwritten
= writev(fd
, iov
, ion
)) < 0) {
1851 if (errno
!= EAGAIN
) {
1852 redisLog(REDIS_VERBOSE
,
1853 "Error writing to client: %s", strerror(errno
));
1860 totwritten
+= nwritten
;
1861 offset
= c
->sentlen
;
1863 /* remove written robjs from c->reply */
1864 while (nwritten
&& listLength(c
->reply
)) {
1865 o
= listNodeValue(listFirst(c
->reply
));
1866 objlen
= sdslen(o
->ptr
);
1868 if(nwritten
>= objlen
- offset
) {
1869 listDelNode(c
->reply
, listFirst(c
->reply
));
1870 nwritten
-= objlen
- offset
;
1874 c
->sentlen
+= nwritten
;
1882 c
->lastinteraction
= time(NULL
);
1884 if (listLength(c
->reply
) == 0) {
1886 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1890 static struct redisCommand
*lookupCommand(char *name
) {
1892 while(cmdTable
[j
].name
!= NULL
) {
1893 if (!strcasecmp(name
,cmdTable
[j
].name
)) return &cmdTable
[j
];
1899 /* resetClient prepare the client to process the next command */
1900 static void resetClient(redisClient
*c
) {
1906 /* Call() is the core of Redis execution of a command */
1907 static void call(redisClient
*c
, struct redisCommand
*cmd
) {
1910 dirty
= server
.dirty
;
1912 if (server
.appendonly
&& server
.dirty
-dirty
)
1913 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1914 if (server
.dirty
-dirty
&& listLength(server
.slaves
))
1915 replicationFeedSlaves(server
.slaves
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1916 if (listLength(server
.monitors
))
1917 replicationFeedSlaves(server
.monitors
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1918 server
.stat_numcommands
++;
1921 /* If this function gets called we already read a whole
1922 * command, argments are in the client argv/argc fields.
1923 * processCommand() execute the command or prepare the
1924 * server for a bulk read from the client.
1926 * If 1 is returned the client is still alive and valid and
1927 * and other operations can be performed by the caller. Otherwise
1928 * if 0 is returned the client was destroied (i.e. after QUIT). */
1929 static int processCommand(redisClient
*c
) {
1930 struct redisCommand
*cmd
;
1932 /* Free some memory if needed (maxmemory setting) */
1933 if (server
.maxmemory
) freeMemoryIfNeeded();
1935 /* Handle the multi bulk command type. This is an alternative protocol
1936 * supported by Redis in order to receive commands that are composed of
1937 * multiple binary-safe "bulk" arguments. The latency of processing is
1938 * a bit higher but this allows things like multi-sets, so if this
1939 * protocol is used only for MSET and similar commands this is a big win. */
1940 if (c
->multibulk
== 0 && c
->argc
== 1 && ((char*)(c
->argv
[0]->ptr
))[0] == '*') {
1941 c
->multibulk
= atoi(((char*)c
->argv
[0]->ptr
)+1);
1942 if (c
->multibulk
<= 0) {
1946 decrRefCount(c
->argv
[c
->argc
-1]);
1950 } else if (c
->multibulk
) {
1951 if (c
->bulklen
== -1) {
1952 if (((char*)c
->argv
[0]->ptr
)[0] != '$') {
1953 addReplySds(c
,sdsnew("-ERR multi bulk protocol error\r\n"));
1957 int bulklen
= atoi(((char*)c
->argv
[0]->ptr
)+1);
1958 decrRefCount(c
->argv
[0]);
1959 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
1961 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
1966 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
1970 c
->mbargv
= zrealloc(c
->mbargv
,(sizeof(robj
*))*(c
->mbargc
+1));
1971 c
->mbargv
[c
->mbargc
] = c
->argv
[0];
1975 if (c
->multibulk
== 0) {
1979 /* Here we need to swap the multi-bulk argc/argv with the
1980 * normal argc/argv of the client structure. */
1982 c
->argv
= c
->mbargv
;
1983 c
->mbargv
= auxargv
;
1986 c
->argc
= c
->mbargc
;
1987 c
->mbargc
= auxargc
;
1989 /* We need to set bulklen to something different than -1
1990 * in order for the code below to process the command without
1991 * to try to read the last argument of a bulk command as
1992 * a special argument. */
1994 /* continue below and process the command */
2001 /* -- end of multi bulk commands processing -- */
2003 /* The QUIT command is handled as a special case. Normal command
2004 * procs are unable to close the client connection safely */
2005 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
2009 cmd
= lookupCommand(c
->argv
[0]->ptr
);
2012 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
2013 (char*)c
->argv
[0]->ptr
));
2016 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
2017 (c
->argc
< -cmd
->arity
)) {
2019 sdscatprintf(sdsempty(),
2020 "-ERR wrong number of arguments for '%s' command\r\n",
2024 } else if (server
.maxmemory
&& cmd
->flags
& REDIS_CMD_DENYOOM
&& zmalloc_used_memory() > server
.maxmemory
) {
2025 addReplySds(c
,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
2028 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
2029 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
2031 decrRefCount(c
->argv
[c
->argc
-1]);
2032 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
2034 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
2039 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
2040 /* It is possible that the bulk read is already in the
2041 * buffer. Check this condition and handle it accordingly.
2042 * This is just a fast path, alternative to call processInputBuffer().
2043 * It's a good idea since the code is small and this condition
2044 * happens most of the times. */
2045 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
2046 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2048 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2053 /* Let's try to share objects on the command arguments vector */
2054 if (server
.shareobjects
) {
2056 for(j
= 1; j
< c
->argc
; j
++)
2057 c
->argv
[j
] = tryObjectSharing(c
->argv
[j
]);
2059 /* Let's try to encode the bulk object to save space. */
2060 if (cmd
->flags
& REDIS_CMD_BULK
)
2061 tryObjectEncoding(c
->argv
[c
->argc
-1]);
2063 /* Check if the user is authenticated */
2064 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
2065 addReplySds(c
,sdsnew("-ERR operation not permitted\r\n"));
2070 /* Exec the command */
2071 if (c
->flags
& REDIS_MULTI
&& cmd
->proc
!= execCommand
) {
2072 queueMultiCommand(c
,cmd
);
2073 addReply(c
,shared
.queued
);
2078 /* Prepare the client for the next command */
2079 if (c
->flags
& REDIS_CLOSE
) {
2087 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
2092 /* (args*2)+1 is enough room for args, spaces, newlines */
2093 robj
*static_outv
[REDIS_STATIC_ARGS
*2+1];
2095 if (argc
<= REDIS_STATIC_ARGS
) {
2098 outv
= zmalloc(sizeof(robj
*)*(argc
*2+1));
2101 for (j
= 0; j
< argc
; j
++) {
2102 if (j
!= 0) outv
[outc
++] = shared
.space
;
2103 if ((cmd
->flags
& REDIS_CMD_BULK
) && j
== argc
-1) {
2106 lenobj
= createObject(REDIS_STRING
,
2107 sdscatprintf(sdsempty(),"%lu\r\n",
2108 (unsigned long) stringObjectLen(argv
[j
])));
2109 lenobj
->refcount
= 0;
2110 outv
[outc
++] = lenobj
;
2112 outv
[outc
++] = argv
[j
];
2114 outv
[outc
++] = shared
.crlf
;
2116 /* Increment all the refcounts at start and decrement at end in order to
2117 * be sure to free objects if there is no slave in a replication state
2118 * able to be feed with commands */
2119 for (j
= 0; j
< outc
; j
++) incrRefCount(outv
[j
]);
2120 listRewind(slaves
,&li
);
2121 while((ln
= listNext(&li
))) {
2122 redisClient
*slave
= ln
->value
;
2124 /* Don't feed slaves that are still waiting for BGSAVE to start */
2125 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) continue;
2127 /* Feed all the other slaves, MONITORs and so on */
2128 if (slave
->slaveseldb
!= dictid
) {
2132 case 0: selectcmd
= shared
.select0
; break;
2133 case 1: selectcmd
= shared
.select1
; break;
2134 case 2: selectcmd
= shared
.select2
; break;
2135 case 3: selectcmd
= shared
.select3
; break;
2136 case 4: selectcmd
= shared
.select4
; break;
2137 case 5: selectcmd
= shared
.select5
; break;
2138 case 6: selectcmd
= shared
.select6
; break;
2139 case 7: selectcmd
= shared
.select7
; break;
2140 case 8: selectcmd
= shared
.select8
; break;
2141 case 9: selectcmd
= shared
.select9
; break;
2143 selectcmd
= createObject(REDIS_STRING
,
2144 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
2145 selectcmd
->refcount
= 0;
2148 addReply(slave
,selectcmd
);
2149 slave
->slaveseldb
= dictid
;
2151 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
2153 for (j
= 0; j
< outc
; j
++) decrRefCount(outv
[j
]);
2154 if (outv
!= static_outv
) zfree(outv
);
2157 static void processInputBuffer(redisClient
*c
) {
2159 /* Before to process the input buffer, make sure the client is not
2160 * waitig for a blocking operation such as BLPOP. Note that the first
2161 * iteration the client is never blocked, otherwise the processInputBuffer
2162 * would not be called at all, but after the execution of the first commands
2163 * in the input buffer the client may be blocked, and the "goto again"
2164 * will try to reiterate. The following line will make it return asap. */
2165 if (c
->flags
& REDIS_BLOCKED
|| c
->flags
& REDIS_IO_WAIT
) return;
2166 if (c
->bulklen
== -1) {
2167 /* Read the first line of the query */
2168 char *p
= strchr(c
->querybuf
,'\n');
2175 query
= c
->querybuf
;
2176 c
->querybuf
= sdsempty();
2177 querylen
= 1+(p
-(query
));
2178 if (sdslen(query
) > querylen
) {
2179 /* leave data after the first line of the query in the buffer */
2180 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
2182 *p
= '\0'; /* remove "\n" */
2183 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
2184 sdsupdatelen(query
);
2186 /* Now we can split the query in arguments */
2187 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
2190 if (c
->argv
) zfree(c
->argv
);
2191 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
2193 for (j
= 0; j
< argc
; j
++) {
2194 if (sdslen(argv
[j
])) {
2195 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
2203 /* Execute the command. If the client is still valid
2204 * after processCommand() return and there is something
2205 * on the query buffer try to process the next command. */
2206 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2208 /* Nothing to process, argc == 0. Just process the query
2209 * buffer if it's not empty or return to the caller */
2210 if (sdslen(c
->querybuf
)) goto again
;
2213 } else if (sdslen(c
->querybuf
) >= REDIS_REQUEST_MAX_SIZE
) {
2214 redisLog(REDIS_VERBOSE
, "Client protocol error");
2219 /* Bulk read handling. Note that if we are at this point
2220 the client already sent a command terminated with a newline,
2221 we are reading the bulk data that is actually the last
2222 argument of the command. */
2223 int qbl
= sdslen(c
->querybuf
);
2225 if (c
->bulklen
<= qbl
) {
2226 /* Copy everything but the final CRLF as final argument */
2227 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2229 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2230 /* Process the command. If the client is still valid after
2231 * the processing and there is more data in the buffer
2232 * try to parse it. */
2233 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2239 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2240 redisClient
*c
= (redisClient
*) privdata
;
2241 char buf
[REDIS_IOBUF_LEN
];
2244 REDIS_NOTUSED(mask
);
2246 nread
= read(fd
, buf
, REDIS_IOBUF_LEN
);
2248 if (errno
== EAGAIN
) {
2251 redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
));
2255 } else if (nread
== 0) {
2256 redisLog(REDIS_VERBOSE
, "Client closed connection");
2261 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
2262 c
->lastinteraction
= time(NULL
);
2266 processInputBuffer(c
);
2269 static int selectDb(redisClient
*c
, int id
) {
2270 if (id
< 0 || id
>= server
.dbnum
)
2272 c
->db
= &server
.db
[id
];
2276 static void *dupClientReplyValue(void *o
) {
2277 incrRefCount((robj
*)o
);
2281 static redisClient
*createClient(int fd
) {
2282 redisClient
*c
= zmalloc(sizeof(*c
));
2284 anetNonBlock(NULL
,fd
);
2285 anetTcpNoDelay(NULL
,fd
);
2286 if (!c
) return NULL
;
2289 c
->querybuf
= sdsempty();
2298 c
->lastinteraction
= time(NULL
);
2299 c
->authenticated
= 0;
2300 c
->replstate
= REDIS_REPL_NONE
;
2301 c
->reply
= listCreate();
2302 listSetFreeMethod(c
->reply
,decrRefCount
);
2303 listSetDupMethod(c
->reply
,dupClientReplyValue
);
2304 c
->blockingkeys
= NULL
;
2305 c
->blockingkeysnum
= 0;
2306 c
->io_keys
= listCreate();
2307 listSetFreeMethod(c
->io_keys
,decrRefCount
);
2308 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
2309 readQueryFromClient
, c
) == AE_ERR
) {
2313 listAddNodeTail(server
.clients
,c
);
2314 initClientMultiState(c
);
2318 static void addReply(redisClient
*c
, robj
*obj
) {
2319 if (listLength(c
->reply
) == 0 &&
2320 (c
->replstate
== REDIS_REPL_NONE
||
2321 c
->replstate
== REDIS_REPL_ONLINE
) &&
2322 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
2323 sendReplyToClient
, c
) == AE_ERR
) return;
2325 if (server
.vm_enabled
&& obj
->storage
!= REDIS_VM_MEMORY
) {
2326 obj
= dupStringObject(obj
);
2327 obj
->refcount
= 0; /* getDecodedObject() will increment the refcount */
2329 listAddNodeTail(c
->reply
,getDecodedObject(obj
));
2332 static void addReplySds(redisClient
*c
, sds s
) {
2333 robj
*o
= createObject(REDIS_STRING
,s
);
2338 static void addReplyDouble(redisClient
*c
, double d
) {
2341 snprintf(buf
,sizeof(buf
),"%.17g",d
);
2342 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
2343 (unsigned long) strlen(buf
),buf
));
2346 static void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
2349 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
2350 len
= sdslen(obj
->ptr
);
2352 long n
= (long)obj
->ptr
;
2354 /* Compute how many bytes will take this integer as a radix 10 string */
2360 while((n
= n
/10) != 0) {
2364 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",(unsigned long)len
));
2367 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2372 REDIS_NOTUSED(mask
);
2373 REDIS_NOTUSED(privdata
);
2375 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
2376 if (cfd
== AE_ERR
) {
2377 redisLog(REDIS_VERBOSE
,"Accepting client connection: %s", server
.neterr
);
2380 redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
);
2381 if ((c
= createClient(cfd
)) == NULL
) {
2382 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
2383 close(cfd
); /* May be already closed, just ingore errors */
2386 /* If maxclient directive is set and this is one client more... close the
2387 * connection. Note that we create the client instead to check before
2388 * for this condition, since now the socket is already set in nonblocking
2389 * mode and we can send an error for free using the Kernel I/O */
2390 if (server
.maxclients
&& listLength(server
.clients
) > server
.maxclients
) {
2391 char *err
= "-ERR max number of clients reached\r\n";
2393 /* That's a best effort error message, don't check write errors */
2394 if (write(c
->fd
,err
,strlen(err
)) == -1) {
2395 /* Nothing to do, Just to avoid the warning... */
2400 server
.stat_numconnections
++;
2403 /* ======================= Redis objects implementation ===================== */
2405 static robj
*createObject(int type
, void *ptr
) {
2408 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
2409 if (listLength(server
.objfreelist
)) {
2410 listNode
*head
= listFirst(server
.objfreelist
);
2411 o
= listNodeValue(head
);
2412 listDelNode(server
.objfreelist
,head
);
2413 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2415 if (server
.vm_enabled
) {
2416 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2417 o
= zmalloc(sizeof(*o
));
2419 o
= zmalloc(sizeof(*o
)-sizeof(struct redisObjectVM
));
2423 o
->encoding
= REDIS_ENCODING_RAW
;
2426 if (server
.vm_enabled
) {
2427 /* Note that this code may run in the context of an I/O thread
2428 * and accessing to server.unixtime in theory is an error
2429 * (no locks). But in practice this is safe, and even if we read
2430 * garbage Redis will not fail, as it's just a statistical info */
2431 o
->vm
.atime
= server
.unixtime
;
2432 o
->storage
= REDIS_VM_MEMORY
;
2437 static robj
*createStringObject(char *ptr
, size_t len
) {
2438 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
2441 static robj
*dupStringObject(robj
*o
) {
2442 assert(o
->encoding
== REDIS_ENCODING_RAW
);
2443 return createStringObject(o
->ptr
,sdslen(o
->ptr
));
2446 static robj
*createListObject(void) {
2447 list
*l
= listCreate();
2449 listSetFreeMethod(l
,decrRefCount
);
2450 return createObject(REDIS_LIST
,l
);
2453 static robj
*createSetObject(void) {
2454 dict
*d
= dictCreate(&setDictType
,NULL
);
2455 return createObject(REDIS_SET
,d
);
2458 static robj
*createZsetObject(void) {
2459 zset
*zs
= zmalloc(sizeof(*zs
));
2461 zs
->dict
= dictCreate(&zsetDictType
,NULL
);
2462 zs
->zsl
= zslCreate();
2463 return createObject(REDIS_ZSET
,zs
);
2466 static void freeStringObject(robj
*o
) {
2467 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2472 static void freeListObject(robj
*o
) {
2473 listRelease((list
*) o
->ptr
);
2476 static void freeSetObject(robj
*o
) {
2477 dictRelease((dict
*) o
->ptr
);
2480 static void freeZsetObject(robj
*o
) {
2483 dictRelease(zs
->dict
);
2488 static void freeHashObject(robj
*o
) {
2489 dictRelease((dict
*) o
->ptr
);
2492 static void incrRefCount(robj
*o
) {
2493 redisAssert(!server
.vm_enabled
|| o
->storage
== REDIS_VM_MEMORY
);
2497 static void decrRefCount(void *obj
) {
2500 /* Object is swapped out, or in the process of being loaded. */
2501 if (server
.vm_enabled
&&
2502 (o
->storage
== REDIS_VM_SWAPPED
|| o
->storage
== REDIS_VM_LOADING
))
2504 if (o
->storage
== REDIS_VM_SWAPPED
|| o
->storage
== REDIS_VM_LOADING
) {
2505 redisAssert(o
->refcount
== 1);
2507 if (o
->storage
== REDIS_VM_LOADING
) vmCancelThreadedIOJob(obj
);
2508 redisAssert(o
->type
== REDIS_STRING
);
2509 freeStringObject(o
);
2510 vmMarkPagesFree(o
->vm
.page
,o
->vm
.usedpages
);
2511 pthread_mutex_lock(&server
.obj_freelist_mutex
);
2512 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2513 !listAddNodeHead(server
.objfreelist
,o
))
2515 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2516 server
.vm_stats_swapped_objects
--;
2519 /* Object is in memory, or in the process of being swapped out. */
2520 if (--(o
->refcount
) == 0) {
2521 if (server
.vm_enabled
&& o
->storage
== REDIS_VM_SWAPPING
)
2522 vmCancelThreadedIOJob(obj
);
2524 case REDIS_STRING
: freeStringObject(o
); break;
2525 case REDIS_LIST
: freeListObject(o
); break;
2526 case REDIS_SET
: freeSetObject(o
); break;
2527 case REDIS_ZSET
: freeZsetObject(o
); break;
2528 case REDIS_HASH
: freeHashObject(o
); break;
2529 default: redisAssert(0 != 0); break;
2531 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
2532 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2533 !listAddNodeHead(server
.objfreelist
,o
))
2535 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2539 static robj
*lookupKey(redisDb
*db
, robj
*key
) {
2540 dictEntry
*de
= dictFind(db
->dict
,key
);
2542 robj
*key
= dictGetEntryKey(de
);
2543 robj
*val
= dictGetEntryVal(de
);
2545 if (server
.vm_enabled
) {
2546 if (key
->storage
== REDIS_VM_MEMORY
||
2547 key
->storage
== REDIS_VM_SWAPPING
)
2549 /* If we were swapping the object out, stop it, this key
2551 if (key
->storage
== REDIS_VM_SWAPPING
)
2552 vmCancelThreadedIOJob(key
);
2553 /* Update the access time of the key for the aging algorithm. */
2554 key
->vm
.atime
= server
.unixtime
;
2556 /* Our value was swapped on disk. Bring it at home. */
2557 redisAssert(val
== NULL
);
2558 val
= vmLoadObject(key
);
2559 dictGetEntryVal(de
) = val
;
2568 static robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
2569 expireIfNeeded(db
,key
);
2570 return lookupKey(db
,key
);
2573 static robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
2574 deleteIfVolatile(db
,key
);
2575 return lookupKey(db
,key
);
2578 static int deleteKey(redisDb
*db
, robj
*key
) {
2581 /* We need to protect key from destruction: after the first dictDelete()
2582 * it may happen that 'key' is no longer valid if we don't increment
2583 * it's count. This may happen when we get the object reference directly
2584 * from the hash table with dictRandomKey() or dict iterators */
2586 if (dictSize(db
->expires
)) dictDelete(db
->expires
,key
);
2587 retval
= dictDelete(db
->dict
,key
);
2590 return retval
== DICT_OK
;
2593 /* Try to share an object against the shared objects pool */
2594 static robj
*tryObjectSharing(robj
*o
) {
2595 struct dictEntry
*de
;
2598 if (o
== NULL
|| server
.shareobjects
== 0) return o
;
2600 redisAssert(o
->type
== REDIS_STRING
);
2601 de
= dictFind(server
.sharingpool
,o
);
2603 robj
*shared
= dictGetEntryKey(de
);
2605 c
= ((unsigned long) dictGetEntryVal(de
))+1;
2606 dictGetEntryVal(de
) = (void*) c
;
2607 incrRefCount(shared
);
2611 /* Here we are using a stream algorihtm: Every time an object is
2612 * shared we increment its count, everytime there is a miss we
2613 * recrement the counter of a random object. If this object reaches
2614 * zero we remove the object and put the current object instead. */
2615 if (dictSize(server
.sharingpool
) >=
2616 server
.sharingpoolsize
) {
2617 de
= dictGetRandomKey(server
.sharingpool
);
2618 redisAssert(de
!= NULL
);
2619 c
= ((unsigned long) dictGetEntryVal(de
))-1;
2620 dictGetEntryVal(de
) = (void*) c
;
2622 dictDelete(server
.sharingpool
,de
->key
);
2625 c
= 0; /* If the pool is empty we want to add this object */
2630 retval
= dictAdd(server
.sharingpool
,o
,(void*)1);
2631 redisAssert(retval
== DICT_OK
);
2638 /* Check if the nul-terminated string 's' can be represented by a long
2639 * (that is, is a number that fits into long without any other space or
2640 * character before or after the digits).
2642 * If so, the function returns REDIS_OK and *longval is set to the value
2643 * of the number. Otherwise REDIS_ERR is returned */
2644 static int isStringRepresentableAsLong(sds s
, long *longval
) {
2645 char buf
[32], *endptr
;
2649 value
= strtol(s
, &endptr
, 10);
2650 if (endptr
[0] != '\0') return REDIS_ERR
;
2651 slen
= snprintf(buf
,32,"%ld",value
);
2653 /* If the number converted back into a string is not identical
2654 * then it's not possible to encode the string as integer */
2655 if (sdslen(s
) != (unsigned)slen
|| memcmp(buf
,s
,slen
)) return REDIS_ERR
;
2656 if (longval
) *longval
= value
;
2660 /* Try to encode a string object in order to save space */
2661 static int tryObjectEncoding(robj
*o
) {
2665 if (o
->encoding
!= REDIS_ENCODING_RAW
)
2666 return REDIS_ERR
; /* Already encoded */
2668 /* It's not save to encode shared objects: shared objects can be shared
2669 * everywhere in the "object space" of Redis. Encoded objects can only
2670 * appear as "values" (and not, for instance, as keys) */
2671 if (o
->refcount
> 1) return REDIS_ERR
;
2673 /* Currently we try to encode only strings */
2674 redisAssert(o
->type
== REDIS_STRING
);
2676 /* Check if we can represent this string as a long integer */
2677 if (isStringRepresentableAsLong(s
,&value
) == REDIS_ERR
) return REDIS_ERR
;
2679 /* Ok, this object can be encoded */
2680 o
->encoding
= REDIS_ENCODING_INT
;
2682 o
->ptr
= (void*) value
;
2686 /* Get a decoded version of an encoded object (returned as a new object).
2687 * If the object is already raw-encoded just increment the ref count. */
2688 static robj
*getDecodedObject(robj
*o
) {
2691 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2695 if (o
->type
== REDIS_STRING
&& o
->encoding
== REDIS_ENCODING_INT
) {
2698 snprintf(buf
,32,"%ld",(long)o
->ptr
);
2699 dec
= createStringObject(buf
,strlen(buf
));
2702 redisAssert(1 != 1);
2706 /* Compare two string objects via strcmp() or alike.
2707 * Note that the objects may be integer-encoded. In such a case we
2708 * use snprintf() to get a string representation of the numbers on the stack
2709 * and compare the strings, it's much faster than calling getDecodedObject().
2711 * Important note: if objects are not integer encoded, but binary-safe strings,
2712 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
2714 static int compareStringObjects(robj
*a
, robj
*b
) {
2715 redisAssert(a
->type
== REDIS_STRING
&& b
->type
== REDIS_STRING
);
2716 char bufa
[128], bufb
[128], *astr
, *bstr
;
2719 if (a
== b
) return 0;
2720 if (a
->encoding
!= REDIS_ENCODING_RAW
) {
2721 snprintf(bufa
,sizeof(bufa
),"%ld",(long) a
->ptr
);
2727 if (b
->encoding
!= REDIS_ENCODING_RAW
) {
2728 snprintf(bufb
,sizeof(bufb
),"%ld",(long) b
->ptr
);
2734 return bothsds
? sdscmp(astr
,bstr
) : strcmp(astr
,bstr
);
2737 static size_t stringObjectLen(robj
*o
) {
2738 redisAssert(o
->type
== REDIS_STRING
);
2739 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2740 return sdslen(o
->ptr
);
2744 return snprintf(buf
,32,"%ld",(long)o
->ptr
);
2748 /*============================ RDB saving/loading =========================== */
2750 static int rdbSaveType(FILE *fp
, unsigned char type
) {
2751 if (fwrite(&type
,1,1,fp
) == 0) return -1;
2755 static int rdbSaveTime(FILE *fp
, time_t t
) {
2756 int32_t t32
= (int32_t) t
;
2757 if (fwrite(&t32
,4,1,fp
) == 0) return -1;
2761 /* check rdbLoadLen() comments for more info */
2762 static int rdbSaveLen(FILE *fp
, uint32_t len
) {
2763 unsigned char buf
[2];
2766 /* Save a 6 bit len */
2767 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
2768 if (fwrite(buf
,1,1,fp
) == 0) return -1;
2769 } else if (len
< (1<<14)) {
2770 /* Save a 14 bit len */
2771 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
2773 if (fwrite(buf
,2,1,fp
) == 0) return -1;
2775 /* Save a 32 bit len */
2776 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
2777 if (fwrite(buf
,1,1,fp
) == 0) return -1;
2779 if (fwrite(&len
,4,1,fp
) == 0) return -1;
2784 /* String objects in the form "2391" "-100" without any space and with a
2785 * range of values that can fit in an 8, 16 or 32 bit signed value can be
2786 * encoded as integers to save space */
2787 static int rdbTryIntegerEncoding(sds s
, unsigned char *enc
) {
2789 char *endptr
, buf
[32];
2791 /* Check if it's possible to encode this value as a number */
2792 value
= strtoll(s
, &endptr
, 10);
2793 if (endptr
[0] != '\0') return 0;
2794 snprintf(buf
,32,"%lld",value
);
2796 /* If the number converted back into a string is not identical
2797 * then it's not possible to encode the string as integer */
2798 if (strlen(buf
) != sdslen(s
) || memcmp(buf
,s
,sdslen(s
))) return 0;
2800 /* Finally check if it fits in our ranges */
2801 if (value
>= -(1<<7) && value
<= (1<<7)-1) {
2802 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT8
;
2803 enc
[1] = value
&0xFF;
2805 } else if (value
>= -(1<<15) && value
<= (1<<15)-1) {
2806 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
;
2807 enc
[1] = value
&0xFF;
2808 enc
[2] = (value
>>8)&0xFF;
2810 } else if (value
>= -((long long)1<<31) && value
<= ((long long)1<<31)-1) {
2811 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT32
;
2812 enc
[1] = value
&0xFF;
2813 enc
[2] = (value
>>8)&0xFF;
2814 enc
[3] = (value
>>16)&0xFF;
2815 enc
[4] = (value
>>24)&0xFF;
2822 static int rdbSaveLzfStringObject(FILE *fp
, robj
*obj
) {
2823 unsigned int comprlen
, outlen
;
2827 /* We require at least four bytes compression for this to be worth it */
2828 outlen
= sdslen(obj
->ptr
)-4;
2829 if (outlen
<= 0) return 0;
2830 if ((out
= zmalloc(outlen
+1)) == NULL
) return 0;
2831 printf("Calling LZF with ptr: %p\n", (void*)obj
->ptr
);
2833 comprlen
= lzf_compress(obj
->ptr
, sdslen(obj
->ptr
), out
, outlen
);
2834 if (comprlen
== 0) {
2838 /* Data compressed! Let's save it on disk */
2839 byte
= (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_LZF
;
2840 if (fwrite(&byte
,1,1,fp
) == 0) goto writeerr
;
2841 if (rdbSaveLen(fp
,comprlen
) == -1) goto writeerr
;
2842 if (rdbSaveLen(fp
,sdslen(obj
->ptr
)) == -1) goto writeerr
;
2843 if (fwrite(out
,comprlen
,1,fp
) == 0) goto writeerr
;
2852 /* Save a string objet as [len][data] on disk. If the object is a string
2853 * representation of an integer value we try to safe it in a special form */
2854 static int rdbSaveStringObjectRaw(FILE *fp
, robj
*obj
) {
2858 len
= sdslen(obj
->ptr
);
2860 /* Try integer encoding */
2862 unsigned char buf
[5];
2863 if ((enclen
= rdbTryIntegerEncoding(obj
->ptr
,buf
)) > 0) {
2864 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
2869 /* Try LZF compression - under 20 bytes it's unable to compress even
2870 * aaaaaaaaaaaaaaaaaa so skip it */
2871 if (server
.rdbcompression
&& len
> 20) {
2874 retval
= rdbSaveLzfStringObject(fp
,obj
);
2875 if (retval
== -1) return -1;
2876 if (retval
> 0) return 0;
2877 /* retval == 0 means data can't be compressed, save the old way */
2880 /* Store verbatim */
2881 if (rdbSaveLen(fp
,len
) == -1) return -1;
2882 if (len
&& fwrite(obj
->ptr
,len
,1,fp
) == 0) return -1;
2886 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
2887 static int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
2890 /* Avoid incr/decr ref count business when possible.
2891 * This plays well with copy-on-write given that we are probably
2892 * in a child process (BGSAVE). Also this makes sure key objects
2893 * of swapped objects are not incRefCount-ed (an assert does not allow
2894 * this in order to avoid bugs) */
2895 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
2896 obj
= getDecodedObject(obj
);
2897 retval
= rdbSaveStringObjectRaw(fp
,obj
);
2900 retval
= rdbSaveStringObjectRaw(fp
,obj
);
2905 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
2906 * 8 bit integer specifing the length of the representation.
2907 * This 8 bit integer has special values in order to specify the following
2913 static int rdbSaveDoubleValue(FILE *fp
, double val
) {
2914 unsigned char buf
[128];
2920 } else if (!isfinite(val
)) {
2922 buf
[0] = (val
< 0) ? 255 : 254;
2924 snprintf((char*)buf
+1,sizeof(buf
)-1,"%.17g",val
);
2925 buf
[0] = strlen((char*)buf
+1);
2928 if (fwrite(buf
,len
,1,fp
) == 0) return -1;
2932 /* Save a Redis object. */
2933 static int rdbSaveObject(FILE *fp
, robj
*o
) {
2934 if (o
->type
== REDIS_STRING
) {
2935 /* Save a string value */
2936 if (rdbSaveStringObject(fp
,o
) == -1) return -1;
2937 } else if (o
->type
== REDIS_LIST
) {
2938 /* Save a list value */
2939 list
*list
= o
->ptr
;
2943 if (rdbSaveLen(fp
,listLength(list
)) == -1) return -1;
2944 listRewind(list
,&li
);
2945 while((ln
= listNext(&li
))) {
2946 robj
*eleobj
= listNodeValue(ln
);
2948 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2950 } else if (o
->type
== REDIS_SET
) {
2951 /* Save a set value */
2953 dictIterator
*di
= dictGetIterator(set
);
2956 if (rdbSaveLen(fp
,dictSize(set
)) == -1) return -1;
2957 while((de
= dictNext(di
)) != NULL
) {
2958 robj
*eleobj
= dictGetEntryKey(de
);
2960 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2962 dictReleaseIterator(di
);
2963 } else if (o
->type
== REDIS_ZSET
) {
2964 /* Save a set value */
2966 dictIterator
*di
= dictGetIterator(zs
->dict
);
2969 if (rdbSaveLen(fp
,dictSize(zs
->dict
)) == -1) return -1;
2970 while((de
= dictNext(di
)) != NULL
) {
2971 robj
*eleobj
= dictGetEntryKey(de
);
2972 double *score
= dictGetEntryVal(de
);
2974 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2975 if (rdbSaveDoubleValue(fp
,*score
) == -1) return -1;
2977 dictReleaseIterator(di
);
2979 redisAssert(0 != 0);
2984 /* Return the length the object will have on disk if saved with
2985 * the rdbSaveObject() function. Currently we use a trick to get
2986 * this length with very little changes to the code. In the future
2987 * we could switch to a faster solution. */
2988 static off_t
rdbSavedObjectLen(robj
*o
, FILE *fp
) {
2989 if (fp
== NULL
) fp
= server
.devnull
;
2991 assert(rdbSaveObject(fp
,o
) != 1);
2995 /* Return the number of pages required to save this object in the swap file */
2996 static off_t
rdbSavedObjectPages(robj
*o
, FILE *fp
) {
2997 off_t bytes
= rdbSavedObjectLen(o
,fp
);
2999 return (bytes
+(server
.vm_page_size
-1))/server
.vm_page_size
;
3002 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
3003 static int rdbSave(char *filename
) {
3004 dictIterator
*di
= NULL
;
3009 time_t now
= time(NULL
);
3011 snprintf(tmpfile
,256,"temp-%d.rdb", (int) getpid());
3012 fp
= fopen(tmpfile
,"w");
3014 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
3017 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
3018 for (j
= 0; j
< server
.dbnum
; j
++) {
3019 redisDb
*db
= server
.db
+j
;
3021 if (dictSize(d
) == 0) continue;
3022 di
= dictGetIterator(d
);
3028 /* Write the SELECT DB opcode */
3029 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
3030 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
3032 /* Iterate this DB writing every entry */
3033 while((de
= dictNext(di
)) != NULL
) {
3034 robj
*key
= dictGetEntryKey(de
);
3035 robj
*o
= dictGetEntryVal(de
);
3036 time_t expiretime
= getExpire(db
,key
);
3038 /* Save the expire time */
3039 if (expiretime
!= -1) {
3040 /* If this key is already expired skip it */
3041 if (expiretime
< now
) continue;
3042 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
;
3043 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
;
3045 /* Save the key and associated value. This requires special
3046 * handling if the value is swapped out. */
3047 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
3048 key
->storage
== REDIS_VM_SWAPPING
) {
3049 /* Save type, key, value */
3050 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
3051 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3052 if (rdbSaveObject(fp
,o
) == -1) goto werr
;
3054 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
3056 /* Get a preview of the object in memory */
3057 po
= vmPreviewObject(key
);
3058 /* Save type, key, value */
3059 if (rdbSaveType(fp
,key
->vtype
) == -1) goto werr
;
3060 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3061 if (rdbSaveObject(fp
,po
) == -1) goto werr
;
3062 /* Remove the loaded object from memory */
3066 dictReleaseIterator(di
);
3069 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
3071 /* Make sure data will not remain on the OS's output buffers */
3076 /* Use RENAME to make sure the DB file is changed atomically only
3077 * if the generate DB file is ok. */
3078 if (rename(tmpfile
,filename
) == -1) {
3079 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destination: %s", strerror(errno
));
3083 redisLog(REDIS_NOTICE
,"DB saved on disk");
3085 server
.lastsave
= time(NULL
);
3091 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
3092 if (di
) dictReleaseIterator(di
);
3096 static int rdbSaveBackground(char *filename
) {
3099 if (server
.bgsavechildpid
!= -1) return REDIS_ERR
;
3100 if (server
.vm_enabled
) waitZeroActiveThreads();
3101 if ((childpid
= fork()) == 0) {
3104 if (rdbSave(filename
) == REDIS_OK
) {
3111 if (childpid
== -1) {
3112 redisLog(REDIS_WARNING
,"Can't save in background: fork: %s",
3116 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
3117 server
.bgsavechildpid
= childpid
;
3120 return REDIS_OK
; /* unreached */
3123 static void rdbRemoveTempFile(pid_t childpid
) {
3126 snprintf(tmpfile
,256,"temp-%d.rdb", (int) childpid
);
3130 static int rdbLoadType(FILE *fp
) {
3132 if (fread(&type
,1,1,fp
) == 0) return -1;
3136 static time_t rdbLoadTime(FILE *fp
) {
3138 if (fread(&t32
,4,1,fp
) == 0) return -1;
3139 return (time_t) t32
;
3142 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
3143 * of this file for a description of how this are stored on disk.
3145 * isencoded is set to 1 if the readed length is not actually a length but
3146 * an "encoding type", check the above comments for more info */
3147 static uint32_t rdbLoadLen(FILE *fp
, int *isencoded
) {
3148 unsigned char buf
[2];
3152 if (isencoded
) *isencoded
= 0;
3153 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3154 type
= (buf
[0]&0xC0)>>6;
3155 if (type
== REDIS_RDB_6BITLEN
) {
3156 /* Read a 6 bit len */
3158 } else if (type
== REDIS_RDB_ENCVAL
) {
3159 /* Read a 6 bit len encoding type */
3160 if (isencoded
) *isencoded
= 1;
3162 } else if (type
== REDIS_RDB_14BITLEN
) {
3163 /* Read a 14 bit len */
3164 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3165 return ((buf
[0]&0x3F)<<8)|buf
[1];
3167 /* Read a 32 bit len */
3168 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
3173 static robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
) {
3174 unsigned char enc
[4];
3177 if (enctype
== REDIS_RDB_ENC_INT8
) {
3178 if (fread(enc
,1,1,fp
) == 0) return NULL
;
3179 val
= (signed char)enc
[0];
3180 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
3182 if (fread(enc
,2,1,fp
) == 0) return NULL
;
3183 v
= enc
[0]|(enc
[1]<<8);
3185 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
3187 if (fread(enc
,4,1,fp
) == 0) return NULL
;
3188 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
3191 val
= 0; /* anti-warning */
3194 return createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",val
));
3197 static robj
*rdbLoadLzfStringObject(FILE*fp
) {
3198 unsigned int len
, clen
;
3199 unsigned char *c
= NULL
;
3202 if ((clen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3203 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3204 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
3205 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
3206 if (fread(c
,clen
,1,fp
) == 0) goto err
;
3207 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
3209 return createObject(REDIS_STRING
,val
);
3216 static robj
*rdbLoadStringObject(FILE*fp
) {
3221 len
= rdbLoadLen(fp
,&isencoded
);
3224 case REDIS_RDB_ENC_INT8
:
3225 case REDIS_RDB_ENC_INT16
:
3226 case REDIS_RDB_ENC_INT32
:
3227 return tryObjectSharing(rdbLoadIntegerObject(fp
,len
));
3228 case REDIS_RDB_ENC_LZF
:
3229 return tryObjectSharing(rdbLoadLzfStringObject(fp
));
3235 if (len
== REDIS_RDB_LENERR
) return NULL
;
3236 val
= sdsnewlen(NULL
,len
);
3237 if (len
&& fread(val
,len
,1,fp
) == 0) {
3241 return tryObjectSharing(createObject(REDIS_STRING
,val
));
3244 /* For information about double serialization check rdbSaveDoubleValue() */
3245 static int rdbLoadDoubleValue(FILE *fp
, double *val
) {
3249 if (fread(&len
,1,1,fp
) == 0) return -1;
3251 case 255: *val
= R_NegInf
; return 0;
3252 case 254: *val
= R_PosInf
; return 0;
3253 case 253: *val
= R_Nan
; return 0;
3255 if (fread(buf
,len
,1,fp
) == 0) return -1;
3257 sscanf(buf
, "%lg", val
);
3262 /* Load a Redis object of the specified type from the specified file.
3263 * On success a newly allocated object is returned, otherwise NULL. */
3264 static robj
*rdbLoadObject(int type
, FILE *fp
) {
3267 if (type
== REDIS_STRING
) {
3268 /* Read string value */
3269 if ((o
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3270 tryObjectEncoding(o
);
3271 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
3272 /* Read list/set value */
3275 if ((listlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3276 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
3277 /* Load every single element of the list/set */
3281 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3282 tryObjectEncoding(ele
);
3283 if (type
== REDIS_LIST
) {
3284 listAddNodeTail((list
*)o
->ptr
,ele
);
3286 dictAdd((dict
*)o
->ptr
,ele
,NULL
);
3289 } else if (type
== REDIS_ZSET
) {
3290 /* Read list/set value */
3294 if ((zsetlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3295 o
= createZsetObject();
3297 /* Load every single element of the list/set */
3300 double *score
= zmalloc(sizeof(double));
3302 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3303 tryObjectEncoding(ele
);
3304 if (rdbLoadDoubleValue(fp
,score
) == -1) return NULL
;
3305 dictAdd(zs
->dict
,ele
,score
);
3306 zslInsert(zs
->zsl
,*score
,ele
);
3307 incrRefCount(ele
); /* added to skiplist */
3310 redisAssert(0 != 0);
3315 static int rdbLoad(char *filename
) {
3317 robj
*keyobj
= NULL
;
3319 int type
, retval
, rdbver
;
3320 dict
*d
= server
.db
[0].dict
;
3321 redisDb
*db
= server
.db
+0;
3323 time_t expiretime
= -1, now
= time(NULL
);
3324 long long loadedkeys
= 0;
3326 fp
= fopen(filename
,"r");
3327 if (!fp
) return REDIS_ERR
;
3328 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
3330 if (memcmp(buf
,"REDIS",5) != 0) {
3332 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
3335 rdbver
= atoi(buf
+5);
3338 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
3345 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3346 if (type
== REDIS_EXPIRETIME
) {
3347 if ((expiretime
= rdbLoadTime(fp
)) == -1) goto eoferr
;
3348 /* We read the time so we need to read the object type again */
3349 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3351 if (type
== REDIS_EOF
) break;
3352 /* Handle SELECT DB opcode as a special case */
3353 if (type
== REDIS_SELECTDB
) {
3354 if ((dbid
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
)
3356 if (dbid
>= (unsigned)server
.dbnum
) {
3357 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
3360 db
= server
.db
+dbid
;
3365 if ((keyobj
= rdbLoadStringObject(fp
)) == NULL
) goto eoferr
;
3367 if ((o
= rdbLoadObject(type
,fp
)) == NULL
) goto eoferr
;
3368 /* Add the new object in the hash table */
3369 retval
= dictAdd(d
,keyobj
,o
);
3370 if (retval
== DICT_ERR
) {
3371 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj
->ptr
);
3374 /* Set the expire time if needed */
3375 if (expiretime
!= -1) {
3376 setExpire(db
,keyobj
,expiretime
);
3377 /* Delete this key if already expired */
3378 if (expiretime
< now
) deleteKey(db
,keyobj
);
3382 /* Handle swapping while loading big datasets when VM is on */
3384 if (server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
3385 while (zmalloc_used_memory() > server
.vm_max_memory
) {
3386 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
3393 eoferr
: /* unexpected end of file is handled here with a fatal exit */
3394 if (keyobj
) decrRefCount(keyobj
);
3395 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
3397 return REDIS_ERR
; /* Just to avoid warning */
3400 /*================================== Commands =============================== */
3402 static void authCommand(redisClient
*c
) {
3403 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
3404 c
->authenticated
= 1;
3405 addReply(c
,shared
.ok
);
3407 c
->authenticated
= 0;
3408 addReplySds(c
,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
3412 static void pingCommand(redisClient
*c
) {
3413 addReply(c
,shared
.pong
);
3416 static void echoCommand(redisClient
*c
) {
3417 addReplyBulkLen(c
,c
->argv
[1]);
3418 addReply(c
,c
->argv
[1]);
3419 addReply(c
,shared
.crlf
);
3422 /*=================================== Strings =============================== */
3424 static void setGenericCommand(redisClient
*c
, int nx
) {
3427 if (nx
) deleteIfVolatile(c
->db
,c
->argv
[1]);
3428 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3429 if (retval
== DICT_ERR
) {
3431 /* If the key is about a swapped value, we want a new key object
3432 * to overwrite the old. So we delete the old key in the database.
3433 * This will also make sure that swap pages about the old object
3434 * will be marked as free. */
3435 if (deleteIfSwapped(c
->db
,c
->argv
[1]))
3436 incrRefCount(c
->argv
[1]);
3437 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3438 incrRefCount(c
->argv
[2]);
3440 addReply(c
,shared
.czero
);
3444 incrRefCount(c
->argv
[1]);
3445 incrRefCount(c
->argv
[2]);
3448 removeExpire(c
->db
,c
->argv
[1]);
3449 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3452 static void setCommand(redisClient
*c
) {
3453 setGenericCommand(c
,0);
3456 static void setnxCommand(redisClient
*c
) {
3457 setGenericCommand(c
,1);
3460 static int getGenericCommand(redisClient
*c
) {
3461 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3464 addReply(c
,shared
.nullbulk
);
3467 if (o
->type
!= REDIS_STRING
) {
3468 addReply(c
,shared
.wrongtypeerr
);
3471 addReplyBulkLen(c
,o
);
3473 addReply(c
,shared
.crlf
);
3479 static void getCommand(redisClient
*c
) {
3480 getGenericCommand(c
);
3483 static void getsetCommand(redisClient
*c
) {
3484 if (getGenericCommand(c
) == REDIS_ERR
) return;
3485 if (dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]) == DICT_ERR
) {
3486 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3488 incrRefCount(c
->argv
[1]);
3490 incrRefCount(c
->argv
[2]);
3492 removeExpire(c
->db
,c
->argv
[1]);
3495 static void mgetCommand(redisClient
*c
) {
3498 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
3499 for (j
= 1; j
< c
->argc
; j
++) {
3500 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[j
]);
3502 addReply(c
,shared
.nullbulk
);
3504 if (o
->type
!= REDIS_STRING
) {
3505 addReply(c
,shared
.nullbulk
);
3507 addReplyBulkLen(c
,o
);
3509 addReply(c
,shared
.crlf
);
3515 static void msetGenericCommand(redisClient
*c
, int nx
) {
3516 int j
, busykeys
= 0;
3518 if ((c
->argc
% 2) == 0) {
3519 addReplySds(c
,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
3522 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
3523 * set nothing at all if at least one already key exists. */
3525 for (j
= 1; j
< c
->argc
; j
+= 2) {
3526 if (lookupKeyWrite(c
->db
,c
->argv
[j
]) != NULL
) {
3532 addReply(c
, shared
.czero
);
3536 for (j
= 1; j
< c
->argc
; j
+= 2) {
3539 tryObjectEncoding(c
->argv
[j
+1]);
3540 retval
= dictAdd(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3541 if (retval
== DICT_ERR
) {
3542 dictReplace(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3543 incrRefCount(c
->argv
[j
+1]);
3545 incrRefCount(c
->argv
[j
]);
3546 incrRefCount(c
->argv
[j
+1]);
3548 removeExpire(c
->db
,c
->argv
[j
]);
3550 server
.dirty
+= (c
->argc
-1)/2;
3551 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3554 static void msetCommand(redisClient
*c
) {
3555 msetGenericCommand(c
,0);
3558 static void msetnxCommand(redisClient
*c
) {
3559 msetGenericCommand(c
,1);
3562 static void incrDecrCommand(redisClient
*c
, long long incr
) {
3567 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3571 if (o
->type
!= REDIS_STRING
) {
3576 if (o
->encoding
== REDIS_ENCODING_RAW
)
3577 value
= strtoll(o
->ptr
, &eptr
, 10);
3578 else if (o
->encoding
== REDIS_ENCODING_INT
)
3579 value
= (long)o
->ptr
;
3581 redisAssert(1 != 1);
3586 o
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
));
3587 tryObjectEncoding(o
);
3588 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],o
);
3589 if (retval
== DICT_ERR
) {
3590 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
3591 removeExpire(c
->db
,c
->argv
[1]);
3593 incrRefCount(c
->argv
[1]);
3596 addReply(c
,shared
.colon
);
3598 addReply(c
,shared
.crlf
);
3601 static void incrCommand(redisClient
*c
) {
3602 incrDecrCommand(c
,1);
3605 static void decrCommand(redisClient
*c
) {
3606 incrDecrCommand(c
,-1);
3609 static void incrbyCommand(redisClient
*c
) {
3610 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3611 incrDecrCommand(c
,incr
);
3614 static void decrbyCommand(redisClient
*c
) {
3615 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3616 incrDecrCommand(c
,-incr
);
3619 /* ========================= Type agnostic commands ========================= */
3621 static void delCommand(redisClient
*c
) {
3624 for (j
= 1; j
< c
->argc
; j
++) {
3625 if (deleteKey(c
->db
,c
->argv
[j
])) {
3632 addReply(c
,shared
.czero
);
3635 addReply(c
,shared
.cone
);
3638 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",deleted
));
3643 static void existsCommand(redisClient
*c
) {
3644 addReply(c
,lookupKeyRead(c
->db
,c
->argv
[1]) ? shared
.cone
: shared
.czero
);
3647 static void selectCommand(redisClient
*c
) {
3648 int id
= atoi(c
->argv
[1]->ptr
);
3650 if (selectDb(c
,id
) == REDIS_ERR
) {
3651 addReplySds(c
,sdsnew("-ERR invalid DB index\r\n"));
3653 addReply(c
,shared
.ok
);
3657 static void randomkeyCommand(redisClient
*c
) {
3661 de
= dictGetRandomKey(c
->db
->dict
);
3662 if (!de
|| expireIfNeeded(c
->db
,dictGetEntryKey(de
)) == 0) break;
3665 addReply(c
,shared
.plus
);
3666 addReply(c
,shared
.crlf
);
3668 addReply(c
,shared
.plus
);
3669 addReply(c
,dictGetEntryKey(de
));
3670 addReply(c
,shared
.crlf
);
3674 static void keysCommand(redisClient
*c
) {
3677 sds pattern
= c
->argv
[1]->ptr
;
3678 int plen
= sdslen(pattern
);
3679 unsigned long numkeys
= 0, keyslen
= 0;
3680 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
3682 di
= dictGetIterator(c
->db
->dict
);
3684 decrRefCount(lenobj
);
3685 while((de
= dictNext(di
)) != NULL
) {
3686 robj
*keyobj
= dictGetEntryKey(de
);
3688 sds key
= keyobj
->ptr
;
3689 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
3690 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
3691 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
3693 addReply(c
,shared
.space
);
3696 keyslen
+= sdslen(key
);
3700 dictReleaseIterator(di
);
3701 lenobj
->ptr
= sdscatprintf(sdsempty(),"$%lu\r\n",keyslen
+(numkeys
? (numkeys
-1) : 0));
3702 addReply(c
,shared
.crlf
);
3705 static void dbsizeCommand(redisClient
*c
) {
3707 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c
->db
->dict
)));
3710 static void lastsaveCommand(redisClient
*c
) {
3712 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
3715 static void typeCommand(redisClient
*c
) {
3719 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3724 case REDIS_STRING
: type
= "+string"; break;
3725 case REDIS_LIST
: type
= "+list"; break;
3726 case REDIS_SET
: type
= "+set"; break;
3727 case REDIS_ZSET
: type
= "+zset"; break;
3728 default: type
= "unknown"; break;
3731 addReplySds(c
,sdsnew(type
));
3732 addReply(c
,shared
.crlf
);
3735 static void saveCommand(redisClient
*c
) {
3736 if (server
.bgsavechildpid
!= -1) {
3737 addReplySds(c
,sdsnew("-ERR background save in progress\r\n"));
3740 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
3741 addReply(c
,shared
.ok
);
3743 addReply(c
,shared
.err
);
3747 static void bgsaveCommand(redisClient
*c
) {
3748 if (server
.bgsavechildpid
!= -1) {
3749 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
3752 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
3753 char *status
= "+Background saving started\r\n";
3754 addReplySds(c
,sdsnew(status
));
3756 addReply(c
,shared
.err
);
3760 static void shutdownCommand(redisClient
*c
) {
3761 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
3762 /* Kill the saving child if there is a background saving in progress.
3763 We want to avoid race conditions, for instance our saving child may
3764 overwrite the synchronous saving did by SHUTDOWN. */
3765 if (server
.bgsavechildpid
!= -1) {
3766 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
3767 kill(server
.bgsavechildpid
,SIGKILL
);
3768 rdbRemoveTempFile(server
.bgsavechildpid
);
3770 if (server
.appendonly
) {
3771 /* Append only file: fsync() the AOF and exit */
3772 fsync(server
.appendfd
);
3775 /* Snapshotting. Perform a SYNC SAVE and exit */
3776 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
3777 if (server
.daemonize
)
3778 unlink(server
.pidfile
);
3779 redisLog(REDIS_WARNING
,"%zu bytes used at exit",zmalloc_used_memory());
3780 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
3783 /* Ooops.. error saving! The best we can do is to continue operating.
3784 * Note that if there was a background saving process, in the next
3785 * cron() Redis will be notified that the background saving aborted,
3786 * handling special stuff like slaves pending for synchronization... */
3787 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
3788 addReplySds(c
,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
3793 static void renameGenericCommand(redisClient
*c
, int nx
) {
3796 /* To use the same key as src and dst is probably an error */
3797 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
3798 addReply(c
,shared
.sameobjecterr
);
3802 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3804 addReply(c
,shared
.nokeyerr
);
3808 deleteIfVolatile(c
->db
,c
->argv
[2]);
3809 if (dictAdd(c
->db
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
3812 addReply(c
,shared
.czero
);
3815 dictReplace(c
->db
->dict
,c
->argv
[2],o
);
3817 incrRefCount(c
->argv
[2]);
3819 deleteKey(c
->db
,c
->argv
[1]);
3821 addReply(c
,nx
? shared
.cone
: shared
.ok
);
3824 static void renameCommand(redisClient
*c
) {
3825 renameGenericCommand(c
,0);
3828 static void renamenxCommand(redisClient
*c
) {
3829 renameGenericCommand(c
,1);
3832 static void moveCommand(redisClient
*c
) {
3837 /* Obtain source and target DB pointers */
3840 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
3841 addReply(c
,shared
.outofrangeerr
);
3845 selectDb(c
,srcid
); /* Back to the source DB */
3847 /* If the user is moving using as target the same
3848 * DB as the source DB it is probably an error. */
3850 addReply(c
,shared
.sameobjecterr
);
3854 /* Check if the element exists and get a reference */
3855 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3857 addReply(c
,shared
.czero
);
3861 /* Try to add the element to the target DB */
3862 deleteIfVolatile(dst
,c
->argv
[1]);
3863 if (dictAdd(dst
->dict
,c
->argv
[1],o
) == DICT_ERR
) {
3864 addReply(c
,shared
.czero
);
3867 incrRefCount(c
->argv
[1]);
3870 /* OK! key moved, free the entry in the source DB */
3871 deleteKey(src
,c
->argv
[1]);
3873 addReply(c
,shared
.cone
);
3876 /* =================================== Lists ================================ */
3877 static void pushGenericCommand(redisClient
*c
, int where
) {
3881 lobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3883 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
3884 addReply(c
,shared
.ok
);
3887 lobj
= createListObject();
3889 if (where
== REDIS_HEAD
) {
3890 listAddNodeHead(list
,c
->argv
[2]);
3892 listAddNodeTail(list
,c
->argv
[2]);
3894 dictAdd(c
->db
->dict
,c
->argv
[1],lobj
);
3895 incrRefCount(c
->argv
[1]);
3896 incrRefCount(c
->argv
[2]);
3898 if (lobj
->type
!= REDIS_LIST
) {
3899 addReply(c
,shared
.wrongtypeerr
);
3902 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
3903 addReply(c
,shared
.ok
);
3907 if (where
== REDIS_HEAD
) {
3908 listAddNodeHead(list
,c
->argv
[2]);
3910 listAddNodeTail(list
,c
->argv
[2]);
3912 incrRefCount(c
->argv
[2]);
3915 addReply(c
,shared
.ok
);
3918 static void lpushCommand(redisClient
*c
) {
3919 pushGenericCommand(c
,REDIS_HEAD
);
3922 static void rpushCommand(redisClient
*c
) {
3923 pushGenericCommand(c
,REDIS_TAIL
);
3926 static void llenCommand(redisClient
*c
) {
3930 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3932 addReply(c
,shared
.czero
);
3935 if (o
->type
!= REDIS_LIST
) {
3936 addReply(c
,shared
.wrongtypeerr
);
3939 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(l
)));
3944 static void lindexCommand(redisClient
*c
) {
3946 int index
= atoi(c
->argv
[2]->ptr
);
3948 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3950 addReply(c
,shared
.nullbulk
);
3952 if (o
->type
!= REDIS_LIST
) {
3953 addReply(c
,shared
.wrongtypeerr
);
3955 list
*list
= o
->ptr
;
3958 ln
= listIndex(list
, index
);
3960 addReply(c
,shared
.nullbulk
);
3962 robj
*ele
= listNodeValue(ln
);
3963 addReplyBulkLen(c
,ele
);
3965 addReply(c
,shared
.crlf
);
3971 static void lsetCommand(redisClient
*c
) {
3973 int index
= atoi(c
->argv
[2]->ptr
);
3975 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3977 addReply(c
,shared
.nokeyerr
);
3979 if (o
->type
!= REDIS_LIST
) {
3980 addReply(c
,shared
.wrongtypeerr
);
3982 list
*list
= o
->ptr
;
3985 ln
= listIndex(list
, index
);
3987 addReply(c
,shared
.outofrangeerr
);
3989 robj
*ele
= listNodeValue(ln
);
3992 listNodeValue(ln
) = c
->argv
[3];
3993 incrRefCount(c
->argv
[3]);
3994 addReply(c
,shared
.ok
);
4001 static void popGenericCommand(redisClient
*c
, int where
) {
4004 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4006 addReply(c
,shared
.nullbulk
);
4008 if (o
->type
!= REDIS_LIST
) {
4009 addReply(c
,shared
.wrongtypeerr
);
4011 list
*list
= o
->ptr
;
4014 if (where
== REDIS_HEAD
)
4015 ln
= listFirst(list
);
4017 ln
= listLast(list
);
4020 addReply(c
,shared
.nullbulk
);
4022 robj
*ele
= listNodeValue(ln
);
4023 addReplyBulkLen(c
,ele
);
4025 addReply(c
,shared
.crlf
);
4026 listDelNode(list
,ln
);
4033 static void lpopCommand(redisClient
*c
) {
4034 popGenericCommand(c
,REDIS_HEAD
);
4037 static void rpopCommand(redisClient
*c
) {
4038 popGenericCommand(c
,REDIS_TAIL
);
4041 static void lrangeCommand(redisClient
*c
) {
4043 int start
= atoi(c
->argv
[2]->ptr
);
4044 int end
= atoi(c
->argv
[3]->ptr
);
4046 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4048 addReply(c
,shared
.nullmultibulk
);
4050 if (o
->type
!= REDIS_LIST
) {
4051 addReply(c
,shared
.wrongtypeerr
);
4053 list
*list
= o
->ptr
;
4055 int llen
= listLength(list
);
4059 /* convert negative indexes */
4060 if (start
< 0) start
= llen
+start
;
4061 if (end
< 0) end
= llen
+end
;
4062 if (start
< 0) start
= 0;
4063 if (end
< 0) end
= 0;
4065 /* indexes sanity checks */
4066 if (start
> end
|| start
>= llen
) {
4067 /* Out of range start or start > end result in empty list */
4068 addReply(c
,shared
.emptymultibulk
);
4071 if (end
>= llen
) end
= llen
-1;
4072 rangelen
= (end
-start
)+1;
4074 /* Return the result in form of a multi-bulk reply */
4075 ln
= listIndex(list
, start
);
4076 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
4077 for (j
= 0; j
< rangelen
; j
++) {
4078 ele
= listNodeValue(ln
);
4079 addReplyBulkLen(c
,ele
);
4081 addReply(c
,shared
.crlf
);
4088 static void ltrimCommand(redisClient
*c
) {
4090 int start
= atoi(c
->argv
[2]->ptr
);
4091 int end
= atoi(c
->argv
[3]->ptr
);
4093 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4095 addReply(c
,shared
.ok
);
4097 if (o
->type
!= REDIS_LIST
) {
4098 addReply(c
,shared
.wrongtypeerr
);
4100 list
*list
= o
->ptr
;
4102 int llen
= listLength(list
);
4103 int j
, ltrim
, rtrim
;
4105 /* convert negative indexes */
4106 if (start
< 0) start
= llen
+start
;
4107 if (end
< 0) end
= llen
+end
;
4108 if (start
< 0) start
= 0;
4109 if (end
< 0) end
= 0;
4111 /* indexes sanity checks */
4112 if (start
> end
|| start
>= llen
) {
4113 /* Out of range start or start > end result in empty list */
4117 if (end
>= llen
) end
= llen
-1;
4122 /* Remove list elements to perform the trim */
4123 for (j
= 0; j
< ltrim
; j
++) {
4124 ln
= listFirst(list
);
4125 listDelNode(list
,ln
);
4127 for (j
= 0; j
< rtrim
; j
++) {
4128 ln
= listLast(list
);
4129 listDelNode(list
,ln
);
4132 addReply(c
,shared
.ok
);
4137 static void lremCommand(redisClient
*c
) {
4140 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4142 addReply(c
,shared
.czero
);
4144 if (o
->type
!= REDIS_LIST
) {
4145 addReply(c
,shared
.wrongtypeerr
);
4147 list
*list
= o
->ptr
;
4148 listNode
*ln
, *next
;
4149 int toremove
= atoi(c
->argv
[2]->ptr
);
4154 toremove
= -toremove
;
4157 ln
= fromtail
? list
->tail
: list
->head
;
4159 robj
*ele
= listNodeValue(ln
);
4161 next
= fromtail
? ln
->prev
: ln
->next
;
4162 if (compareStringObjects(ele
,c
->argv
[3]) == 0) {
4163 listDelNode(list
,ln
);
4166 if (toremove
&& removed
== toremove
) break;
4170 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
4175 /* This is the semantic of this command:
4176 * RPOPLPUSH srclist dstlist:
4177 * IF LLEN(srclist) > 0
4178 * element = RPOP srclist
4179 * LPUSH dstlist element
4186 * The idea is to be able to get an element from a list in a reliable way
4187 * since the element is not just returned but pushed against another list
4188 * as well. This command was originally proposed by Ezra Zygmuntowicz.
4190 static void rpoplpushcommand(redisClient
*c
) {
4193 sobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4195 addReply(c
,shared
.nullbulk
);
4197 if (sobj
->type
!= REDIS_LIST
) {
4198 addReply(c
,shared
.wrongtypeerr
);
4200 list
*srclist
= sobj
->ptr
;
4201 listNode
*ln
= listLast(srclist
);
4204 addReply(c
,shared
.nullbulk
);
4206 robj
*dobj
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4207 robj
*ele
= listNodeValue(ln
);
4210 if (dobj
&& dobj
->type
!= REDIS_LIST
) {
4211 addReply(c
,shared
.wrongtypeerr
);
4215 /* Add the element to the target list (unless it's directly
4216 * passed to some BLPOP-ing client */
4217 if (!handleClientsWaitingListPush(c
,c
->argv
[2],ele
)) {
4219 /* Create the list if the key does not exist */
4220 dobj
= createListObject();
4221 dictAdd(c
->db
->dict
,c
->argv
[2],dobj
);
4222 incrRefCount(c
->argv
[2]);
4224 dstlist
= dobj
->ptr
;
4225 listAddNodeHead(dstlist
,ele
);
4229 /* Send the element to the client as reply as well */
4230 addReplyBulkLen(c
,ele
);
4232 addReply(c
,shared
.crlf
);
4234 /* Finally remove the element from the source list */
4235 listDelNode(srclist
,ln
);
4243 /* ==================================== Sets ================================ */
4245 static void saddCommand(redisClient
*c
) {
4248 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4250 set
= createSetObject();
4251 dictAdd(c
->db
->dict
,c
->argv
[1],set
);
4252 incrRefCount(c
->argv
[1]);
4254 if (set
->type
!= REDIS_SET
) {
4255 addReply(c
,shared
.wrongtypeerr
);
4259 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
4260 incrRefCount(c
->argv
[2]);
4262 addReply(c
,shared
.cone
);
4264 addReply(c
,shared
.czero
);
4268 static void sremCommand(redisClient
*c
) {
4271 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4273 addReply(c
,shared
.czero
);
4275 if (set
->type
!= REDIS_SET
) {
4276 addReply(c
,shared
.wrongtypeerr
);
4279 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
4281 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4282 addReply(c
,shared
.cone
);
4284 addReply(c
,shared
.czero
);
4289 static void smoveCommand(redisClient
*c
) {
4290 robj
*srcset
, *dstset
;
4292 srcset
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4293 dstset
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4295 /* If the source key does not exist return 0, if it's of the wrong type
4297 if (srcset
== NULL
|| srcset
->type
!= REDIS_SET
) {
4298 addReply(c
, srcset
? shared
.wrongtypeerr
: shared
.czero
);
4301 /* Error if the destination key is not a set as well */
4302 if (dstset
&& dstset
->type
!= REDIS_SET
) {
4303 addReply(c
,shared
.wrongtypeerr
);
4306 /* Remove the element from the source set */
4307 if (dictDelete(srcset
->ptr
,c
->argv
[3]) == DICT_ERR
) {
4308 /* Key not found in the src set! return zero */
4309 addReply(c
,shared
.czero
);
4313 /* Add the element to the destination set */
4315 dstset
= createSetObject();
4316 dictAdd(c
->db
->dict
,c
->argv
[2],dstset
);
4317 incrRefCount(c
->argv
[2]);
4319 if (dictAdd(dstset
->ptr
,c
->argv
[3],NULL
) == DICT_OK
)
4320 incrRefCount(c
->argv
[3]);
4321 addReply(c
,shared
.cone
);
4324 static void sismemberCommand(redisClient
*c
) {
4327 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
4329 addReply(c
,shared
.czero
);
4331 if (set
->type
!= REDIS_SET
) {
4332 addReply(c
,shared
.wrongtypeerr
);
4335 if (dictFind(set
->ptr
,c
->argv
[2]))
4336 addReply(c
,shared
.cone
);
4338 addReply(c
,shared
.czero
);
4342 static void scardCommand(redisClient
*c
) {
4346 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4348 addReply(c
,shared
.czero
);
4351 if (o
->type
!= REDIS_SET
) {
4352 addReply(c
,shared
.wrongtypeerr
);
4355 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4361 static void spopCommand(redisClient
*c
) {
4365 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4367 addReply(c
,shared
.nullbulk
);
4369 if (set
->type
!= REDIS_SET
) {
4370 addReply(c
,shared
.wrongtypeerr
);
4373 de
= dictGetRandomKey(set
->ptr
);
4375 addReply(c
,shared
.nullbulk
);
4377 robj
*ele
= dictGetEntryKey(de
);
4379 addReplyBulkLen(c
,ele
);
4381 addReply(c
,shared
.crlf
);
4382 dictDelete(set
->ptr
,ele
);
4383 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4389 static void srandmemberCommand(redisClient
*c
) {
4393 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
4395 addReply(c
,shared
.nullbulk
);
4397 if (set
->type
!= REDIS_SET
) {
4398 addReply(c
,shared
.wrongtypeerr
);
4401 de
= dictGetRandomKey(set
->ptr
);
4403 addReply(c
,shared
.nullbulk
);
4405 robj
*ele
= dictGetEntryKey(de
);
4407 addReplyBulkLen(c
,ele
);
4409 addReply(c
,shared
.crlf
);
4414 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
4415 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
4417 return dictSize(*d1
)-dictSize(*d2
);
4420 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, unsigned long setsnum
, robj
*dstkey
) {
4421 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4424 robj
*lenobj
= NULL
, *dstset
= NULL
;
4425 unsigned long j
, cardinality
= 0;
4427 for (j
= 0; j
< setsnum
; j
++) {
4431 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4432 lookupKeyRead(c
->db
,setskeys
[j
]);
4436 if (deleteKey(c
->db
,dstkey
))
4438 addReply(c
,shared
.czero
);
4440 addReply(c
,shared
.nullmultibulk
);
4444 if (setobj
->type
!= REDIS_SET
) {
4446 addReply(c
,shared
.wrongtypeerr
);
4449 dv
[j
] = setobj
->ptr
;
4451 /* Sort sets from the smallest to largest, this will improve our
4452 * algorithm's performace */
4453 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
4455 /* The first thing we should output is the total number of elements...
4456 * since this is a multi-bulk write, but at this stage we don't know
4457 * the intersection set size, so we use a trick, append an empty object
4458 * to the output list and save the pointer to later modify it with the
4461 lenobj
= createObject(REDIS_STRING
,NULL
);
4463 decrRefCount(lenobj
);
4465 /* If we have a target key where to store the resulting set
4466 * create this key with an empty set inside */
4467 dstset
= createSetObject();
4470 /* Iterate all the elements of the first (smallest) set, and test
4471 * the element against all the other sets, if at least one set does
4472 * not include the element it is discarded */
4473 di
= dictGetIterator(dv
[0]);
4475 while((de
= dictNext(di
)) != NULL
) {
4478 for (j
= 1; j
< setsnum
; j
++)
4479 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
4481 continue; /* at least one set does not contain the member */
4482 ele
= dictGetEntryKey(de
);
4484 addReplyBulkLen(c
,ele
);
4486 addReply(c
,shared
.crlf
);
4489 dictAdd(dstset
->ptr
,ele
,NULL
);
4493 dictReleaseIterator(di
);
4496 /* Store the resulting set into the target */
4497 deleteKey(c
->db
,dstkey
);
4498 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4499 incrRefCount(dstkey
);
4503 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",cardinality
);
4505 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4506 dictSize((dict
*)dstset
->ptr
)));
4512 static void sinterCommand(redisClient
*c
) {
4513 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
4516 static void sinterstoreCommand(redisClient
*c
) {
4517 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
4520 #define REDIS_OP_UNION 0
4521 #define REDIS_OP_DIFF 1
4523 static void sunionDiffGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
, int op
) {
4524 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4527 robj
*dstset
= NULL
;
4528 int j
, cardinality
= 0;
4530 for (j
= 0; j
< setsnum
; j
++) {
4534 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4535 lookupKeyRead(c
->db
,setskeys
[j
]);
4540 if (setobj
->type
!= REDIS_SET
) {
4542 addReply(c
,shared
.wrongtypeerr
);
4545 dv
[j
] = setobj
->ptr
;
4548 /* We need a temp set object to store our union. If the dstkey
4549 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
4550 * this set object will be the resulting object to set into the target key*/
4551 dstset
= createSetObject();
4553 /* Iterate all the elements of all the sets, add every element a single
4554 * time to the result set */
4555 for (j
= 0; j
< setsnum
; j
++) {
4556 if (op
== REDIS_OP_DIFF
&& j
== 0 && !dv
[j
]) break; /* result set is empty */
4557 if (!dv
[j
]) continue; /* non existing keys are like empty sets */
4559 di
= dictGetIterator(dv
[j
]);
4561 while((de
= dictNext(di
)) != NULL
) {
4564 /* dictAdd will not add the same element multiple times */
4565 ele
= dictGetEntryKey(de
);
4566 if (op
== REDIS_OP_UNION
|| j
== 0) {
4567 if (dictAdd(dstset
->ptr
,ele
,NULL
) == DICT_OK
) {
4571 } else if (op
== REDIS_OP_DIFF
) {
4572 if (dictDelete(dstset
->ptr
,ele
) == DICT_OK
) {
4577 dictReleaseIterator(di
);
4579 if (op
== REDIS_OP_DIFF
&& cardinality
== 0) break; /* result set is empty */
4582 /* Output the content of the resulting set, if not in STORE mode */
4584 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",cardinality
));
4585 di
= dictGetIterator(dstset
->ptr
);
4586 while((de
= dictNext(di
)) != NULL
) {
4589 ele
= dictGetEntryKey(de
);
4590 addReplyBulkLen(c
,ele
);
4592 addReply(c
,shared
.crlf
);
4594 dictReleaseIterator(di
);
4596 /* If we have a target key where to store the resulting set
4597 * create this key with the result set inside */
4598 deleteKey(c
->db
,dstkey
);
4599 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4600 incrRefCount(dstkey
);
4605 decrRefCount(dstset
);
4607 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4608 dictSize((dict
*)dstset
->ptr
)));
4614 static void sunionCommand(redisClient
*c
) {
4615 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_UNION
);
4618 static void sunionstoreCommand(redisClient
*c
) {
4619 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_UNION
);
4622 static void sdiffCommand(redisClient
*c
) {
4623 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_DIFF
);
4626 static void sdiffstoreCommand(redisClient
*c
) {
4627 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_DIFF
);
4630 /* ==================================== ZSets =============================== */
4632 /* ZSETs are ordered sets using two data structures to hold the same elements
4633 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
4636 * The elements are added to an hash table mapping Redis objects to scores.
4637 * At the same time the elements are added to a skip list mapping scores
4638 * to Redis objects (so objects are sorted by scores in this "view"). */
4640 /* This skiplist implementation is almost a C translation of the original
4641 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
4642 * Alternative to Balanced Trees", modified in three ways:
4643 * a) this implementation allows for repeated values.
4644 * b) the comparison is not just by key (our 'score') but by satellite data.
4645 * c) there is a back pointer, so it's a doubly linked list with the back
4646 * pointers being only at "level 1". This allows to traverse the list
4647 * from tail to head, useful for ZREVRANGE. */
4649 static zskiplistNode
*zslCreateNode(int level
, double score
, robj
*obj
) {
4650 zskiplistNode
*zn
= zmalloc(sizeof(*zn
));
4652 zn
->forward
= zmalloc(sizeof(zskiplistNode
*) * level
);
4658 static zskiplist
*zslCreate(void) {
4662 zsl
= zmalloc(sizeof(*zsl
));
4665 zsl
->header
= zslCreateNode(ZSKIPLIST_MAXLEVEL
,0,NULL
);
4666 for (j
= 0; j
< ZSKIPLIST_MAXLEVEL
; j
++)
4667 zsl
->header
->forward
[j
] = NULL
;
4668 zsl
->header
->backward
= NULL
;
4673 static void zslFreeNode(zskiplistNode
*node
) {
4674 decrRefCount(node
->obj
);
4675 zfree(node
->forward
);
4679 static void zslFree(zskiplist
*zsl
) {
4680 zskiplistNode
*node
= zsl
->header
->forward
[0], *next
;
4682 zfree(zsl
->header
->forward
);
4685 next
= node
->forward
[0];
4692 static int zslRandomLevel(void) {
4694 while ((random()&0xFFFF) < (ZSKIPLIST_P
* 0xFFFF))
4699 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
) {
4700 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4704 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4705 while (x
->forward
[i
] &&
4706 (x
->forward
[i
]->score
< score
||
4707 (x
->forward
[i
]->score
== score
&&
4708 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
4712 /* we assume the key is not already inside, since we allow duplicated
4713 * scores, and the re-insertion of score and redis object should never
4714 * happpen since the caller of zslInsert() should test in the hash table
4715 * if the element is already inside or not. */
4716 level
= zslRandomLevel();
4717 if (level
> zsl
->level
) {
4718 for (i
= zsl
->level
; i
< level
; i
++)
4719 update
[i
] = zsl
->header
;
4722 x
= zslCreateNode(level
,score
,obj
);
4723 for (i
= 0; i
< level
; i
++) {
4724 x
->forward
[i
] = update
[i
]->forward
[i
];
4725 update
[i
]->forward
[i
] = x
;
4727 x
->backward
= (update
[0] == zsl
->header
) ? NULL
: update
[0];
4729 x
->forward
[0]->backward
= x
;
4735 /* Delete an element with matching score/object from the skiplist. */
4736 static int zslDelete(zskiplist
*zsl
, double score
, robj
*obj
) {
4737 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4741 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4742 while (x
->forward
[i
] &&
4743 (x
->forward
[i
]->score
< score
||
4744 (x
->forward
[i
]->score
== score
&&
4745 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
4749 /* We may have multiple elements with the same score, what we need
4750 * is to find the element with both the right score and object. */
4752 if (x
&& score
== x
->score
&& compareStringObjects(x
->obj
,obj
) == 0) {
4753 for (i
= 0; i
< zsl
->level
; i
++) {
4754 if (update
[i
]->forward
[i
] != x
) break;
4755 update
[i
]->forward
[i
] = x
->forward
[i
];
4757 if (x
->forward
[0]) {
4758 x
->forward
[0]->backward
= (x
->backward
== zsl
->header
) ?
4761 zsl
->tail
= x
->backward
;
4764 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
4769 return 0; /* not found */
4771 return 0; /* not found */
4774 /* Delete all the elements with score between min and max from the skiplist.
4775 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
4776 * Note that this function takes the reference to the hash table view of the
4777 * sorted set, in order to remove the elements from the hash table too. */
4778 static unsigned long zslDeleteRange(zskiplist
*zsl
, double min
, double max
, dict
*dict
) {
4779 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4780 unsigned long removed
= 0;
4784 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4785 while (x
->forward
[i
] && x
->forward
[i
]->score
< min
)
4789 /* We may have multiple elements with the same score, what we need
4790 * is to find the element with both the right score and object. */
4792 while (x
&& x
->score
<= max
) {
4793 zskiplistNode
*next
;
4795 for (i
= 0; i
< zsl
->level
; i
++) {
4796 if (update
[i
]->forward
[i
] != x
) break;
4797 update
[i
]->forward
[i
] = x
->forward
[i
];
4799 if (x
->forward
[0]) {
4800 x
->forward
[0]->backward
= (x
->backward
== zsl
->header
) ?
4803 zsl
->tail
= x
->backward
;
4805 next
= x
->forward
[0];
4806 dictDelete(dict
,x
->obj
);
4808 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
4814 return removed
; /* not found */
4817 /* Find the first node having a score equal or greater than the specified one.
4818 * Returns NULL if there is no match. */
4819 static zskiplistNode
*zslFirstWithScore(zskiplist
*zsl
, double score
) {
4824 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4825 while (x
->forward
[i
] && x
->forward
[i
]->score
< score
)
4828 /* We may have multiple elements with the same score, what we need
4829 * is to find the element with both the right score and object. */
4830 return x
->forward
[0];
4833 /* The actual Z-commands implementations */
4835 /* This generic command implements both ZADD and ZINCRBY.
4836 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
4837 * the increment if the operation is a ZINCRBY (doincrement == 1). */
4838 static void zaddGenericCommand(redisClient
*c
, robj
*key
, robj
*ele
, double scoreval
, int doincrement
) {
4843 zsetobj
= lookupKeyWrite(c
->db
,key
);
4844 if (zsetobj
== NULL
) {
4845 zsetobj
= createZsetObject();
4846 dictAdd(c
->db
->dict
,key
,zsetobj
);
4849 if (zsetobj
->type
!= REDIS_ZSET
) {
4850 addReply(c
,shared
.wrongtypeerr
);
4856 /* Ok now since we implement both ZADD and ZINCRBY here the code
4857 * needs to handle the two different conditions. It's all about setting
4858 * '*score', that is, the new score to set, to the right value. */
4859 score
= zmalloc(sizeof(double));
4863 /* Read the old score. If the element was not present starts from 0 */
4864 de
= dictFind(zs
->dict
,ele
);
4866 double *oldscore
= dictGetEntryVal(de
);
4867 *score
= *oldscore
+ scoreval
;
4875 /* What follows is a simple remove and re-insert operation that is common
4876 * to both ZADD and ZINCRBY... */
4877 if (dictAdd(zs
->dict
,ele
,score
) == DICT_OK
) {
4878 /* case 1: New element */
4879 incrRefCount(ele
); /* added to hash */
4880 zslInsert(zs
->zsl
,*score
,ele
);
4881 incrRefCount(ele
); /* added to skiplist */
4884 addReplyDouble(c
,*score
);
4886 addReply(c
,shared
.cone
);
4891 /* case 2: Score update operation */
4892 de
= dictFind(zs
->dict
,ele
);
4893 redisAssert(de
!= NULL
);
4894 oldscore
= dictGetEntryVal(de
);
4895 if (*score
!= *oldscore
) {
4898 /* Remove and insert the element in the skip list with new score */
4899 deleted
= zslDelete(zs
->zsl
,*oldscore
,ele
);
4900 redisAssert(deleted
!= 0);
4901 zslInsert(zs
->zsl
,*score
,ele
);
4903 /* Update the score in the hash table */
4904 dictReplace(zs
->dict
,ele
,score
);
4910 addReplyDouble(c
,*score
);
4912 addReply(c
,shared
.czero
);
4916 static void zaddCommand(redisClient
*c
) {
4919 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
4920 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,0);
4923 static void zincrbyCommand(redisClient
*c
) {
4926 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
4927 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,1);
4930 static void zremCommand(redisClient
*c
) {
4934 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4935 if (zsetobj
== NULL
) {
4936 addReply(c
,shared
.czero
);
4942 if (zsetobj
->type
!= REDIS_ZSET
) {
4943 addReply(c
,shared
.wrongtypeerr
);
4947 de
= dictFind(zs
->dict
,c
->argv
[2]);
4949 addReply(c
,shared
.czero
);
4952 /* Delete from the skiplist */
4953 oldscore
= dictGetEntryVal(de
);
4954 deleted
= zslDelete(zs
->zsl
,*oldscore
,c
->argv
[2]);
4955 redisAssert(deleted
!= 0);
4957 /* Delete from the hash table */
4958 dictDelete(zs
->dict
,c
->argv
[2]);
4959 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
4961 addReply(c
,shared
.cone
);
4965 static void zremrangebyscoreCommand(redisClient
*c
) {
4966 double min
= strtod(c
->argv
[2]->ptr
,NULL
);
4967 double max
= strtod(c
->argv
[3]->ptr
,NULL
);
4971 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4972 if (zsetobj
== NULL
) {
4973 addReply(c
,shared
.czero
);
4977 if (zsetobj
->type
!= REDIS_ZSET
) {
4978 addReply(c
,shared
.wrongtypeerr
);
4982 deleted
= zslDeleteRange(zs
->zsl
,min
,max
,zs
->dict
);
4983 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
4984 server
.dirty
+= deleted
;
4985 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",deleted
));
4989 static void zrangeGenericCommand(redisClient
*c
, int reverse
) {
4991 int start
= atoi(c
->argv
[2]->ptr
);
4992 int end
= atoi(c
->argv
[3]->ptr
);
4995 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
4997 } else if (c
->argc
>= 5) {
4998 addReply(c
,shared
.syntaxerr
);
5002 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5004 addReply(c
,shared
.nullmultibulk
);
5006 if (o
->type
!= REDIS_ZSET
) {
5007 addReply(c
,shared
.wrongtypeerr
);
5009 zset
*zsetobj
= o
->ptr
;
5010 zskiplist
*zsl
= zsetobj
->zsl
;
5013 int llen
= zsl
->length
;
5017 /* convert negative indexes */
5018 if (start
< 0) start
= llen
+start
;
5019 if (end
< 0) end
= llen
+end
;
5020 if (start
< 0) start
= 0;
5021 if (end
< 0) end
= 0;
5023 /* indexes sanity checks */
5024 if (start
> end
|| start
>= llen
) {
5025 /* Out of range start or start > end result in empty list */
5026 addReply(c
,shared
.emptymultibulk
);
5029 if (end
>= llen
) end
= llen
-1;
5030 rangelen
= (end
-start
)+1;
5032 /* Return the result in form of a multi-bulk reply */
5038 ln
= zsl
->header
->forward
[0];
5040 ln
= ln
->forward
[0];
5043 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",
5044 withscores
? (rangelen
*2) : rangelen
));
5045 for (j
= 0; j
< rangelen
; j
++) {
5047 addReplyBulkLen(c
,ele
);
5049 addReply(c
,shared
.crlf
);
5051 addReplyDouble(c
,ln
->score
);
5052 ln
= reverse
? ln
->backward
: ln
->forward
[0];
5058 static void zrangeCommand(redisClient
*c
) {
5059 zrangeGenericCommand(c
,0);
5062 static void zrevrangeCommand(redisClient
*c
) {
5063 zrangeGenericCommand(c
,1);
5066 static void zrangebyscoreCommand(redisClient
*c
) {
5068 double min
= strtod(c
->argv
[2]->ptr
,NULL
);
5069 double max
= strtod(c
->argv
[3]->ptr
,NULL
);
5070 int offset
= 0, limit
= -1;
5072 if (c
->argc
!= 4 && c
->argc
!= 7) {
5074 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
5076 } else if (c
->argc
== 7 && strcasecmp(c
->argv
[4]->ptr
,"limit")) {
5077 addReply(c
,shared
.syntaxerr
);
5079 } else if (c
->argc
== 7) {
5080 offset
= atoi(c
->argv
[5]->ptr
);
5081 limit
= atoi(c
->argv
[6]->ptr
);
5082 if (offset
< 0) offset
= 0;
5085 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5087 addReply(c
,shared
.nullmultibulk
);
5089 if (o
->type
!= REDIS_ZSET
) {
5090 addReply(c
,shared
.wrongtypeerr
);
5092 zset
*zsetobj
= o
->ptr
;
5093 zskiplist
*zsl
= zsetobj
->zsl
;
5096 unsigned int rangelen
= 0;
5098 /* Get the first node with the score >= min */
5099 ln
= zslFirstWithScore(zsl
,min
);
5101 /* No element matching the speciifed interval */
5102 addReply(c
,shared
.emptymultibulk
);
5106 /* We don't know in advance how many matching elements there
5107 * are in the list, so we push this object that will represent
5108 * the multi-bulk length in the output buffer, and will "fix"
5110 lenobj
= createObject(REDIS_STRING
,NULL
);
5112 decrRefCount(lenobj
);
5114 while(ln
&& ln
->score
<= max
) {
5117 ln
= ln
->forward
[0];
5120 if (limit
== 0) break;
5122 addReplyBulkLen(c
,ele
);
5124 addReply(c
,shared
.crlf
);
5125 ln
= ln
->forward
[0];
5127 if (limit
> 0) limit
--;
5129 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%d\r\n",rangelen
);
5134 static void zcardCommand(redisClient
*c
) {
5138 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5140 addReply(c
,shared
.czero
);
5143 if (o
->type
!= REDIS_ZSET
) {
5144 addReply(c
,shared
.wrongtypeerr
);
5147 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",zs
->zsl
->length
));
5152 static void zscoreCommand(redisClient
*c
) {
5156 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5158 addReply(c
,shared
.nullbulk
);
5161 if (o
->type
!= REDIS_ZSET
) {
5162 addReply(c
,shared
.wrongtypeerr
);
5167 de
= dictFind(zs
->dict
,c
->argv
[2]);
5169 addReply(c
,shared
.nullbulk
);
5171 double *score
= dictGetEntryVal(de
);
5173 addReplyDouble(c
,*score
);
5179 /* ========================= Non type-specific commands ==================== */
5181 static void flushdbCommand(redisClient
*c
) {
5182 server
.dirty
+= dictSize(c
->db
->dict
);
5183 dictEmpty(c
->db
->dict
);
5184 dictEmpty(c
->db
->expires
);
5185 addReply(c
,shared
.ok
);
5188 static void flushallCommand(redisClient
*c
) {
5189 server
.dirty
+= emptyDb();
5190 addReply(c
,shared
.ok
);
5191 rdbSave(server
.dbfilename
);
5195 static redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
5196 redisSortOperation
*so
= zmalloc(sizeof(*so
));
5198 so
->pattern
= pattern
;
5202 /* Return the value associated to the key with a name obtained
5203 * substituting the first occurence of '*' in 'pattern' with 'subst' */
5204 static robj
*lookupKeyByPattern(redisDb
*db
, robj
*pattern
, robj
*subst
) {
5208 int prefixlen
, sublen
, postfixlen
;
5209 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
5213 char buf
[REDIS_SORTKEY_MAX
+1];
5216 /* If the pattern is "#" return the substitution object itself in order
5217 * to implement the "SORT ... GET #" feature. */
5218 spat
= pattern
->ptr
;
5219 if (spat
[0] == '#' && spat
[1] == '\0') {
5223 /* The substitution object may be specially encoded. If so we create
5224 * a decoded object on the fly. Otherwise getDecodedObject will just
5225 * increment the ref count, that we'll decrement later. */
5226 subst
= getDecodedObject(subst
);
5229 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
5230 p
= strchr(spat
,'*');
5232 decrRefCount(subst
);
5237 sublen
= sdslen(ssub
);
5238 postfixlen
= sdslen(spat
)-(prefixlen
+1);
5239 memcpy(keyname
.buf
,spat
,prefixlen
);
5240 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
5241 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
5242 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
5243 keyname
.len
= prefixlen
+sublen
+postfixlen
;
5245 initStaticStringObject(keyobj
,((char*)&keyname
)+(sizeof(long)*2))
5246 decrRefCount(subst
);
5248 /* printf("lookup '%s' => %p\n", keyname.buf,de); */
5249 return lookupKeyRead(db
,&keyobj
);
5252 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
5253 * the additional parameter is not standard but a BSD-specific we have to
5254 * pass sorting parameters via the global 'server' structure */
5255 static int sortCompare(const void *s1
, const void *s2
) {
5256 const redisSortObject
*so1
= s1
, *so2
= s2
;
5259 if (!server
.sort_alpha
) {
5260 /* Numeric sorting. Here it's trivial as we precomputed scores */
5261 if (so1
->u
.score
> so2
->u
.score
) {
5263 } else if (so1
->u
.score
< so2
->u
.score
) {
5269 /* Alphanumeric sorting */
5270 if (server
.sort_bypattern
) {
5271 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
5272 /* At least one compare object is NULL */
5273 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
5275 else if (so1
->u
.cmpobj
== NULL
)
5280 /* We have both the objects, use strcoll */
5281 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
5284 /* Compare elements directly */
5287 dec1
= getDecodedObject(so1
->obj
);
5288 dec2
= getDecodedObject(so2
->obj
);
5289 cmp
= strcoll(dec1
->ptr
,dec2
->ptr
);
5294 return server
.sort_desc
? -cmp
: cmp
;
5297 /* The SORT command is the most complex command in Redis. Warning: this code
5298 * is optimized for speed and a bit less for readability */
5299 static void sortCommand(redisClient
*c
) {
5302 int desc
= 0, alpha
= 0;
5303 int limit_start
= 0, limit_count
= -1, start
, end
;
5304 int j
, dontsort
= 0, vectorlen
;
5305 int getop
= 0; /* GET operation counter */
5306 robj
*sortval
, *sortby
= NULL
, *storekey
= NULL
;
5307 redisSortObject
*vector
; /* Resulting vector to sort */
5309 /* Lookup the key to sort. It must be of the right types */
5310 sortval
= lookupKeyRead(c
->db
,c
->argv
[1]);
5311 if (sortval
== NULL
) {
5312 addReply(c
,shared
.nullmultibulk
);
5315 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
&&
5316 sortval
->type
!= REDIS_ZSET
)
5318 addReply(c
,shared
.wrongtypeerr
);
5322 /* Create a list of operations to perform for every sorted element.
5323 * Operations can be GET/DEL/INCR/DECR */
5324 operations
= listCreate();
5325 listSetFreeMethod(operations
,zfree
);
5328 /* Now we need to protect sortval incrementing its count, in the future
5329 * SORT may have options able to overwrite/delete keys during the sorting
5330 * and the sorted key itself may get destroied */
5331 incrRefCount(sortval
);
5333 /* The SORT command has an SQL-alike syntax, parse it */
5334 while(j
< c
->argc
) {
5335 int leftargs
= c
->argc
-j
-1;
5336 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
5338 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
5340 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
5342 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
5343 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
5344 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
5346 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"store") && leftargs
>= 1) {
5347 storekey
= c
->argv
[j
+1];
5349 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
5350 sortby
= c
->argv
[j
+1];
5351 /* If the BY pattern does not contain '*', i.e. it is constant,
5352 * we don't need to sort nor to lookup the weight keys. */
5353 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
5355 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
5356 listAddNodeTail(operations
,createSortOperation(
5357 REDIS_SORT_GET
,c
->argv
[j
+1]));
5361 decrRefCount(sortval
);
5362 listRelease(operations
);
5363 addReply(c
,shared
.syntaxerr
);
5369 /* Load the sorting vector with all the objects to sort */
5370 switch(sortval
->type
) {
5371 case REDIS_LIST
: vectorlen
= listLength((list
*)sortval
->ptr
); break;
5372 case REDIS_SET
: vectorlen
= dictSize((dict
*)sortval
->ptr
); break;
5373 case REDIS_ZSET
: vectorlen
= dictSize(((zset
*)sortval
->ptr
)->dict
); break;
5374 default: vectorlen
= 0; redisAssert(0); /* Avoid GCC warning */
5376 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
5379 if (sortval
->type
== REDIS_LIST
) {
5380 list
*list
= sortval
->ptr
;
5384 listRewind(list
,&li
);
5385 while((ln
= listNext(&li
))) {
5386 robj
*ele
= ln
->value
;
5387 vector
[j
].obj
= ele
;
5388 vector
[j
].u
.score
= 0;
5389 vector
[j
].u
.cmpobj
= NULL
;
5397 if (sortval
->type
== REDIS_SET
) {
5400 zset
*zs
= sortval
->ptr
;
5404 di
= dictGetIterator(set
);
5405 while((setele
= dictNext(di
)) != NULL
) {
5406 vector
[j
].obj
= dictGetEntryKey(setele
);
5407 vector
[j
].u
.score
= 0;
5408 vector
[j
].u
.cmpobj
= NULL
;
5411 dictReleaseIterator(di
);
5413 redisAssert(j
== vectorlen
);
5415 /* Now it's time to load the right scores in the sorting vector */
5416 if (dontsort
== 0) {
5417 for (j
= 0; j
< vectorlen
; j
++) {
5421 byval
= lookupKeyByPattern(c
->db
,sortby
,vector
[j
].obj
);
5422 if (!byval
|| byval
->type
!= REDIS_STRING
) continue;
5424 vector
[j
].u
.cmpobj
= getDecodedObject(byval
);
5426 if (byval
->encoding
== REDIS_ENCODING_RAW
) {
5427 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
5429 /* Don't need to decode the object if it's
5430 * integer-encoded (the only encoding supported) so
5431 * far. We can just cast it */
5432 if (byval
->encoding
== REDIS_ENCODING_INT
) {
5433 vector
[j
].u
.score
= (long)byval
->ptr
;
5435 redisAssert(1 != 1);
5440 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_RAW
)
5441 vector
[j
].u
.score
= strtod(vector
[j
].obj
->ptr
,NULL
);
5443 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_INT
)
5444 vector
[j
].u
.score
= (long) vector
[j
].obj
->ptr
;
5446 redisAssert(1 != 1);
5453 /* We are ready to sort the vector... perform a bit of sanity check
5454 * on the LIMIT option too. We'll use a partial version of quicksort. */
5455 start
= (limit_start
< 0) ? 0 : limit_start
;
5456 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
5457 if (start
>= vectorlen
) {
5458 start
= vectorlen
-1;
5461 if (end
>= vectorlen
) end
= vectorlen
-1;
5463 if (dontsort
== 0) {
5464 server
.sort_desc
= desc
;
5465 server
.sort_alpha
= alpha
;
5466 server
.sort_bypattern
= sortby
? 1 : 0;
5467 if (sortby
&& (start
!= 0 || end
!= vectorlen
-1))
5468 pqsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
, start
,end
);
5470 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
5473 /* Send command output to the output buffer, performing the specified
5474 * GET/DEL/INCR/DECR operations if any. */
5475 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
5476 if (storekey
== NULL
) {
5477 /* STORE option not specified, sent the sorting result to client */
5478 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
5479 for (j
= start
; j
<= end
; j
++) {
5484 addReplyBulkLen(c
,vector
[j
].obj
);
5485 addReply(c
,vector
[j
].obj
);
5486 addReply(c
,shared
.crlf
);
5488 listRewind(operations
,&li
);
5489 while((ln
= listNext(&li
))) {
5490 redisSortOperation
*sop
= ln
->value
;
5491 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
5494 if (sop
->type
== REDIS_SORT_GET
) {
5495 if (!val
|| val
->type
!= REDIS_STRING
) {
5496 addReply(c
,shared
.nullbulk
);
5498 addReplyBulkLen(c
,val
);
5500 addReply(c
,shared
.crlf
);
5503 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
5508 robj
*listObject
= createListObject();
5509 list
*listPtr
= (list
*) listObject
->ptr
;
5511 /* STORE option specified, set the sorting result as a List object */
5512 for (j
= start
; j
<= end
; j
++) {
5517 listAddNodeTail(listPtr
,vector
[j
].obj
);
5518 incrRefCount(vector
[j
].obj
);
5520 listRewind(operations
,&li
);
5521 while((ln
= listNext(&li
))) {
5522 redisSortOperation
*sop
= ln
->value
;
5523 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
5526 if (sop
->type
== REDIS_SORT_GET
) {
5527 if (!val
|| val
->type
!= REDIS_STRING
) {
5528 listAddNodeTail(listPtr
,createStringObject("",0));
5530 listAddNodeTail(listPtr
,val
);
5534 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
5538 if (dictReplace(c
->db
->dict
,storekey
,listObject
)) {
5539 incrRefCount(storekey
);
5541 /* Note: we add 1 because the DB is dirty anyway since even if the
5542 * SORT result is empty a new key is set and maybe the old content
5544 server
.dirty
+= 1+outputlen
;
5545 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",outputlen
));
5549 decrRefCount(sortval
);
5550 listRelease(operations
);
5551 for (j
= 0; j
< vectorlen
; j
++) {
5552 if (sortby
&& alpha
&& vector
[j
].u
.cmpobj
)
5553 decrRefCount(vector
[j
].u
.cmpobj
);
5558 /* Convert an amount of bytes into a human readable string in the form
5559 * of 100B, 2G, 100M, 4K, and so forth. */
5560 static void bytesToHuman(char *s
, unsigned long long n
) {
5565 sprintf(s
,"%lluB",n
);
5567 } else if (n
< (1024*1024)) {
5568 d
= (double)n
/(1024);
5569 sprintf(s
,"%.2fK",d
);
5570 } else if (n
< (1024LL*1024*1024)) {
5571 d
= (double)n
/(1024*1024);
5572 sprintf(s
,"%.2fM",d
);
5573 } else if (n
< (1024LL*1024*1024*1024)) {
5574 d
= (double)n
/(1024LL*1024*1024);
5575 sprintf(s
,"%.2fM",d
);
5579 /* Create the string returned by the INFO command. This is decoupled
5580 * by the INFO command itself as we need to report the same information
5581 * on memory corruption problems. */
5582 static sds
genRedisInfoString(void) {
5584 time_t uptime
= time(NULL
)-server
.stat_starttime
;
5588 bytesToHuman(hmem
,server
.usedmemory
);
5589 info
= sdscatprintf(sdsempty(),
5590 "redis_version:%s\r\n"
5592 "multiplexing_api:%s\r\n"
5593 "process_id:%ld\r\n"
5594 "uptime_in_seconds:%ld\r\n"
5595 "uptime_in_days:%ld\r\n"
5596 "connected_clients:%d\r\n"
5597 "connected_slaves:%d\r\n"
5598 "blocked_clients:%d\r\n"
5599 "used_memory:%zu\r\n"
5600 "used_memory_human:%s\r\n"
5601 "changes_since_last_save:%lld\r\n"
5602 "bgsave_in_progress:%d\r\n"
5603 "last_save_time:%ld\r\n"
5604 "bgrewriteaof_in_progress:%d\r\n"
5605 "total_connections_received:%lld\r\n"
5606 "total_commands_processed:%lld\r\n"
5610 (sizeof(long) == 8) ? "64" : "32",
5615 listLength(server
.clients
)-listLength(server
.slaves
),
5616 listLength(server
.slaves
),
5617 server
.blockedclients
,
5621 server
.bgsavechildpid
!= -1,
5623 server
.bgrewritechildpid
!= -1,
5624 server
.stat_numconnections
,
5625 server
.stat_numcommands
,
5626 server
.vm_enabled
!= 0,
5627 server
.masterhost
== NULL
? "master" : "slave"
5629 if (server
.masterhost
) {
5630 info
= sdscatprintf(info
,
5631 "master_host:%s\r\n"
5632 "master_port:%d\r\n"
5633 "master_link_status:%s\r\n"
5634 "master_last_io_seconds_ago:%d\r\n"
5637 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
5639 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1
5642 if (server
.vm_enabled
) {
5644 info
= sdscatprintf(info
,
5645 "vm_conf_max_memory:%llu\r\n"
5646 "vm_conf_page_size:%llu\r\n"
5647 "vm_conf_pages:%llu\r\n"
5648 "vm_stats_used_pages:%llu\r\n"
5649 "vm_stats_swapped_objects:%llu\r\n"
5650 "vm_stats_swappin_count:%llu\r\n"
5651 "vm_stats_swappout_count:%llu\r\n"
5652 "vm_stats_io_newjobs_len:%lu\r\n"
5653 "vm_stats_io_processing_len:%lu\r\n"
5654 "vm_stats_io_processed_len:%lu\r\n"
5655 "vm_stats_io_waiting_clients:%lu\r\n"
5656 "vm_stats_io_active_threads:%lu\r\n"
5657 ,(unsigned long long) server
.vm_max_memory
,
5658 (unsigned long long) server
.vm_page_size
,
5659 (unsigned long long) server
.vm_pages
,
5660 (unsigned long long) server
.vm_stats_used_pages
,
5661 (unsigned long long) server
.vm_stats_swapped_objects
,
5662 (unsigned long long) server
.vm_stats_swapins
,
5663 (unsigned long long) server
.vm_stats_swapouts
,
5664 (unsigned long) listLength(server
.io_newjobs
),
5665 (unsigned long) listLength(server
.io_processing
),
5666 (unsigned long) listLength(server
.io_processed
),
5667 (unsigned long) listLength(server
.io_clients
),
5668 (unsigned long) server
.io_active_threads
5672 for (j
= 0; j
< server
.dbnum
; j
++) {
5673 long long keys
, vkeys
;
5675 keys
= dictSize(server
.db
[j
].dict
);
5676 vkeys
= dictSize(server
.db
[j
].expires
);
5677 if (keys
|| vkeys
) {
5678 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
5685 static void infoCommand(redisClient
*c
) {
5686 sds info
= genRedisInfoString();
5687 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
5688 (unsigned long)sdslen(info
)));
5689 addReplySds(c
,info
);
5690 addReply(c
,shared
.crlf
);
5693 static void monitorCommand(redisClient
*c
) {
5694 /* ignore MONITOR if aleady slave or in monitor mode */
5695 if (c
->flags
& REDIS_SLAVE
) return;
5697 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
5699 listAddNodeTail(server
.monitors
,c
);
5700 addReply(c
,shared
.ok
);
5703 /* ================================= Expire ================================= */
5704 static int removeExpire(redisDb
*db
, robj
*key
) {
5705 if (dictDelete(db
->expires
,key
) == DICT_OK
) {
5712 static int setExpire(redisDb
*db
, robj
*key
, time_t when
) {
5713 if (dictAdd(db
->expires
,key
,(void*)when
) == DICT_ERR
) {
5721 /* Return the expire time of the specified key, or -1 if no expire
5722 * is associated with this key (i.e. the key is non volatile) */
5723 static time_t getExpire(redisDb
*db
, robj
*key
) {
5726 /* No expire? return ASAP */
5727 if (dictSize(db
->expires
) == 0 ||
5728 (de
= dictFind(db
->expires
,key
)) == NULL
) return -1;
5730 return (time_t) dictGetEntryVal(de
);
5733 static int expireIfNeeded(redisDb
*db
, robj
*key
) {
5737 /* No expire? return ASAP */
5738 if (dictSize(db
->expires
) == 0 ||
5739 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
5741 /* Lookup the expire */
5742 when
= (time_t) dictGetEntryVal(de
);
5743 if (time(NULL
) <= when
) return 0;
5745 /* Delete the key */
5746 dictDelete(db
->expires
,key
);
5747 return dictDelete(db
->dict
,key
) == DICT_OK
;
5750 static int deleteIfVolatile(redisDb
*db
, robj
*key
) {
5753 /* No expire? return ASAP */
5754 if (dictSize(db
->expires
) == 0 ||
5755 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
5757 /* Delete the key */
5759 dictDelete(db
->expires
,key
);
5760 return dictDelete(db
->dict
,key
) == DICT_OK
;
5763 static void expireGenericCommand(redisClient
*c
, robj
*key
, time_t seconds
) {
5766 de
= dictFind(c
->db
->dict
,key
);
5768 addReply(c
,shared
.czero
);
5772 if (deleteKey(c
->db
,key
)) server
.dirty
++;
5773 addReply(c
, shared
.cone
);
5776 time_t when
= time(NULL
)+seconds
;
5777 if (setExpire(c
->db
,key
,when
)) {
5778 addReply(c
,shared
.cone
);
5781 addReply(c
,shared
.czero
);
5787 static void expireCommand(redisClient
*c
) {
5788 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10));
5791 static void expireatCommand(redisClient
*c
) {
5792 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10)-time(NULL
));
5795 static void ttlCommand(redisClient
*c
) {
5799 expire
= getExpire(c
->db
,c
->argv
[1]);
5801 ttl
= (int) (expire
-time(NULL
));
5802 if (ttl
< 0) ttl
= -1;
5804 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",ttl
));
5807 /* ================================ MULTI/EXEC ============================== */
5809 /* Client state initialization for MULTI/EXEC */
5810 static void initClientMultiState(redisClient
*c
) {
5811 c
->mstate
.commands
= NULL
;
5812 c
->mstate
.count
= 0;
5815 /* Release all the resources associated with MULTI/EXEC state */
5816 static void freeClientMultiState(redisClient
*c
) {
5819 for (j
= 0; j
< c
->mstate
.count
; j
++) {
5821 multiCmd
*mc
= c
->mstate
.commands
+j
;
5823 for (i
= 0; i
< mc
->argc
; i
++)
5824 decrRefCount(mc
->argv
[i
]);
5827 zfree(c
->mstate
.commands
);
5830 /* Add a new command into the MULTI commands queue */
5831 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
) {
5835 c
->mstate
.commands
= zrealloc(c
->mstate
.commands
,
5836 sizeof(multiCmd
)*(c
->mstate
.count
+1));
5837 mc
= c
->mstate
.commands
+c
->mstate
.count
;
5840 mc
->argv
= zmalloc(sizeof(robj
*)*c
->argc
);
5841 memcpy(mc
->argv
,c
->argv
,sizeof(robj
*)*c
->argc
);
5842 for (j
= 0; j
< c
->argc
; j
++)
5843 incrRefCount(mc
->argv
[j
]);
5847 static void multiCommand(redisClient
*c
) {
5848 c
->flags
|= REDIS_MULTI
;
5849 addReply(c
,shared
.ok
);
5852 static void execCommand(redisClient
*c
) {
5857 if (!(c
->flags
& REDIS_MULTI
)) {
5858 addReplySds(c
,sdsnew("-ERR EXEC without MULTI\r\n"));
5862 orig_argv
= c
->argv
;
5863 orig_argc
= c
->argc
;
5864 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->mstate
.count
));
5865 for (j
= 0; j
< c
->mstate
.count
; j
++) {
5866 c
->argc
= c
->mstate
.commands
[j
].argc
;
5867 c
->argv
= c
->mstate
.commands
[j
].argv
;
5868 call(c
,c
->mstate
.commands
[j
].cmd
);
5870 c
->argv
= orig_argv
;
5871 c
->argc
= orig_argc
;
5872 freeClientMultiState(c
);
5873 initClientMultiState(c
);
5874 c
->flags
&= (~REDIS_MULTI
);
5877 /* =========================== Blocking Operations ========================= */
5879 /* Currently Redis blocking operations support is limited to list POP ops,
5880 * so the current implementation is not fully generic, but it is also not
5881 * completely specific so it will not require a rewrite to support new
5882 * kind of blocking operations in the future.
5884 * Still it's important to note that list blocking operations can be already
5885 * used as a notification mechanism in order to implement other blocking
5886 * operations at application level, so there must be a very strong evidence
5887 * of usefulness and generality before new blocking operations are implemented.
5889 * This is how the current blocking POP works, we use BLPOP as example:
5890 * - If the user calls BLPOP and the key exists and contains a non empty list
5891 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
5892 * if there is not to block.
5893 * - If instead BLPOP is called and the key does not exists or the list is
5894 * empty we need to block. In order to do so we remove the notification for
5895 * new data to read in the client socket (so that we'll not serve new
5896 * requests if the blocking request is not served). Also we put the client
5897 * in a dictionary (db->blockingkeys) mapping keys to a list of clients
5898 * blocking for this keys.
5899 * - If a PUSH operation against a key with blocked clients waiting is
5900 * performed, we serve the first in the list: basically instead to push
5901 * the new element inside the list we return it to the (first / oldest)
5902 * blocking client, unblock the client, and remove it form the list.
5904 * The above comment and the source code should be enough in order to understand
5905 * the implementation and modify / fix it later.
5908 /* Set a client in blocking mode for the specified key, with the specified
5910 static void blockForKeys(redisClient
*c
, robj
**keys
, int numkeys
, time_t timeout
) {
5915 c
->blockingkeys
= zmalloc(sizeof(robj
*)*numkeys
);
5916 c
->blockingkeysnum
= numkeys
;
5917 c
->blockingto
= timeout
;
5918 for (j
= 0; j
< numkeys
; j
++) {
5919 /* Add the key in the client structure, to map clients -> keys */
5920 c
->blockingkeys
[j
] = keys
[j
];
5921 incrRefCount(keys
[j
]);
5923 /* And in the other "side", to map keys -> clients */
5924 de
= dictFind(c
->db
->blockingkeys
,keys
[j
]);
5928 /* For every key we take a list of clients blocked for it */
5930 retval
= dictAdd(c
->db
->blockingkeys
,keys
[j
],l
);
5931 incrRefCount(keys
[j
]);
5932 assert(retval
== DICT_OK
);
5934 l
= dictGetEntryVal(de
);
5936 listAddNodeTail(l
,c
);
5938 /* Mark the client as a blocked client */
5939 c
->flags
|= REDIS_BLOCKED
;
5940 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
5941 server
.blockedclients
++;
5944 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
5945 static void unblockClient(redisClient
*c
) {
5950 assert(c
->blockingkeys
!= NULL
);
5951 /* The client may wait for multiple keys, so unblock it for every key. */
5952 for (j
= 0; j
< c
->blockingkeysnum
; j
++) {
5953 /* Remove this client from the list of clients waiting for this key. */
5954 de
= dictFind(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
5956 l
= dictGetEntryVal(de
);
5957 listDelNode(l
,listSearchKey(l
,c
));
5958 /* If the list is empty we need to remove it to avoid wasting memory */
5959 if (listLength(l
) == 0)
5960 dictDelete(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
5961 decrRefCount(c
->blockingkeys
[j
]);
5963 /* Cleanup the client structure */
5964 zfree(c
->blockingkeys
);
5965 c
->blockingkeys
= NULL
;
5966 c
->flags
&= (~REDIS_BLOCKED
);
5967 server
.blockedclients
--;
5968 /* Ok now we are ready to get read events from socket, note that we
5969 * can't trap errors here as it's possible that unblockClients() is
5970 * called from freeClient() itself, and the only thing we can do
5971 * if we failed to register the READABLE event is to kill the client.
5972 * Still the following function should never fail in the real world as
5973 * we are sure the file descriptor is sane, and we exit on out of mem. */
5974 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
, readQueryFromClient
, c
);
5975 /* As a final step we want to process data if there is some command waiting
5976 * in the input buffer. Note that this is safe even if unblockClient()
5977 * gets called from freeClient() because freeClient() will be smart
5978 * enough to call this function *after* c->querybuf was set to NULL. */
5979 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0) processInputBuffer(c
);
5982 /* This should be called from any function PUSHing into lists.
5983 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
5984 * 'ele' is the element pushed.
5986 * If the function returns 0 there was no client waiting for a list push
5989 * If the function returns 1 there was a client waiting for a list push
5990 * against this key, the element was passed to this client thus it's not
5991 * needed to actually add it to the list and the caller should return asap. */
5992 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
) {
5993 struct dictEntry
*de
;
5994 redisClient
*receiver
;
5998 de
= dictFind(c
->db
->blockingkeys
,key
);
5999 if (de
== NULL
) return 0;
6000 l
= dictGetEntryVal(de
);
6003 receiver
= ln
->value
;
6005 addReplySds(receiver
,sdsnew("*2\r\n"));
6006 addReplyBulkLen(receiver
,key
);
6007 addReply(receiver
,key
);
6008 addReply(receiver
,shared
.crlf
);
6009 addReplyBulkLen(receiver
,ele
);
6010 addReply(receiver
,ele
);
6011 addReply(receiver
,shared
.crlf
);
6012 unblockClient(receiver
);
6016 /* Blocking RPOP/LPOP */
6017 static void blockingPopGenericCommand(redisClient
*c
, int where
) {
6022 for (j
= 1; j
< c
->argc
-1; j
++) {
6023 o
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
6025 if (o
->type
!= REDIS_LIST
) {
6026 addReply(c
,shared
.wrongtypeerr
);
6029 list
*list
= o
->ptr
;
6030 if (listLength(list
) != 0) {
6031 /* If the list contains elements fall back to the usual
6032 * non-blocking POP operation */
6033 robj
*argv
[2], **orig_argv
;
6036 /* We need to alter the command arguments before to call
6037 * popGenericCommand() as the command takes a single key. */
6038 orig_argv
= c
->argv
;
6039 orig_argc
= c
->argc
;
6040 argv
[1] = c
->argv
[j
];
6044 /* Also the return value is different, we need to output
6045 * the multi bulk reply header and the key name. The
6046 * "real" command will add the last element (the value)
6047 * for us. If this souds like an hack to you it's just
6048 * because it is... */
6049 addReplySds(c
,sdsnew("*2\r\n"));
6050 addReplyBulkLen(c
,argv
[1]);
6051 addReply(c
,argv
[1]);
6052 addReply(c
,shared
.crlf
);
6053 popGenericCommand(c
,where
);
6055 /* Fix the client structure with the original stuff */
6056 c
->argv
= orig_argv
;
6057 c
->argc
= orig_argc
;
6063 /* If the list is empty or the key does not exists we must block */
6064 timeout
= strtol(c
->argv
[c
->argc
-1]->ptr
,NULL
,10);
6065 if (timeout
> 0) timeout
+= time(NULL
);
6066 blockForKeys(c
,c
->argv
+1,c
->argc
-2,timeout
);
6069 static void blpopCommand(redisClient
*c
) {
6070 blockingPopGenericCommand(c
,REDIS_HEAD
);
6073 static void brpopCommand(redisClient
*c
) {
6074 blockingPopGenericCommand(c
,REDIS_TAIL
);
6077 /* =============================== Replication ============================= */
6079 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6080 ssize_t nwritten
, ret
= size
;
6081 time_t start
= time(NULL
);
6085 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
6086 nwritten
= write(fd
,ptr
,size
);
6087 if (nwritten
== -1) return -1;
6091 if ((time(NULL
)-start
) > timeout
) {
6099 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6100 ssize_t nread
, totread
= 0;
6101 time_t start
= time(NULL
);
6105 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
6106 nread
= read(fd
,ptr
,size
);
6107 if (nread
== -1) return -1;
6112 if ((time(NULL
)-start
) > timeout
) {
6120 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6127 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
6130 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
6141 static void syncCommand(redisClient
*c
) {
6142 /* ignore SYNC if aleady slave or in monitor mode */
6143 if (c
->flags
& REDIS_SLAVE
) return;
6145 /* SYNC can't be issued when the server has pending data to send to
6146 * the client about already issued commands. We need a fresh reply
6147 * buffer registering the differences between the BGSAVE and the current
6148 * dataset, so that we can copy to other slaves if needed. */
6149 if (listLength(c
->reply
) != 0) {
6150 addReplySds(c
,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
6154 redisLog(REDIS_NOTICE
,"Slave ask for synchronization");
6155 /* Here we need to check if there is a background saving operation
6156 * in progress, or if it is required to start one */
6157 if (server
.bgsavechildpid
!= -1) {
6158 /* Ok a background save is in progress. Let's check if it is a good
6159 * one for replication, i.e. if there is another slave that is
6160 * registering differences since the server forked to save */
6165 listRewind(server
.slaves
,&li
);
6166 while((ln
= listNext(&li
))) {
6168 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) break;
6171 /* Perfect, the server is already registering differences for
6172 * another slave. Set the right state, and copy the buffer. */
6173 listRelease(c
->reply
);
6174 c
->reply
= listDup(slave
->reply
);
6175 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6176 redisLog(REDIS_NOTICE
,"Waiting for end of BGSAVE for SYNC");
6178 /* No way, we need to wait for the next BGSAVE in order to
6179 * register differences */
6180 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
6181 redisLog(REDIS_NOTICE
,"Waiting for next BGSAVE for SYNC");
6184 /* Ok we don't have a BGSAVE in progress, let's start one */
6185 redisLog(REDIS_NOTICE
,"Starting BGSAVE for SYNC");
6186 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
6187 redisLog(REDIS_NOTICE
,"Replication failed, can't BGSAVE");
6188 addReplySds(c
,sdsnew("-ERR Unalbe to perform background save\r\n"));
6191 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6194 c
->flags
|= REDIS_SLAVE
;
6196 listAddNodeTail(server
.slaves
,c
);
6200 static void sendBulkToSlave(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
6201 redisClient
*slave
= privdata
;
6203 REDIS_NOTUSED(mask
);
6204 char buf
[REDIS_IOBUF_LEN
];
6205 ssize_t nwritten
, buflen
;
6207 if (slave
->repldboff
== 0) {
6208 /* Write the bulk write count before to transfer the DB. In theory here
6209 * we don't know how much room there is in the output buffer of the
6210 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
6211 * operations) will never be smaller than the few bytes we need. */
6214 bulkcount
= sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
6216 if (write(fd
,bulkcount
,sdslen(bulkcount
)) != (signed)sdslen(bulkcount
))
6224 lseek(slave
->repldbfd
,slave
->repldboff
,SEEK_SET
);
6225 buflen
= read(slave
->repldbfd
,buf
,REDIS_IOBUF_LEN
);
6227 redisLog(REDIS_WARNING
,"Read error sending DB to slave: %s",
6228 (buflen
== 0) ? "premature EOF" : strerror(errno
));
6232 if ((nwritten
= write(fd
,buf
,buflen
)) == -1) {
6233 redisLog(REDIS_VERBOSE
,"Write error sending DB to slave: %s",
6238 slave
->repldboff
+= nwritten
;
6239 if (slave
->repldboff
== slave
->repldbsize
) {
6240 close(slave
->repldbfd
);
6241 slave
->repldbfd
= -1;
6242 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
6243 slave
->replstate
= REDIS_REPL_ONLINE
;
6244 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
,
6245 sendReplyToClient
, slave
) == AE_ERR
) {
6249 addReplySds(slave
,sdsempty());
6250 redisLog(REDIS_NOTICE
,"Synchronization with slave succeeded");
6254 /* This function is called at the end of every backgrond saving.
6255 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
6256 * otherwise REDIS_ERR is passed to the function.
6258 * The goal of this function is to handle slaves waiting for a successful
6259 * background saving in order to perform non-blocking synchronization. */
6260 static void updateSlavesWaitingBgsave(int bgsaveerr
) {
6262 int startbgsave
= 0;
6265 listRewind(server
.slaves
,&li
);
6266 while((ln
= listNext(&li
))) {
6267 redisClient
*slave
= ln
->value
;
6269 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) {
6271 slave
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6272 } else if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) {
6273 struct redis_stat buf
;
6275 if (bgsaveerr
!= REDIS_OK
) {
6277 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE child returned an error");
6280 if ((slave
->repldbfd
= open(server
.dbfilename
,O_RDONLY
)) == -1 ||
6281 redis_fstat(slave
->repldbfd
,&buf
) == -1) {
6283 redisLog(REDIS_WARNING
,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno
));
6286 slave
->repldboff
= 0;
6287 slave
->repldbsize
= buf
.st_size
;
6288 slave
->replstate
= REDIS_REPL_SEND_BULK
;
6289 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
6290 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
, sendBulkToSlave
, slave
) == AE_ERR
) {
6297 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
6300 listRewind(server
.slaves
,&li
);
6301 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE failed");
6302 while((ln
= listNext(&li
))) {
6303 redisClient
*slave
= ln
->value
;
6305 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
)
6312 static int syncWithMaster(void) {
6313 char buf
[1024], tmpfile
[256], authcmd
[1024];
6315 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
6319 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
6324 /* AUTH with the master if required. */
6325 if(server
.masterauth
) {
6326 snprintf(authcmd
, 1024, "AUTH %s\r\n", server
.masterauth
);
6327 if (syncWrite(fd
, authcmd
, strlen(server
.masterauth
)+7, 5) == -1) {
6329 redisLog(REDIS_WARNING
,"Unable to AUTH to MASTER: %s",
6333 /* Read the AUTH result. */
6334 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
6336 redisLog(REDIS_WARNING
,"I/O error reading auth result from MASTER: %s",
6340 if (buf
[0] != '+') {
6342 redisLog(REDIS_WARNING
,"Cannot AUTH to MASTER, is the masterauth password correct?");
6347 /* Issue the SYNC command */
6348 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
6350 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
6354 /* Read the bulk write count */
6355 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
6357 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
6361 if (buf
[0] != '$') {
6363 redisLog(REDIS_WARNING
,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
6366 dumpsize
= atoi(buf
+1);
6367 redisLog(REDIS_NOTICE
,"Receiving %d bytes data dump from MASTER",dumpsize
);
6368 /* Read the bulk write data on a temp file */
6369 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
6370 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
,0644);
6373 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
6377 int nread
, nwritten
;
6379 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
6381 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
6387 nwritten
= write(dfd
,buf
,nread
);
6388 if (nwritten
== -1) {
6389 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
6397 if (rename(tmpfile
,server
.dbfilename
) == -1) {
6398 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
6404 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
6405 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
6409 server
.master
= createClient(fd
);
6410 server
.master
->flags
|= REDIS_MASTER
;
6411 server
.master
->authenticated
= 1;
6412 server
.replstate
= REDIS_REPL_CONNECTED
;
6416 static void slaveofCommand(redisClient
*c
) {
6417 if (!strcasecmp(c
->argv
[1]->ptr
,"no") &&
6418 !strcasecmp(c
->argv
[2]->ptr
,"one")) {
6419 if (server
.masterhost
) {
6420 sdsfree(server
.masterhost
);
6421 server
.masterhost
= NULL
;
6422 if (server
.master
) freeClient(server
.master
);
6423 server
.replstate
= REDIS_REPL_NONE
;
6424 redisLog(REDIS_NOTICE
,"MASTER MODE enabled (user request)");
6427 sdsfree(server
.masterhost
);
6428 server
.masterhost
= sdsdup(c
->argv
[1]->ptr
);
6429 server
.masterport
= atoi(c
->argv
[2]->ptr
);
6430 if (server
.master
) freeClient(server
.master
);
6431 server
.replstate
= REDIS_REPL_CONNECT
;
6432 redisLog(REDIS_NOTICE
,"SLAVE OF %s:%d enabled (user request)",
6433 server
.masterhost
, server
.masterport
);
6435 addReply(c
,shared
.ok
);
6438 /* ============================ Maxmemory directive ======================== */
6440 /* Try to free one object form the pre-allocated objects free list.
6441 * This is useful under low mem conditions as by default we take 1 million
6442 * free objects allocated. On success REDIS_OK is returned, otherwise
6444 static int tryFreeOneObjectFromFreelist(void) {
6447 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
6448 if (listLength(server
.objfreelist
)) {
6449 listNode
*head
= listFirst(server
.objfreelist
);
6450 o
= listNodeValue(head
);
6451 listDelNode(server
.objfreelist
,head
);
6452 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
6456 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
6461 /* This function gets called when 'maxmemory' is set on the config file to limit
6462 * the max memory used by the server, and we are out of memory.
6463 * This function will try to, in order:
6465 * - Free objects from the free list
6466 * - Try to remove keys with an EXPIRE set
6468 * It is not possible to free enough memory to reach used-memory < maxmemory
6469 * the server will start refusing commands that will enlarge even more the
6472 static void freeMemoryIfNeeded(void) {
6473 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
6474 int j
, k
, freed
= 0;
6476 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
6477 for (j
= 0; j
< server
.dbnum
; j
++) {
6479 robj
*minkey
= NULL
;
6480 struct dictEntry
*de
;
6482 if (dictSize(server
.db
[j
].expires
)) {
6484 /* From a sample of three keys drop the one nearest to
6485 * the natural expire */
6486 for (k
= 0; k
< 3; k
++) {
6489 de
= dictGetRandomKey(server
.db
[j
].expires
);
6490 t
= (time_t) dictGetEntryVal(de
);
6491 if (minttl
== -1 || t
< minttl
) {
6492 minkey
= dictGetEntryKey(de
);
6496 deleteKey(server
.db
+j
,minkey
);
6499 if (!freed
) return; /* nothing to free... */
6503 /* ============================== Append Only file ========================== */
6505 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
6506 sds buf
= sdsempty();
6512 /* The DB this command was targetting is not the same as the last command
6513 * we appendend. To issue a SELECT command is needed. */
6514 if (dictid
!= server
.appendseldb
) {
6517 snprintf(seldb
,sizeof(seldb
),"%d",dictid
);
6518 buf
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
6519 (unsigned long)strlen(seldb
),seldb
);
6520 server
.appendseldb
= dictid
;
6523 /* "Fix" the argv vector if the command is EXPIRE. We want to translate
6524 * EXPIREs into EXPIREATs calls */
6525 if (cmd
->proc
== expireCommand
) {
6528 tmpargv
[0] = createStringObject("EXPIREAT",8);
6529 tmpargv
[1] = argv
[1];
6530 incrRefCount(argv
[1]);
6531 when
= time(NULL
)+strtol(argv
[2]->ptr
,NULL
,10);
6532 tmpargv
[2] = createObject(REDIS_STRING
,
6533 sdscatprintf(sdsempty(),"%ld",when
));
6537 /* Append the actual command */
6538 buf
= sdscatprintf(buf
,"*%d\r\n",argc
);
6539 for (j
= 0; j
< argc
; j
++) {
6542 o
= getDecodedObject(o
);
6543 buf
= sdscatprintf(buf
,"$%lu\r\n",(unsigned long)sdslen(o
->ptr
));
6544 buf
= sdscatlen(buf
,o
->ptr
,sdslen(o
->ptr
));
6545 buf
= sdscatlen(buf
,"\r\n",2);
6549 /* Free the objects from the modified argv for EXPIREAT */
6550 if (cmd
->proc
== expireCommand
) {
6551 for (j
= 0; j
< 3; j
++)
6552 decrRefCount(argv
[j
]);
6555 /* We want to perform a single write. This should be guaranteed atomic
6556 * at least if the filesystem we are writing is a real physical one.
6557 * While this will save us against the server being killed I don't think
6558 * there is much to do about the whole server stopping for power problems
6560 nwritten
= write(server
.appendfd
,buf
,sdslen(buf
));
6561 if (nwritten
!= (signed)sdslen(buf
)) {
6562 /* Ooops, we are in troubles. The best thing to do for now is
6563 * to simply exit instead to give the illusion that everything is
6564 * working as expected. */
6565 if (nwritten
== -1) {
6566 redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
));
6568 redisLog(REDIS_WARNING
,"Exiting on short write while writing to the append-only file: %s",strerror(errno
));
6572 /* If a background append only file rewriting is in progress we want to
6573 * accumulate the differences between the child DB and the current one
6574 * in a buffer, so that when the child process will do its work we
6575 * can append the differences to the new append only file. */
6576 if (server
.bgrewritechildpid
!= -1)
6577 server
.bgrewritebuf
= sdscatlen(server
.bgrewritebuf
,buf
,sdslen(buf
));
6581 if (server
.appendfsync
== APPENDFSYNC_ALWAYS
||
6582 (server
.appendfsync
== APPENDFSYNC_EVERYSEC
&&
6583 now
-server
.lastfsync
> 1))
6585 fsync(server
.appendfd
); /* Let's try to get this data on the disk */
6586 server
.lastfsync
= now
;
6590 /* In Redis commands are always executed in the context of a client, so in
6591 * order to load the append only file we need to create a fake client. */
6592 static struct redisClient
*createFakeClient(void) {
6593 struct redisClient
*c
= zmalloc(sizeof(*c
));
6597 c
->querybuf
= sdsempty();
6601 /* We set the fake client as a slave waiting for the synchronization
6602 * so that Redis will not try to send replies to this client. */
6603 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
6604 c
->reply
= listCreate();
6605 listSetFreeMethod(c
->reply
,decrRefCount
);
6606 listSetDupMethod(c
->reply
,dupClientReplyValue
);
6610 static void freeFakeClient(struct redisClient
*c
) {
6611 sdsfree(c
->querybuf
);
6612 listRelease(c
->reply
);
6616 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
6617 * error (the append only file is zero-length) REDIS_ERR is returned. On
6618 * fatal error an error message is logged and the program exists. */
6619 int loadAppendOnlyFile(char *filename
) {
6620 struct redisClient
*fakeClient
;
6621 FILE *fp
= fopen(filename
,"r");
6622 struct redis_stat sb
;
6623 unsigned long long loadedkeys
= 0;
6625 if (redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0)
6629 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
6633 fakeClient
= createFakeClient();
6640 struct redisCommand
*cmd
;
6642 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
6648 if (buf
[0] != '*') goto fmterr
;
6650 argv
= zmalloc(sizeof(robj
*)*argc
);
6651 for (j
= 0; j
< argc
; j
++) {
6652 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
6653 if (buf
[0] != '$') goto fmterr
;
6654 len
= strtol(buf
+1,NULL
,10);
6655 argsds
= sdsnewlen(NULL
,len
);
6656 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
6657 argv
[j
] = createObject(REDIS_STRING
,argsds
);
6658 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
6661 /* Command lookup */
6662 cmd
= lookupCommand(argv
[0]->ptr
);
6664 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
6667 /* Try object sharing and encoding */
6668 if (server
.shareobjects
) {
6670 for(j
= 1; j
< argc
; j
++)
6671 argv
[j
] = tryObjectSharing(argv
[j
]);
6673 if (cmd
->flags
& REDIS_CMD_BULK
)
6674 tryObjectEncoding(argv
[argc
-1]);
6675 /* Run the command in the context of a fake client */
6676 fakeClient
->argc
= argc
;
6677 fakeClient
->argv
= argv
;
6678 cmd
->proc(fakeClient
);
6679 /* Discard the reply objects list from the fake client */
6680 while(listLength(fakeClient
->reply
))
6681 listDelNode(fakeClient
->reply
,listFirst(fakeClient
->reply
));
6682 /* Clean up, ready for the next command */
6683 for (j
= 0; j
< argc
; j
++) decrRefCount(argv
[j
]);
6685 /* Handle swapping while loading big datasets when VM is on */
6687 if (server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
6688 while (zmalloc_used_memory() > server
.vm_max_memory
) {
6689 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
6694 freeFakeClient(fakeClient
);
6699 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
6701 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
6705 redisLog(REDIS_WARNING
,"Bad file format reading the append only file");
6709 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
6710 static int fwriteBulk(FILE *fp
, robj
*obj
) {
6714 /* Avoid the incr/decr ref count business if possible to help
6715 * copy-on-write (we are often in a child process when this function
6717 * Also makes sure that key objects don't get incrRefCount-ed when VM
6719 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
6720 obj
= getDecodedObject(obj
);
6723 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(long)sdslen(obj
->ptr
));
6724 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) goto err
;
6725 if (sdslen(obj
->ptr
) && fwrite(obj
->ptr
,sdslen(obj
->ptr
),1,fp
) == 0)
6727 if (fwrite("\r\n",2,1,fp
) == 0) goto err
;
6728 if (decrrc
) decrRefCount(obj
);
6731 if (decrrc
) decrRefCount(obj
);
6735 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
6736 static int fwriteBulkDouble(FILE *fp
, double d
) {
6737 char buf
[128], dbuf
[128];
6739 snprintf(dbuf
,sizeof(dbuf
),"%.17g\r\n",d
);
6740 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(dbuf
)-2);
6741 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
6742 if (fwrite(dbuf
,strlen(dbuf
),1,fp
) == 0) return 0;
6746 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
6747 static int fwriteBulkLong(FILE *fp
, long l
) {
6748 char buf
[128], lbuf
[128];
6750 snprintf(lbuf
,sizeof(lbuf
),"%ld\r\n",l
);
6751 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(lbuf
)-2);
6752 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
6753 if (fwrite(lbuf
,strlen(lbuf
),1,fp
) == 0) return 0;
6757 /* Write a sequence of commands able to fully rebuild the dataset into
6758 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
6759 static int rewriteAppendOnlyFile(char *filename
) {
6760 dictIterator
*di
= NULL
;
6765 time_t now
= time(NULL
);
6767 /* Note that we have to use a different temp name here compared to the
6768 * one used by rewriteAppendOnlyFileBackground() function. */
6769 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
6770 fp
= fopen(tmpfile
,"w");
6772 redisLog(REDIS_WARNING
, "Failed rewriting the append only file: %s", strerror(errno
));
6775 for (j
= 0; j
< server
.dbnum
; j
++) {
6776 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
6777 redisDb
*db
= server
.db
+j
;
6779 if (dictSize(d
) == 0) continue;
6780 di
= dictGetIterator(d
);
6786 /* SELECT the new DB */
6787 if (fwrite(selectcmd
,sizeof(selectcmd
)-1,1,fp
) == 0) goto werr
;
6788 if (fwriteBulkLong(fp
,j
) == 0) goto werr
;
6790 /* Iterate this DB writing every entry */
6791 while((de
= dictNext(di
)) != NULL
) {
6796 key
= dictGetEntryKey(de
);
6797 /* If the value for this key is swapped, load a preview in memory.
6798 * We use a "swapped" flag to remember if we need to free the
6799 * value object instead to just increment the ref count anyway
6800 * in order to avoid copy-on-write of pages if we are forked() */
6801 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
6802 key
->storage
== REDIS_VM_SWAPPING
) {
6803 o
= dictGetEntryVal(de
);
6806 o
= vmPreviewObject(key
);
6809 expiretime
= getExpire(db
,key
);
6811 /* Save the key and associated value */
6812 if (o
->type
== REDIS_STRING
) {
6813 /* Emit a SET command */
6814 char cmd
[]="*3\r\n$3\r\nSET\r\n";
6815 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6817 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6818 if (fwriteBulk(fp
,o
) == 0) goto werr
;
6819 } else if (o
->type
== REDIS_LIST
) {
6820 /* Emit the RPUSHes needed to rebuild the list */
6821 list
*list
= o
->ptr
;
6825 listRewind(list
,&li
);
6826 while((ln
= listNext(&li
))) {
6827 char cmd
[]="*3\r\n$5\r\nRPUSH\r\n";
6828 robj
*eleobj
= listNodeValue(ln
);
6830 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6831 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6832 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6834 } else if (o
->type
== REDIS_SET
) {
6835 /* Emit the SADDs needed to rebuild the set */
6837 dictIterator
*di
= dictGetIterator(set
);
6840 while((de
= dictNext(di
)) != NULL
) {
6841 char cmd
[]="*3\r\n$4\r\nSADD\r\n";
6842 robj
*eleobj
= dictGetEntryKey(de
);
6844 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6845 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6846 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6848 dictReleaseIterator(di
);
6849 } else if (o
->type
== REDIS_ZSET
) {
6850 /* Emit the ZADDs needed to rebuild the sorted set */
6852 dictIterator
*di
= dictGetIterator(zs
->dict
);
6855 while((de
= dictNext(di
)) != NULL
) {
6856 char cmd
[]="*4\r\n$4\r\nZADD\r\n";
6857 robj
*eleobj
= dictGetEntryKey(de
);
6858 double *score
= dictGetEntryVal(de
);
6860 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6861 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6862 if (fwriteBulkDouble(fp
,*score
) == 0) goto werr
;
6863 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6865 dictReleaseIterator(di
);
6867 redisAssert(0 != 0);
6869 /* Save the expire time */
6870 if (expiretime
!= -1) {
6871 char cmd
[]="*3\r\n$8\r\nEXPIREAT\r\n";
6872 /* If this key is already expired skip it */
6873 if (expiretime
< now
) continue;
6874 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6875 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6876 if (fwriteBulkLong(fp
,expiretime
) == 0) goto werr
;
6878 if (swapped
) decrRefCount(o
);
6880 dictReleaseIterator(di
);
6883 /* Make sure data will not remain on the OS's output buffers */
6888 /* Use RENAME to make sure the DB file is changed atomically only
6889 * if the generate DB file is ok. */
6890 if (rename(tmpfile
,filename
) == -1) {
6891 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
6895 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
6901 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
6902 if (di
) dictReleaseIterator(di
);
6906 /* This is how rewriting of the append only file in background works:
6908 * 1) The user calls BGREWRITEAOF
6909 * 2) Redis calls this function, that forks():
6910 * 2a) the child rewrite the append only file in a temp file.
6911 * 2b) the parent accumulates differences in server.bgrewritebuf.
6912 * 3) When the child finished '2a' exists.
6913 * 4) The parent will trap the exit code, if it's OK, will append the
6914 * data accumulated into server.bgrewritebuf into the temp file, and
6915 * finally will rename(2) the temp file in the actual file name.
6916 * The the new file is reopened as the new append only file. Profit!
6918 static int rewriteAppendOnlyFileBackground(void) {
6921 if (server
.bgrewritechildpid
!= -1) return REDIS_ERR
;
6922 if (server
.vm_enabled
) waitZeroActiveThreads();
6923 if ((childpid
= fork()) == 0) {
6928 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
6929 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
6936 if (childpid
== -1) {
6937 redisLog(REDIS_WARNING
,
6938 "Can't rewrite append only file in background: fork: %s",
6942 redisLog(REDIS_NOTICE
,
6943 "Background append only file rewriting started by pid %d",childpid
);
6944 server
.bgrewritechildpid
= childpid
;
6945 /* We set appendseldb to -1 in order to force the next call to the
6946 * feedAppendOnlyFile() to issue a SELECT command, so the differences
6947 * accumulated by the parent into server.bgrewritebuf will start
6948 * with a SELECT statement and it will be safe to merge. */
6949 server
.appendseldb
= -1;
6952 return REDIS_OK
; /* unreached */
6955 static void bgrewriteaofCommand(redisClient
*c
) {
6956 if (server
.bgrewritechildpid
!= -1) {
6957 addReplySds(c
,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
6960 if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
6961 char *status
= "+Background append only file rewriting started\r\n";
6962 addReplySds(c
,sdsnew(status
));
6964 addReply(c
,shared
.err
);
6968 static void aofRemoveTempFile(pid_t childpid
) {
6971 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
6975 /* Virtual Memory is composed mainly of two subsystems:
6976 * - Blocking Virutal Memory
6977 * - Threaded Virtual Memory I/O
6978 * The two parts are not fully decoupled, but functions are split among two
6979 * different sections of the source code (delimited by comments) in order to
6980 * make more clear what functionality is about the blocking VM and what about
6981 * the threaded (not blocking) VM.
6985 * Redis VM is a blocking VM (one that blocks reading swapped values from
6986 * disk into memory when a value swapped out is needed in memory) that is made
6987 * unblocking by trying to examine the command argument vector in order to
6988 * load in background values that will likely be needed in order to exec
6989 * the command. The command is executed only once all the relevant keys
6990 * are loaded into memory.
6992 * This basically is almost as simple of a blocking VM, but almost as parallel
6993 * as a fully non-blocking VM.
6996 /* =================== Virtual Memory - Blocking Side ====================== */
6997 static void vmInit(void) {
7002 if (server
.vm_max_threads
!= 0)
7003 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
7005 server
.vm_fp
= fopen("/tmp/redisvm","w+b");
7006 if (server
.vm_fp
== NULL
) {
7007 redisLog(REDIS_WARNING
,"Impossible to open the swap file. Exiting.");
7010 server
.vm_fd
= fileno(server
.vm_fp
);
7011 server
.vm_next_page
= 0;
7012 server
.vm_near_pages
= 0;
7013 server
.vm_stats_used_pages
= 0;
7014 server
.vm_stats_swapped_objects
= 0;
7015 server
.vm_stats_swapouts
= 0;
7016 server
.vm_stats_swapins
= 0;
7017 totsize
= server
.vm_pages
*server
.vm_page_size
;
7018 redisLog(REDIS_NOTICE
,"Allocating %lld bytes of swap file",totsize
);
7019 if (ftruncate(server
.vm_fd
,totsize
) == -1) {
7020 redisLog(REDIS_WARNING
,"Can't ftruncate swap file: %s. Exiting.",
7024 redisLog(REDIS_NOTICE
,"Swap file allocated with success");
7026 server
.vm_bitmap
= zmalloc((server
.vm_pages
+7)/8);
7027 redisLog(REDIS_VERBOSE
,"Allocated %lld bytes page table for %lld pages",
7028 (long long) (server
.vm_pages
+7)/8, server
.vm_pages
);
7029 memset(server
.vm_bitmap
,0,(server
.vm_pages
+7)/8);
7030 /* Try to remove the swap file, so the OS will really delete it from the
7031 * file system when Redis exists. */
7032 unlink("/tmp/redisvm");
7034 /* Initialize threaded I/O (used by Virtual Memory) */
7035 server
.io_newjobs
= listCreate();
7036 server
.io_processing
= listCreate();
7037 server
.io_processed
= listCreate();
7038 server
.io_clients
= listCreate();
7039 pthread_mutex_init(&server
.io_mutex
,NULL
);
7040 pthread_mutex_init(&server
.obj_freelist_mutex
,NULL
);
7041 pthread_mutex_init(&server
.io_swapfile_mutex
,NULL
);
7042 server
.io_active_threads
= 0;
7043 if (pipe(pipefds
) == -1) {
7044 redisLog(REDIS_WARNING
,"Unable to intialized VM: pipe(2): %s. Exiting."
7048 server
.io_ready_pipe_read
= pipefds
[0];
7049 server
.io_ready_pipe_write
= pipefds
[1];
7050 redisAssert(anetNonBlock(NULL
,server
.io_ready_pipe_read
) != ANET_ERR
);
7051 /* LZF requires a lot of stack */
7052 pthread_attr_init(&server
.io_threads_attr
);
7053 pthread_attr_getstacksize(&server
.io_threads_attr
, &stacksize
);
7054 while (stacksize
< REDIS_THREAD_STACK_SIZE
) stacksize
*= 2;
7055 pthread_attr_setstacksize(&server
.io_threads_attr
, stacksize
);
7056 /* Listen for events in the threaded I/O pipe */
7057 if (aeCreateFileEvent(server
.el
, server
.io_ready_pipe_read
, AE_READABLE
,
7058 vmThreadedIOCompletedJob
, NULL
) == AE_ERR
)
7059 oom("creating file event");
7062 /* Mark the page as used */
7063 static void vmMarkPageUsed(off_t page
) {
7064 off_t byte
= page
/8;
7066 server
.vm_bitmap
[byte
] |= 1<<bit
;
7067 redisLog(REDIS_DEBUG
,"Mark used: %lld (byte:%lld bit:%d)\n",
7068 (long long)page
, (long long)byte
, bit
);
7071 /* Mark N contiguous pages as used, with 'page' being the first. */
7072 static void vmMarkPagesUsed(off_t page
, off_t count
) {
7075 for (j
= 0; j
< count
; j
++)
7076 vmMarkPageUsed(page
+j
);
7077 server
.vm_stats_used_pages
+= count
;
7080 /* Mark the page as free */
7081 static void vmMarkPageFree(off_t page
) {
7082 off_t byte
= page
/8;
7084 server
.vm_bitmap
[byte
] &= ~(1<<bit
);
7087 /* Mark N contiguous pages as free, with 'page' being the first. */
7088 static void vmMarkPagesFree(off_t page
, off_t count
) {
7091 for (j
= 0; j
< count
; j
++)
7092 vmMarkPageFree(page
+j
);
7093 server
.vm_stats_used_pages
-= count
;
7096 /* Test if the page is free */
7097 static int vmFreePage(off_t page
) {
7098 off_t byte
= page
/8;
7100 return (server
.vm_bitmap
[byte
] & (1<<bit
)) == 0;
7103 /* Find N contiguous free pages storing the first page of the cluster in *first.
7104 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
7105 * REDIS_ERR is returned.
7107 * This function uses a simple algorithm: we try to allocate
7108 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
7109 * again from the start of the swap file searching for free spaces.
7111 * If it looks pretty clear that there are no free pages near our offset
7112 * we try to find less populated places doing a forward jump of
7113 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
7114 * without hurry, and then we jump again and so forth...
7116 * This function can be improved using a free list to avoid to guess
7117 * too much, since we could collect data about freed pages.
7119 * note: I implemented this function just after watching an episode of
7120 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
7122 static int vmFindContiguousPages(off_t
*first
, off_t n
) {
7123 off_t base
, offset
= 0, since_jump
= 0, numfree
= 0;
7125 if (server
.vm_near_pages
== REDIS_VM_MAX_NEAR_PAGES
) {
7126 server
.vm_near_pages
= 0;
7127 server
.vm_next_page
= 0;
7129 server
.vm_near_pages
++; /* Yet another try for pages near to the old ones */
7130 base
= server
.vm_next_page
;
7132 while(offset
< server
.vm_pages
) {
7133 off_t
this = base
+offset
;
7135 redisLog(REDIS_DEBUG
, "THIS: %lld (%c)\n", (long long) this, vmFreePage(this) ? 'F' : 'X');
7136 /* If we overflow, restart from page zero */
7137 if (this >= server
.vm_pages
) {
7138 this -= server
.vm_pages
;
7140 /* Just overflowed, what we found on tail is no longer
7141 * interesting, as it's no longer contiguous. */
7145 if (vmFreePage(this)) {
7146 /* This is a free page */
7148 /* Already got N free pages? Return to the caller, with success */
7150 *first
= this-(n
-1);
7151 server
.vm_next_page
= this+1;
7155 /* The current one is not a free page */
7159 /* Fast-forward if the current page is not free and we already
7160 * searched enough near this place. */
7162 if (!numfree
&& since_jump
>= REDIS_VM_MAX_RANDOM_JUMP
/4) {
7163 offset
+= random() % REDIS_VM_MAX_RANDOM_JUMP
;
7165 /* Note that even if we rewind after the jump, we are don't need
7166 * to make sure numfree is set to zero as we only jump *if* it
7167 * is set to zero. */
7169 /* Otherwise just check the next page */
7176 /* Write the specified object at the specified page of the swap file */
7177 static int vmWriteObjectOnSwap(robj
*o
, off_t page
) {
7178 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
7179 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
7180 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
7181 redisLog(REDIS_WARNING
,
7182 "Critical VM problem in vmSwapObjectBlocking(): can't seek: %s",
7186 rdbSaveObject(server
.vm_fp
,o
);
7187 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
7191 /* Swap the 'val' object relative to 'key' into disk. Store all the information
7192 * needed to later retrieve the object into the key object.
7193 * If we can't find enough contiguous empty pages to swap the object on disk
7194 * REDIS_ERR is returned. */
7195 static int vmSwapObjectBlocking(robj
*key
, robj
*val
) {
7196 off_t pages
= rdbSavedObjectPages(val
,NULL
);
7199 assert(key
->storage
== REDIS_VM_MEMORY
);
7200 assert(key
->refcount
== 1);
7201 if (vmFindContiguousPages(&page
,pages
) == REDIS_ERR
) return REDIS_ERR
;
7202 if (vmWriteObjectOnSwap(val
,page
) == REDIS_ERR
) return REDIS_ERR
;
7203 key
->vm
.page
= page
;
7204 key
->vm
.usedpages
= pages
;
7205 key
->storage
= REDIS_VM_SWAPPED
;
7206 key
->vtype
= val
->type
;
7207 decrRefCount(val
); /* Deallocate the object from memory. */
7208 vmMarkPagesUsed(page
,pages
);
7209 redisLog(REDIS_DEBUG
,"VM: object %s swapped out at %lld (%lld pages)",
7210 (unsigned char*) key
->ptr
,
7211 (unsigned long long) page
, (unsigned long long) pages
);
7212 server
.vm_stats_swapped_objects
++;
7213 server
.vm_stats_swapouts
++;
7214 fflush(server
.vm_fp
);
7218 static robj
*vmReadObjectFromSwap(off_t page
, int type
) {
7221 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
7222 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
7223 redisLog(REDIS_WARNING
,
7224 "Unrecoverable VM problem in vmLoadObject(): can't seek: %s",
7228 o
= rdbLoadObject(type
,server
.vm_fp
);
7230 redisLog(REDIS_WARNING
, "Unrecoverable VM problem in vmLoadObject(): can't load object from swap file: %s", strerror(errno
));
7233 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
7237 /* Load the value object relative to the 'key' object from swap to memory.
7238 * The newly allocated object is returned.
7240 * If preview is true the unserialized object is returned to the caller but
7241 * no changes are made to the key object, nor the pages are marked as freed */
7242 static robj
*vmGenericLoadObject(robj
*key
, int preview
) {
7245 redisAssert(key
->storage
== REDIS_VM_SWAPPED
);
7246 val
= vmReadObjectFromSwap(key
->vm
.page
,key
->vtype
);
7248 key
->storage
= REDIS_VM_MEMORY
;
7249 key
->vm
.atime
= server
.unixtime
;
7250 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
7251 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk",
7252 (unsigned char*) key
->ptr
);
7253 server
.vm_stats_swapped_objects
--;
7255 redisLog(REDIS_DEBUG
, "VM: object %s previewed from disk",
7256 (unsigned char*) key
->ptr
);
7258 server
.vm_stats_swapins
++;
7262 /* Plain object loading, from swap to memory */
7263 static robj
*vmLoadObject(robj
*key
) {
7264 /* If we are loading the object in background, stop it, we
7265 * need to load this object synchronously ASAP. */
7266 if (key
->storage
== REDIS_VM_LOADING
)
7267 vmCancelThreadedIOJob(key
);
7268 return vmGenericLoadObject(key
,0);
7271 /* Just load the value on disk, without to modify the key.
7272 * This is useful when we want to perform some operation on the value
7273 * without to really bring it from swap to memory, like while saving the
7274 * dataset or rewriting the append only log. */
7275 static robj
*vmPreviewObject(robj
*key
) {
7276 return vmGenericLoadObject(key
,1);
7279 /* How a good candidate is this object for swapping?
7280 * The better candidate it is, the greater the returned value.
7282 * Currently we try to perform a fast estimation of the object size in
7283 * memory, and combine it with aging informations.
7285 * Basically swappability = idle-time * log(estimated size)
7287 * Bigger objects are preferred over smaller objects, but not
7288 * proportionally, this is why we use the logarithm. This algorithm is
7289 * just a first try and will probably be tuned later. */
7290 static double computeObjectSwappability(robj
*o
) {
7291 time_t age
= server
.unixtime
- o
->vm
.atime
;
7295 struct dictEntry
*de
;
7298 if (age
<= 0) return 0;
7301 if (o
->encoding
!= REDIS_ENCODING_RAW
) {
7304 asize
= sdslen(o
->ptr
)+sizeof(*o
)+sizeof(long)*2;
7309 listNode
*ln
= listFirst(l
);
7311 asize
= sizeof(list
);
7313 robj
*ele
= ln
->value
;
7316 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
7317 (sizeof(*o
)+sdslen(ele
->ptr
)) :
7319 asize
+= (sizeof(listNode
)+elesize
)*listLength(l
);
7324 z
= (o
->type
== REDIS_ZSET
);
7325 d
= z
? ((zset
*)o
->ptr
)->dict
: o
->ptr
;
7327 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
7328 if (z
) asize
+= sizeof(zset
)-sizeof(dict
);
7333 de
= dictGetRandomKey(d
);
7334 ele
= dictGetEntryKey(de
);
7335 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
7336 (sizeof(*o
)+sdslen(ele
->ptr
)) :
7338 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
7339 if (z
) asize
+= sizeof(zskiplistNode
)*dictSize(d
);
7343 return (double)asize
*log(1+asize
);
7346 /* Try to swap an object that's a good candidate for swapping.
7347 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
7348 * to swap any object at all.
7350 * If 'usethreaded' is true, Redis will try to swap the object in background
7351 * using I/O threads. */
7352 static int vmSwapOneObject(int usethreads
) {
7354 struct dictEntry
*best
= NULL
;
7355 double best_swappability
= 0;
7356 redisDb
*best_db
= NULL
;
7359 for (j
= 0; j
< server
.dbnum
; j
++) {
7360 redisDb
*db
= server
.db
+j
;
7361 int maxtries
= 1000;
7363 if (dictSize(db
->dict
) == 0) continue;
7364 for (i
= 0; i
< 5; i
++) {
7366 double swappability
;
7368 if (maxtries
) maxtries
--;
7369 de
= dictGetRandomKey(db
->dict
);
7370 key
= dictGetEntryKey(de
);
7371 val
= dictGetEntryVal(de
);
7372 /* Only swap objects that are currently in memory.
7374 * Also don't swap shared objects if threaded VM is on, as we
7375 * try to ensure that the main thread does not touch the
7376 * object while the I/O thread is using it, but we can't
7377 * control other keys without adding additional mutex. */
7378 if (key
->storage
!= REDIS_VM_MEMORY
||
7379 (server
.vm_max_threads
!= 0 && val
->refcount
!= 1)) {
7380 if (maxtries
) i
--; /* don't count this try */
7383 swappability
= computeObjectSwappability(val
);
7384 if (!best
|| swappability
> best_swappability
) {
7386 best_swappability
= swappability
;
7392 redisLog(REDIS_DEBUG
,"No swappable key found!");
7395 key
= dictGetEntryKey(best
);
7396 val
= dictGetEntryVal(best
);
7398 redisLog(REDIS_DEBUG
,"Key with best swappability: %s, %f",
7399 key
->ptr
, best_swappability
);
7401 /* Unshare the key if needed */
7402 if (key
->refcount
> 1) {
7403 robj
*newkey
= dupStringObject(key
);
7405 key
= dictGetEntryKey(best
) = newkey
;
7409 vmSwapObjectThreaded(key
,val
,best_db
);
7412 if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
7413 dictGetEntryVal(best
) = NULL
;
7421 static int vmSwapOneObjectBlocking() {
7422 return vmSwapOneObject(0);
7425 static int vmSwapOneObjectThreaded() {
7426 return vmSwapOneObject(1);
7429 /* Return true if it's safe to swap out objects in a given moment.
7430 * Basically we don't want to swap objects out while there is a BGSAVE
7431 * or a BGAEOREWRITE running in backgroud. */
7432 static int vmCanSwapOut(void) {
7433 return (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1);
7436 /* Delete a key if swapped. Returns 1 if the key was found, was swapped
7437 * and was deleted. Otherwise 0 is returned. */
7438 static int deleteIfSwapped(redisDb
*db
, robj
*key
) {
7442 if ((de
= dictFind(db
->dict
,key
)) == NULL
) return 0;
7443 foundkey
= dictGetEntryKey(de
);
7444 if (foundkey
->storage
== REDIS_VM_MEMORY
) return 0;
7449 /* =================== Virtual Memory - Threaded I/O ======================= */
7451 static void freeIOJob(iojob
*j
) {
7452 if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
||
7453 j
->type
== REDIS_IOJOB_DO_SWAP
)
7454 decrRefCount(j
->val
);
7455 decrRefCount(j
->key
);
7459 /* Every time a thread finished a Job, it writes a byte into the write side
7460 * of an unix pipe in order to "awake" the main thread, and this function
7462 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
,
7469 REDIS_NOTUSED(mask
);
7470 REDIS_NOTUSED(privdata
);
7472 /* For every byte we read in the read side of the pipe, there is one
7473 * I/O job completed to process. */
7474 while((retval
= read(fd
,buf
,1)) == 1) {
7478 struct dictEntry
*de
;
7480 redisLog(REDIS_DEBUG
,"Processing I/O completed job");
7482 /* Get the processed element (the oldest one) */
7484 assert(listLength(server
.io_processed
) != 0);
7485 ln
= listFirst(server
.io_processed
);
7487 listDelNode(server
.io_processed
,ln
);
7489 /* If this job is marked as canceled, just ignore it */
7494 /* Post process it in the main thread, as there are things we
7495 * can do just here to avoid race conditions and/or invasive locks */
7496 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
);
7497 de
= dictFind(j
->db
->dict
,j
->key
);
7499 key
= dictGetEntryKey(de
);
7500 if (j
->type
== REDIS_IOJOB_LOAD
) {
7501 /* Key loaded, bring it at home */
7502 key
->storage
= REDIS_VM_MEMORY
;
7503 key
->vm
.atime
= server
.unixtime
;
7504 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
7505 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk (threaded)",
7506 (unsigned char*) key
->ptr
);
7507 server
.vm_stats_swapped_objects
--;
7508 server
.vm_stats_swapins
++;
7510 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
7511 /* Now we know the amount of pages required to swap this object.
7512 * Let's find some space for it, and queue this task again
7513 * rebranded as REDIS_IOJOB_DO_SWAP. */
7514 if (vmFindContiguousPages(&j
->page
,j
->pages
) == REDIS_ERR
) {
7515 /* Ooops... no space! */
7518 /* Note that we need to mark this pages as used now,
7519 * if the job will be canceled, we'll mark them as freed
7521 vmMarkPagesUsed(j
->page
,j
->pages
);
7522 j
->type
= REDIS_IOJOB_DO_SWAP
;
7527 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
7530 /* Key swapped. We can finally free some memory. */
7531 if (key
->storage
!= REDIS_VM_SWAPPING
) {
7532 printf("key->storage: %d\n",key
->storage
);
7533 printf("key->name: %s\n",(char*)key
->ptr
);
7534 printf("key->refcount: %d\n",key
->refcount
);
7535 printf("val: %p\n",(void*)j
->val
);
7536 printf("val->type: %d\n",j
->val
->type
);
7537 printf("val->ptr: %s\n",(char*)j
->val
->ptr
);
7539 redisAssert(key
->storage
== REDIS_VM_SWAPPING
);
7540 val
= dictGetEntryVal(de
);
7541 key
->vm
.page
= j
->page
;
7542 key
->vm
.usedpages
= j
->pages
;
7543 key
->storage
= REDIS_VM_SWAPPED
;
7544 key
->vtype
= j
->val
->type
;
7545 decrRefCount(val
); /* Deallocate the object from memory. */
7546 dictGetEntryVal(de
) = NULL
;
7547 redisLog(REDIS_DEBUG
,
7548 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
7549 (unsigned char*) key
->ptr
,
7550 (unsigned long long) j
->page
, (unsigned long long) j
->pages
);
7551 server
.vm_stats_swapped_objects
++;
7552 server
.vm_stats_swapouts
++;
7554 /* Put a few more swap requests in queue if we are still
7556 if (zmalloc_used_memory() > server
.vm_max_memory
) {
7560 more
= listLength(server
.io_newjobs
) <
7561 (unsigned) server
.vm_max_threads
;
7563 /* Don't waste CPU time if swappable objects are rare. */
7564 if (vmSwapOneObjectThreaded() == REDIS_ERR
) break;
7569 if (processed
== REDIS_MAX_COMPLETED_JOBS_PROCESSED
) return;
7571 if (retval
< 0 && errno
!= EAGAIN
) {
7572 redisLog(REDIS_WARNING
,
7573 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
7578 static void lockThreadedIO(void) {
7579 pthread_mutex_lock(&server
.io_mutex
);
7582 static void unlockThreadedIO(void) {
7583 pthread_mutex_unlock(&server
.io_mutex
);
7586 /* Remove the specified object from the threaded I/O queue if still not
7587 * processed, otherwise make sure to flag it as canceled. */
7588 static void vmCancelThreadedIOJob(robj
*o
) {
7590 server
.io_newjobs
, /* 0 */
7591 server
.io_processing
, /* 1 */
7592 server
.io_processed
/* 2 */
7596 assert(o
->storage
== REDIS_VM_LOADING
|| o
->storage
== REDIS_VM_SWAPPING
);
7599 /* Search for a matching key in one of the queues */
7600 for (i
= 0; i
< 3; i
++) {
7604 listRewind(lists
[i
],&li
);
7605 while ((ln
= listNext(&li
)) != NULL
) {
7606 iojob
*job
= ln
->value
;
7608 if (job
->canceled
) continue; /* Skip this, already canceled. */
7609 if (compareStringObjects(job
->key
,o
) == 0) {
7610 redisLog(REDIS_DEBUG
,"*** CANCELED %p (%s) (LIST ID %d)\n",
7611 (void*)job
, (char*)o
->ptr
, i
);
7612 /* Mark the pages as free since the swap didn't happened
7613 * or happened but is now discarded. */
7614 if (job
->type
== REDIS_IOJOB_DO_SWAP
)
7615 vmMarkPagesFree(job
->page
,job
->pages
);
7616 /* Cancel the job. It depends on the list the job is
7619 case 0: /* io_newjobs */
7620 /* If the job was yet not processed the best thing to do
7621 * is to remove it from the queue at all */
7623 listDelNode(lists
[i
],ln
);
7625 case 1: /* io_processing */
7626 /* Oh Shi- the thread is messing with the Job, and
7627 * probably with the object if this is a
7628 * PREPARE_SWAP or DO_SWAP job. Better to wait for the
7629 * job to move into the next queue... */
7630 if (job
->type
!= REDIS_IOJOB_LOAD
) {
7631 /* Yes, we try again and again until the job
7634 /* But let's wait some time for the I/O thread
7635 * to finish with this job. After all this condition
7636 * should be very rare. */
7643 case 2: /* io_processed */
7644 /* The job was already processed, that's easy...
7645 * just mark it as canceled so that we'll ignore it
7646 * when processing completed jobs. */
7650 /* Finally we have to adjust the storage type of the object
7651 * in order to "UNDO" the operaiton. */
7652 if (o
->storage
== REDIS_VM_LOADING
)
7653 o
->storage
= REDIS_VM_SWAPPED
;
7654 else if (o
->storage
== REDIS_VM_SWAPPING
)
7655 o
->storage
= REDIS_VM_MEMORY
;
7662 assert(1 != 1); /* We should never reach this */
7665 static void *IOThreadEntryPoint(void *arg
) {
7670 pthread_detach(pthread_self());
7672 /* Get a new job to process */
7674 if (listLength(server
.io_newjobs
) == 0) {
7675 #ifdef REDIS_HELGRIND_FRIENDLY
7676 /* No new jobs? Wait and retry, because to be Helgrind
7677 * (valgrind --tool=helgrind) what's needed is to take
7678 * the same threads running instead to create/destroy threads
7679 * as needed (otherwise valgrind will fail) */
7681 usleep(1); /* Give some time for the I/O thread to work. */
7684 /* No new jobs in queue, exit. */
7685 redisLog(REDIS_DEBUG
,"Thread %lld exiting, nothing to do",
7686 (long long) pthread_self());
7687 server
.io_active_threads
--;
7691 ln
= listFirst(server
.io_newjobs
);
7693 listDelNode(server
.io_newjobs
,ln
);
7694 /* Add the job in the processing queue */
7695 j
->thread
= pthread_self();
7696 listAddNodeTail(server
.io_processing
,j
);
7697 ln
= listLast(server
.io_processing
); /* We use ln later to remove it */
7699 redisLog(REDIS_DEBUG
,"Thread %lld got a new job (type %d): %p about key '%s'",
7700 (long long) pthread_self(), j
->type
, (void*)j
, (char*)j
->key
->ptr
);
7702 /* Process the Job */
7703 if (j
->type
== REDIS_IOJOB_LOAD
) {
7704 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
7705 FILE *fp
= fopen("/dev/null","w+");
7706 j
->pages
= rdbSavedObjectPages(j
->val
,fp
);
7708 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
7709 if (vmWriteObjectOnSwap(j
->val
,j
->page
) == REDIS_ERR
)
7713 /* Done: insert the job into the processed queue */
7714 redisLog(REDIS_DEBUG
,"Thread %lld completed the job: %p (key %s)",
7715 (long long) pthread_self(), (void*)j
, (char*)j
->key
->ptr
);
7717 listDelNode(server
.io_processing
,ln
);
7718 listAddNodeTail(server
.io_processed
,j
);
7721 /* Signal the main thread there is new stuff to process */
7722 assert(write(server
.io_ready_pipe_write
,"x",1) == 1);
7724 return NULL
; /* never reached */
7727 static void spawnIOThread(void) {
7730 pthread_create(&thread
,&server
.io_threads_attr
,IOThreadEntryPoint
,NULL
);
7731 server
.io_active_threads
++;
7734 /* We need to wait for the last thread to exit before we are able to
7735 * fork() in order to BGSAVE or BGREWRITEAOF. */
7736 static void waitZeroActiveThreads(void) {
7739 if (server
.io_active_threads
== 0) {
7744 usleep(10000); /* 10 milliseconds */
7748 /* This function must be called while with threaded IO locked */
7749 static void queueIOJob(iojob
*j
) {
7750 redisLog(REDIS_DEBUG
,"Queued IO Job %p type %d about key '%s'\n",
7751 (void*)j
, j
->type
, (char*)j
->key
->ptr
);
7752 listAddNodeTail(server
.io_newjobs
,j
);
7753 if (server
.io_active_threads
< server
.vm_max_threads
)
7757 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
) {
7760 assert(key
->storage
== REDIS_VM_MEMORY
);
7761 assert(key
->refcount
== 1);
7763 j
= zmalloc(sizeof(*j
));
7764 j
->type
= REDIS_IOJOB_PREPARE_SWAP
;
7766 j
->key
= dupStringObject(key
);
7770 j
->thread
= (pthread_t
) -1;
7771 key
->storage
= REDIS_VM_SWAPPING
;
7779 /* ================================= Debugging ============================== */
7781 static void debugCommand(redisClient
*c
) {
7782 if (!strcasecmp(c
->argv
[1]->ptr
,"segfault")) {
7784 } else if (!strcasecmp(c
->argv
[1]->ptr
,"reload")) {
7785 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
7786 addReply(c
,shared
.err
);
7790 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
7791 addReply(c
,shared
.err
);
7794 redisLog(REDIS_WARNING
,"DB reloaded by DEBUG RELOAD");
7795 addReply(c
,shared
.ok
);
7796 } else if (!strcasecmp(c
->argv
[1]->ptr
,"loadaof")) {
7798 if (loadAppendOnlyFile(server
.appendfilename
) != REDIS_OK
) {
7799 addReply(c
,shared
.err
);
7802 redisLog(REDIS_WARNING
,"Append Only File loaded by DEBUG LOADAOF");
7803 addReply(c
,shared
.ok
);
7804 } else if (!strcasecmp(c
->argv
[1]->ptr
,"object") && c
->argc
== 3) {
7805 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
7809 addReply(c
,shared
.nokeyerr
);
7812 key
= dictGetEntryKey(de
);
7813 val
= dictGetEntryVal(de
);
7814 if (server
.vm_enabled
&& (key
->storage
== REDIS_VM_MEMORY
||
7815 key
->storage
== REDIS_VM_SWAPPING
)) {
7816 addReplySds(c
,sdscatprintf(sdsempty(),
7817 "+Key at:%p refcount:%d, value at:%p refcount:%d "
7818 "encoding:%d serializedlength:%lld\r\n",
7819 (void*)key
, key
->refcount
, (void*)val
, val
->refcount
,
7820 val
->encoding
, rdbSavedObjectLen(val
,NULL
)));
7822 addReplySds(c
,sdscatprintf(sdsempty(),
7823 "+Key at:%p refcount:%d, value swapped at: page %llu "
7824 "using %llu pages\r\n",
7825 (void*)key
, key
->refcount
, (unsigned long long) key
->vm
.page
,
7826 (unsigned long long) key
->vm
.usedpages
));
7828 } else if (!strcasecmp(c
->argv
[1]->ptr
,"swapout") && c
->argc
== 3) {
7829 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
7832 if (!server
.vm_enabled
) {
7833 addReplySds(c
,sdsnew("-ERR Virtual Memory is disabled\r\n"));
7837 addReply(c
,shared
.nokeyerr
);
7840 key
= dictGetEntryKey(de
);
7841 val
= dictGetEntryVal(de
);
7842 /* If the key is shared we want to create a copy */
7843 if (key
->refcount
> 1) {
7844 robj
*newkey
= dupStringObject(key
);
7846 key
= dictGetEntryKey(de
) = newkey
;
7849 if (key
->storage
!= REDIS_VM_MEMORY
) {
7850 addReplySds(c
,sdsnew("-ERR This key is not in memory\r\n"));
7851 } else if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
7852 dictGetEntryVal(de
) = NULL
;
7853 addReply(c
,shared
.ok
);
7855 addReply(c
,shared
.err
);
7858 addReplySds(c
,sdsnew(
7859 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPOUT <key>|RELOAD]\r\n"));
7863 static void _redisAssert(char *estr
, char *file
, int line
) {
7864 redisLog(REDIS_WARNING
,"=== ASSERTION FAILED ===");
7865 redisLog(REDIS_WARNING
,"==> %s:%d '%s' is not true\n",file
,line
,estr
);
7866 #ifdef HAVE_BACKTRACE
7867 redisLog(REDIS_WARNING
,"(forcing SIGSEGV in order to print the stack trace)");
7872 /* =================================== Main! ================================ */
7875 int linuxOvercommitMemoryValue(void) {
7876 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
7880 if (fgets(buf
,64,fp
) == NULL
) {
7889 void linuxOvercommitMemoryWarning(void) {
7890 if (linuxOvercommitMemoryValue() == 0) {
7891 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.");
7894 #endif /* __linux__ */
7896 static void daemonize(void) {
7900 if (fork() != 0) exit(0); /* parent exits */
7901 setsid(); /* create a new session */
7903 /* Every output goes to /dev/null. If Redis is daemonized but
7904 * the 'logfile' is set to 'stdout' in the configuration file
7905 * it will not log at all. */
7906 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
7907 dup2(fd
, STDIN_FILENO
);
7908 dup2(fd
, STDOUT_FILENO
);
7909 dup2(fd
, STDERR_FILENO
);
7910 if (fd
> STDERR_FILENO
) close(fd
);
7912 /* Try to write the pid file */
7913 fp
= fopen(server
.pidfile
,"w");
7915 fprintf(fp
,"%d\n",getpid());
7920 int main(int argc
, char **argv
) {
7923 resetServerSaveParams();
7924 loadServerConfig(argv
[1]);
7925 } else if (argc
> 2) {
7926 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
7929 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'");
7931 if (server
.daemonize
) daemonize();
7933 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
7935 linuxOvercommitMemoryWarning();
7937 if (server
.appendonly
) {
7938 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
7939 redisLog(REDIS_NOTICE
,"DB loaded from append only file");
7941 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
7942 redisLog(REDIS_NOTICE
,"DB loaded from disk");
7944 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
7946 aeDeleteEventLoop(server
.el
);
7950 /* ============================= Backtrace support ========================= */
7952 #ifdef HAVE_BACKTRACE
7953 static char *findFuncName(void *pointer
, unsigned long *offset
);
7955 static void *getMcontextEip(ucontext_t
*uc
) {
7956 #if defined(__FreeBSD__)
7957 return (void*) uc
->uc_mcontext
.mc_eip
;
7958 #elif defined(__dietlibc__)
7959 return (void*) uc
->uc_mcontext
.eip
;
7960 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
7962 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
7964 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
7966 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
7967 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
7968 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
7970 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
7972 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
7973 return (void*) uc
->uc_mcontext
.gregs
[REG_EIP
]; /* Linux 32/64 bit */
7974 #elif defined(__ia64__) /* Linux IA64 */
7975 return (void*) uc
->uc_mcontext
.sc_ip
;
7981 static void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
7983 char **messages
= NULL
;
7984 int i
, trace_size
= 0;
7985 unsigned long offset
=0;
7986 ucontext_t
*uc
= (ucontext_t
*) secret
;
7988 REDIS_NOTUSED(info
);
7990 redisLog(REDIS_WARNING
,
7991 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
7992 infostring
= genRedisInfoString();
7993 redisLog(REDIS_WARNING
, "%s",infostring
);
7994 /* It's not safe to sdsfree() the returned string under memory
7995 * corruption conditions. Let it leak as we are going to abort */
7997 trace_size
= backtrace(trace
, 100);
7998 /* overwrite sigaction with caller's address */
7999 if (getMcontextEip(uc
) != NULL
) {
8000 trace
[1] = getMcontextEip(uc
);
8002 messages
= backtrace_symbols(trace
, trace_size
);
8004 for (i
=1; i
<trace_size
; ++i
) {
8005 char *fn
= findFuncName(trace
[i
], &offset
), *p
;
8007 p
= strchr(messages
[i
],'+');
8008 if (!fn
|| (p
&& ((unsigned long)strtol(p
+1,NULL
,10)) < offset
)) {
8009 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
8011 redisLog(REDIS_WARNING
,"%d redis-server %p %s + %d", i
, trace
[i
], fn
, (unsigned int)offset
);
8014 /* free(messages); Don't call free() with possibly corrupted memory. */
8018 static void setupSigSegvAction(void) {
8019 struct sigaction act
;
8021 sigemptyset (&act
.sa_mask
);
8022 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
8023 * is used. Otherwise, sa_handler is used */
8024 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
8025 act
.sa_sigaction
= segvHandler
;
8026 sigaction (SIGSEGV
, &act
, NULL
);
8027 sigaction (SIGBUS
, &act
, NULL
);
8028 sigaction (SIGFPE
, &act
, NULL
);
8029 sigaction (SIGILL
, &act
, NULL
);
8030 sigaction (SIGBUS
, &act
, NULL
);
8034 #include "staticsymbols.h"
8035 /* This function try to convert a pointer into a function name. It's used in
8036 * oreder to provide a backtrace under segmentation fault that's able to
8037 * display functions declared as static (otherwise the backtrace is useless). */
8038 static char *findFuncName(void *pointer
, unsigned long *offset
){
8040 unsigned long off
, minoff
= 0;
8042 /* Try to match against the Symbol with the smallest offset */
8043 for (i
=0; symsTable
[i
].pointer
; i
++) {
8044 unsigned long lp
= (unsigned long) pointer
;
8046 if (lp
!= (unsigned long)-1 && lp
>= symsTable
[i
].pointer
) {
8047 off
=lp
-symsTable
[i
].pointer
;
8048 if (ret
< 0 || off
< minoff
) {
8054 if (ret
== -1) return NULL
;
8056 return symsTable
[ret
].name
;
8058 #else /* HAVE_BACKTRACE */
8059 static void setupSigSegvAction(void) {
8061 #endif /* HAVE_BACKTRACE */