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 */
82 /* Static server configuration */
83 #define REDIS_SERVERPORT 6379 /* TCP port */
84 #define REDIS_MAXIDLETIME (60*5) /* default client timeout */
85 #define REDIS_IOBUF_LEN 1024
86 #define REDIS_LOADBUF_LEN 1024
87 #define REDIS_STATIC_ARGS 4
88 #define REDIS_DEFAULT_DBNUM 16
89 #define REDIS_CONFIGLINE_MAX 1024
90 #define REDIS_OBJFREELIST_MAX 1000000 /* Max number of objects to cache */
91 #define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
92 #define REDIS_EXPIRELOOKUPS_PER_CRON 100 /* try to expire 100 keys/second */
93 #define REDIS_MAX_WRITE_PER_EVENT (1024*64)
94 #define REDIS_REQUEST_MAX_SIZE (1024*1024*256) /* max bytes in inline command */
96 /* If more then REDIS_WRITEV_THRESHOLD write packets are pending use writev */
97 #define REDIS_WRITEV_THRESHOLD 3
98 /* Max number of iovecs used for each writev call */
99 #define REDIS_WRITEV_IOVEC_COUNT 256
101 /* Hash table parameters */
102 #define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
105 #define REDIS_CMD_BULK 1 /* Bulk write command */
106 #define REDIS_CMD_INLINE 2 /* Inline command */
107 /* REDIS_CMD_DENYOOM reserves a longer comment: all the commands marked with
108 this flags will return an error when the 'maxmemory' option is set in the
109 config file and the server is using more than maxmemory bytes of memory.
110 In short this commands are denied on low memory conditions. */
111 #define REDIS_CMD_DENYOOM 4
114 #define REDIS_STRING 0
120 /* Objects encoding */
121 #define REDIS_ENCODING_RAW 0 /* Raw representation */
122 #define REDIS_ENCODING_INT 1 /* Encoded as integer */
124 /* Object types only used for dumping to disk */
125 #define REDIS_EXPIRETIME 253
126 #define REDIS_SELECTDB 254
127 #define REDIS_EOF 255
129 /* Defines related to the dump file format. To store 32 bits lengths for short
130 * keys requires a lot of space, so we check the most significant 2 bits of
131 * the first byte to interpreter the length:
133 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
134 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
135 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
136 * 11|000000 this means: specially encoded object will follow. The six bits
137 * number specify the kind of object that follows.
138 * See the REDIS_RDB_ENC_* defines.
140 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
141 * values, will fit inside. */
142 #define REDIS_RDB_6BITLEN 0
143 #define REDIS_RDB_14BITLEN 1
144 #define REDIS_RDB_32BITLEN 2
145 #define REDIS_RDB_ENCVAL 3
146 #define REDIS_RDB_LENERR UINT_MAX
148 /* When a length of a string object stored on disk has the first two bits
149 * set, the remaining two bits specify a special encoding for the object
150 * accordingly to the following defines: */
151 #define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
152 #define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
153 #define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
154 #define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
156 /* Virtual memory object->where field. */
157 #define REDIS_VM_MEMORY 0 /* The object is on memory */
158 #define REDIS_VM_SWAPPED 1 /* The object is on disk */
159 #define REDIS_VM_SWAPPING 2 /* Redis is swapping this object on disk */
160 #define REDIS_VM_LOADING 3 /* Redis is loading this object from disk */
162 /* Virtual memory static configuration stuff.
163 * Check vmFindContiguousPages() to know more about this magic numbers. */
164 #define REDIS_VM_MAX_NEAR_PAGES 65536
165 #define REDIS_VM_MAX_RANDOM_JUMP 4096
166 #define REDIS_VM_MAX_THREADS 32
167 /* The following is the number of completed I/O jobs to process when the
168 * handelr is called. 1 is the minimum, and also the default, as it allows
169 * to block as little as possible other accessing clients. While Virtual
170 * Memory I/O operations are performed by threads, this operations must
171 * be processed by the main thread when completed to take effect. */
172 #define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
175 #define REDIS_CLOSE 1 /* This client connection should be closed ASAP */
176 #define REDIS_SLAVE 2 /* This client is a slave server */
177 #define REDIS_MASTER 4 /* This client is a master server */
178 #define REDIS_MONITOR 8 /* This client is a slave monitor, see MONITOR */
179 #define REDIS_MULTI 16 /* This client is in a MULTI context */
180 #define REDIS_BLOCKED 32 /* The client is waiting in a blocking operation */
181 #define REDIS_IO_WAIT 64 /* The client is waiting for Virtual Memory I/O */
183 /* Slave replication state - slave side */
184 #define REDIS_REPL_NONE 0 /* No active replication */
185 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
186 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
188 /* Slave replication state - from the point of view of master
189 * Note that in SEND_BULK and ONLINE state the slave receives new updates
190 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
191 * to start the next background saving in order to send updates to it. */
192 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
193 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
194 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
195 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
197 /* List related stuff */
201 /* Sort operations */
202 #define REDIS_SORT_GET 0
203 #define REDIS_SORT_ASC 1
204 #define REDIS_SORT_DESC 2
205 #define REDIS_SORTKEY_MAX 1024
208 #define REDIS_DEBUG 0
209 #define REDIS_VERBOSE 1
210 #define REDIS_NOTICE 2
211 #define REDIS_WARNING 3
213 /* Anti-warning macro... */
214 #define REDIS_NOTUSED(V) ((void) V)
216 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
217 #define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
219 /* Append only defines */
220 #define APPENDFSYNC_NO 0
221 #define APPENDFSYNC_ALWAYS 1
222 #define APPENDFSYNC_EVERYSEC 2
224 /* We can print the stacktrace, so our assert is defined this way: */
225 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),exit(1)))
226 static void _redisAssert(char *estr
, char *file
, int line
);
228 /*================================= Data types ============================== */
230 /* A redis object, that is a type able to hold a string / list / set */
232 /* The VM object structure */
233 struct redisObjectVM
{
234 off_t page
; /* the page at witch the object is stored on disk */
235 off_t usedpages
; /* number of pages used on disk */
236 time_t atime
; /* Last access time */
239 /* The actual Redis Object */
240 typedef struct redisObject
{
243 unsigned char encoding
;
244 unsigned char storage
; /* If this object is a key, where is the value?
245 * REDIS_VM_MEMORY, REDIS_VM_SWAPPED, ... */
246 unsigned char vtype
; /* If this object is a key, and value is swapped out,
247 * this is the type of the swapped out object. */
249 /* VM fields, this are only allocated if VM is active, otherwise the
250 * object allocation function will just allocate
251 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
252 * Redis without VM active will not have any overhead. */
253 struct redisObjectVM vm
;
256 /* Macro used to initalize a Redis object allocated on the stack.
257 * Note that this macro is taken near the structure definition to make sure
258 * we'll update it when the structure is changed, to avoid bugs like
259 * bug #85 introduced exactly in this way. */
260 #define initStaticStringObject(_var,_ptr) do { \
262 _var.type = REDIS_STRING; \
263 _var.encoding = REDIS_ENCODING_RAW; \
265 if (server.vm_enabled) _var.storage = REDIS_VM_MEMORY; \
268 typedef struct redisDb
{
269 dict
*dict
; /* The keyspace for this DB */
270 dict
*expires
; /* Timeout of keys with a timeout set */
271 dict
*blockingkeys
; /* Keys with clients waiting for data (BLPOP) */
275 /* Client MULTI/EXEC state */
276 typedef struct multiCmd
{
279 struct redisCommand
*cmd
;
282 typedef struct multiState
{
283 multiCmd
*commands
; /* Array of MULTI commands */
284 int count
; /* Total number of MULTI commands */
287 /* With multiplexing we need to take per-clinet state.
288 * Clients are taken in a liked list. */
289 typedef struct redisClient
{
294 robj
**argv
, **mbargv
;
296 int bulklen
; /* bulk read len. -1 if not in bulk read mode */
297 int multibulk
; /* multi bulk command format active */
300 time_t lastinteraction
; /* time of the last interaction, used for timeout */
301 int flags
; /* REDIS_CLOSE | REDIS_SLAVE | REDIS_MONITOR */
303 int slaveseldb
; /* slave selected db, if this client is a slave */
304 int authenticated
; /* when requirepass is non-NULL */
305 int replstate
; /* replication state if this is a slave */
306 int repldbfd
; /* replication DB file descriptor */
307 long repldboff
; /* replication DB file offset */
308 off_t repldbsize
; /* replication DB file size */
309 multiState mstate
; /* MULTI/EXEC state */
310 robj
**blockingkeys
; /* The key we waiting to terminate a blocking
311 * operation such as BLPOP. Otherwise NULL. */
312 int blockingkeysnum
; /* Number of blocking keys */
313 time_t blockingto
; /* Blocking operation timeout. If UNIX current time
314 * is >= blockingto then the operation timed out. */
315 list
*io_keys
; /* Keys this client is waiting to be loaded from the
316 * swap file in order to continue. */
324 /* Global server state structure */
329 dict
*sharingpool
; /* Poll used for object sharing */
330 unsigned int sharingpoolsize
;
331 long long dirty
; /* changes to DB from the last save */
333 list
*slaves
, *monitors
;
334 char neterr
[ANET_ERR_LEN
];
336 int cronloops
; /* number of times the cron function run */
337 list
*objfreelist
; /* A list of freed objects to avoid malloc() */
338 time_t lastsave
; /* Unix time of last save succeeede */
339 size_t usedmemory
; /* Used memory in megabytes */
340 /* Fields used only for stats */
341 time_t stat_starttime
; /* server start time */
342 long long stat_numcommands
; /* number of processed commands */
343 long long stat_numconnections
; /* number of connections received */
356 pid_t bgsavechildpid
;
357 pid_t bgrewritechildpid
;
358 sds bgrewritebuf
; /* buffer taken by parent during oppend only rewrite */
359 struct saveparam
*saveparams
;
364 char *appendfilename
;
368 /* Replication related */
373 redisClient
*master
; /* client that is master for this slave */
375 unsigned int maxclients
;
376 unsigned long long maxmemory
;
377 unsigned int blockedclients
;
378 /* Sort parameters - qsort_r() is only available under BSD so we
379 * have to take this state global, in order to pass it to sortCompare() */
383 /* Virtual memory configuration */
387 unsigned long long vm_max_memory
;
388 /* Virtual memory state */
391 off_t vm_next_page
; /* Next probably empty page */
392 off_t vm_near_pages
; /* Number of pages allocated sequentially */
393 unsigned char *vm_bitmap
; /* Bitmap of free/used pages */
394 time_t unixtime
; /* Unix time sampled every second. */
395 /* Virtual memory I/O threads stuff */
396 /* An I/O thread process an element taken from the io_jobs queue and
397 * put the result of the operation in the io_done list. While the
398 * job is being processed, it's put on io_processing queue. */
399 list
*io_newjobs
; /* List of VM I/O jobs yet to be processed */
400 list
*io_processing
; /* List of VM I/O jobs being processed */
401 list
*io_processed
; /* List of VM I/O jobs already processed */
402 list
*io_clients
; /* All the clients waiting for SWAP I/O operations */
403 pthread_mutex_t io_mutex
; /* lock to access io_jobs/io_done/io_thread_job */
404 pthread_mutex_t obj_freelist_mutex
; /* safe redis objects creation/free */
405 pthread_mutex_t io_swapfile_mutex
; /* So we can lseek + write */
406 int io_active_threads
; /* Number of running I/O threads */
407 int vm_max_threads
; /* Max number of I/O threads running at the same time */
408 /* Our main thread is blocked on the event loop, locking for sockets ready
409 * to be read or written, so when a threaded I/O operation is ready to be
410 * processed by the main thread, the I/O thread will use a unix pipe to
411 * awake the main thread. The followings are the two pipe FDs. */
412 int io_ready_pipe_read
;
413 int io_ready_pipe_write
;
414 /* Virtual memory stats */
415 unsigned long long vm_stats_used_pages
;
416 unsigned long long vm_stats_swapped_objects
;
417 unsigned long long vm_stats_swapouts
;
418 unsigned long long vm_stats_swapins
;
422 typedef void redisCommandProc(redisClient
*c
);
423 struct redisCommand
{
425 redisCommandProc
*proc
;
430 struct redisFunctionSym
{
432 unsigned long pointer
;
435 typedef struct _redisSortObject
{
443 typedef struct _redisSortOperation
{
446 } redisSortOperation
;
448 /* ZSETs use a specialized version of Skiplists */
450 typedef struct zskiplistNode
{
451 struct zskiplistNode
**forward
;
452 struct zskiplistNode
*backward
;
457 typedef struct zskiplist
{
458 struct zskiplistNode
*header
, *tail
;
459 unsigned long length
;
463 typedef struct zset
{
468 /* Our shared "common" objects */
470 struct sharedObjectsStruct
{
471 robj
*crlf
, *ok
, *err
, *emptybulk
, *czero
, *cone
, *pong
, *space
,
472 *colon
, *nullbulk
, *nullmultibulk
, *queued
,
473 *emptymultibulk
, *wrongtypeerr
, *nokeyerr
, *syntaxerr
, *sameobjecterr
,
474 *outofrangeerr
, *plus
,
475 *select0
, *select1
, *select2
, *select3
, *select4
,
476 *select5
, *select6
, *select7
, *select8
, *select9
;
479 /* Global vars that are actally used as constants. The following double
480 * values are used for double on-disk serialization, and are initialized
481 * at runtime to avoid strange compiler optimizations. */
483 static double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
;
485 /* VM threaded I/O request message */
486 #define REDIS_IOJOB_LOAD 0 /* Load from disk to memory */
487 #define REDIS_IOJOB_PREPARE_SWAP 1 /* Compute needed pages */
488 #define REDIS_IOJOB_DO_SWAP 2 /* Swap from memory to disk */
489 typedef struct iojon
{
490 int type
; /* Request type, REDIS_IOJOB_* */
491 redisDb
*db
;/* Redis database */
492 robj
*key
; /* This I/O request is about swapping this key */
493 robj
*val
; /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
494 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
495 off_t page
; /* Swap page where to read/write the object */
496 off_t pages
; /* Swap pages needed to safe object. PREPARE_SWAP return val */
497 int canceled
; /* True if this command was canceled by blocking side of VM */
498 pthread_t thread
; /* ID of the thread processing this entry */
501 /*================================ Prototypes =============================== */
503 static void freeStringObject(robj
*o
);
504 static void freeListObject(robj
*o
);
505 static void freeSetObject(robj
*o
);
506 static void decrRefCount(void *o
);
507 static robj
*createObject(int type
, void *ptr
);
508 static void freeClient(redisClient
*c
);
509 static int rdbLoad(char *filename
);
510 static void addReply(redisClient
*c
, robj
*obj
);
511 static void addReplySds(redisClient
*c
, sds s
);
512 static void incrRefCount(robj
*o
);
513 static int rdbSaveBackground(char *filename
);
514 static robj
*createStringObject(char *ptr
, size_t len
);
515 static robj
*dupStringObject(robj
*o
);
516 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
517 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
518 static int syncWithMaster(void);
519 static robj
*tryObjectSharing(robj
*o
);
520 static int tryObjectEncoding(robj
*o
);
521 static robj
*getDecodedObject(robj
*o
);
522 static int removeExpire(redisDb
*db
, robj
*key
);
523 static int expireIfNeeded(redisDb
*db
, robj
*key
);
524 static int deleteIfVolatile(redisDb
*db
, robj
*key
);
525 static int deleteIfSwapped(redisDb
*db
, robj
*key
);
526 static int deleteKey(redisDb
*db
, robj
*key
);
527 static time_t getExpire(redisDb
*db
, robj
*key
);
528 static int setExpire(redisDb
*db
, robj
*key
, time_t when
);
529 static void updateSlavesWaitingBgsave(int bgsaveerr
);
530 static void freeMemoryIfNeeded(void);
531 static int processCommand(redisClient
*c
);
532 static void setupSigSegvAction(void);
533 static void rdbRemoveTempFile(pid_t childpid
);
534 static void aofRemoveTempFile(pid_t childpid
);
535 static size_t stringObjectLen(robj
*o
);
536 static void processInputBuffer(redisClient
*c
);
537 static zskiplist
*zslCreate(void);
538 static void zslFree(zskiplist
*zsl
);
539 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
);
540 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
541 static void initClientMultiState(redisClient
*c
);
542 static void freeClientMultiState(redisClient
*c
);
543 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
);
544 static void unblockClient(redisClient
*c
);
545 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
);
546 static void vmInit(void);
547 static void vmMarkPagesFree(off_t page
, off_t count
);
548 static robj
*vmLoadObject(robj
*key
);
549 static robj
*vmPreviewObject(robj
*key
);
550 static int vmSwapOneObjectBlocking(void);
551 static int vmSwapOneObjectThreaded(void);
552 static int vmCanSwapOut(void);
553 static int tryFreeOneObjectFromFreelist(void);
554 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
555 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
556 static void vmCancelThreadedIOJob(robj
*o
);
557 static void lockThreadedIO(void);
558 static void unlockThreadedIO(void);
559 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
);
560 static void freeIOJob(iojob
*j
);
561 static void queueIOJob(iojob
*j
);
562 static int vmWriteObjectOnSwap(robj
*o
, off_t page
);
563 static robj
*vmReadObjectFromSwap(off_t page
, int type
);
565 static void authCommand(redisClient
*c
);
566 static void pingCommand(redisClient
*c
);
567 static void echoCommand(redisClient
*c
);
568 static void setCommand(redisClient
*c
);
569 static void setnxCommand(redisClient
*c
);
570 static void getCommand(redisClient
*c
);
571 static void delCommand(redisClient
*c
);
572 static void existsCommand(redisClient
*c
);
573 static void incrCommand(redisClient
*c
);
574 static void decrCommand(redisClient
*c
);
575 static void incrbyCommand(redisClient
*c
);
576 static void decrbyCommand(redisClient
*c
);
577 static void selectCommand(redisClient
*c
);
578 static void randomkeyCommand(redisClient
*c
);
579 static void keysCommand(redisClient
*c
);
580 static void dbsizeCommand(redisClient
*c
);
581 static void lastsaveCommand(redisClient
*c
);
582 static void saveCommand(redisClient
*c
);
583 static void bgsaveCommand(redisClient
*c
);
584 static void bgrewriteaofCommand(redisClient
*c
);
585 static void shutdownCommand(redisClient
*c
);
586 static void moveCommand(redisClient
*c
);
587 static void renameCommand(redisClient
*c
);
588 static void renamenxCommand(redisClient
*c
);
589 static void lpushCommand(redisClient
*c
);
590 static void rpushCommand(redisClient
*c
);
591 static void lpopCommand(redisClient
*c
);
592 static void rpopCommand(redisClient
*c
);
593 static void llenCommand(redisClient
*c
);
594 static void lindexCommand(redisClient
*c
);
595 static void lrangeCommand(redisClient
*c
);
596 static void ltrimCommand(redisClient
*c
);
597 static void typeCommand(redisClient
*c
);
598 static void lsetCommand(redisClient
*c
);
599 static void saddCommand(redisClient
*c
);
600 static void sremCommand(redisClient
*c
);
601 static void smoveCommand(redisClient
*c
);
602 static void sismemberCommand(redisClient
*c
);
603 static void scardCommand(redisClient
*c
);
604 static void spopCommand(redisClient
*c
);
605 static void srandmemberCommand(redisClient
*c
);
606 static void sinterCommand(redisClient
*c
);
607 static void sinterstoreCommand(redisClient
*c
);
608 static void sunionCommand(redisClient
*c
);
609 static void sunionstoreCommand(redisClient
*c
);
610 static void sdiffCommand(redisClient
*c
);
611 static void sdiffstoreCommand(redisClient
*c
);
612 static void syncCommand(redisClient
*c
);
613 static void flushdbCommand(redisClient
*c
);
614 static void flushallCommand(redisClient
*c
);
615 static void sortCommand(redisClient
*c
);
616 static void lremCommand(redisClient
*c
);
617 static void rpoplpushcommand(redisClient
*c
);
618 static void infoCommand(redisClient
*c
);
619 static void mgetCommand(redisClient
*c
);
620 static void monitorCommand(redisClient
*c
);
621 static void expireCommand(redisClient
*c
);
622 static void expireatCommand(redisClient
*c
);
623 static void getsetCommand(redisClient
*c
);
624 static void ttlCommand(redisClient
*c
);
625 static void slaveofCommand(redisClient
*c
);
626 static void debugCommand(redisClient
*c
);
627 static void msetCommand(redisClient
*c
);
628 static void msetnxCommand(redisClient
*c
);
629 static void zaddCommand(redisClient
*c
);
630 static void zincrbyCommand(redisClient
*c
);
631 static void zrangeCommand(redisClient
*c
);
632 static void zrangebyscoreCommand(redisClient
*c
);
633 static void zrevrangeCommand(redisClient
*c
);
634 static void zcardCommand(redisClient
*c
);
635 static void zremCommand(redisClient
*c
);
636 static void zscoreCommand(redisClient
*c
);
637 static void zremrangebyscoreCommand(redisClient
*c
);
638 static void multiCommand(redisClient
*c
);
639 static void execCommand(redisClient
*c
);
640 static void blpopCommand(redisClient
*c
);
641 static void brpopCommand(redisClient
*c
);
643 /*================================= Globals ================================= */
646 static struct redisServer server
; /* server global state */
647 static struct redisCommand cmdTable
[] = {
648 {"get",getCommand
,2,REDIS_CMD_INLINE
},
649 {"set",setCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
650 {"setnx",setnxCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
651 {"del",delCommand
,-2,REDIS_CMD_INLINE
},
652 {"exists",existsCommand
,2,REDIS_CMD_INLINE
},
653 {"incr",incrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
654 {"decr",decrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
655 {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
},
656 {"rpush",rpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
657 {"lpush",lpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
658 {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
},
659 {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
},
660 {"brpop",brpopCommand
,-3,REDIS_CMD_INLINE
},
661 {"blpop",blpopCommand
,-3,REDIS_CMD_INLINE
},
662 {"llen",llenCommand
,2,REDIS_CMD_INLINE
},
663 {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
},
664 {"lset",lsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
665 {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
},
666 {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
},
667 {"lrem",lremCommand
,4,REDIS_CMD_BULK
},
668 {"rpoplpush",rpoplpushcommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
669 {"sadd",saddCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
670 {"srem",sremCommand
,3,REDIS_CMD_BULK
},
671 {"smove",smoveCommand
,4,REDIS_CMD_BULK
},
672 {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
},
673 {"scard",scardCommand
,2,REDIS_CMD_INLINE
},
674 {"spop",spopCommand
,2,REDIS_CMD_INLINE
},
675 {"srandmember",srandmemberCommand
,2,REDIS_CMD_INLINE
},
676 {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
677 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
678 {"sunion",sunionCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
679 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
680 {"sdiff",sdiffCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
681 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
682 {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
},
683 {"zadd",zaddCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
684 {"zincrby",zincrbyCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
685 {"zrem",zremCommand
,3,REDIS_CMD_BULK
},
686 {"zremrangebyscore",zremrangebyscoreCommand
,4,REDIS_CMD_INLINE
},
687 {"zrange",zrangeCommand
,-4,REDIS_CMD_INLINE
},
688 {"zrangebyscore",zrangebyscoreCommand
,-4,REDIS_CMD_INLINE
},
689 {"zrevrange",zrevrangeCommand
,-4,REDIS_CMD_INLINE
},
690 {"zcard",zcardCommand
,2,REDIS_CMD_INLINE
},
691 {"zscore",zscoreCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
692 {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
693 {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
694 {"getset",getsetCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
695 {"mset",msetCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
696 {"msetnx",msetnxCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
697 {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
},
698 {"select",selectCommand
,2,REDIS_CMD_INLINE
},
699 {"move",moveCommand
,3,REDIS_CMD_INLINE
},
700 {"rename",renameCommand
,3,REDIS_CMD_INLINE
},
701 {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
},
702 {"expire",expireCommand
,3,REDIS_CMD_INLINE
},
703 {"expireat",expireatCommand
,3,REDIS_CMD_INLINE
},
704 {"keys",keysCommand
,2,REDIS_CMD_INLINE
},
705 {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
},
706 {"auth",authCommand
,2,REDIS_CMD_INLINE
},
707 {"ping",pingCommand
,1,REDIS_CMD_INLINE
},
708 {"echo",echoCommand
,2,REDIS_CMD_BULK
},
709 {"save",saveCommand
,1,REDIS_CMD_INLINE
},
710 {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
},
711 {"bgrewriteaof",bgrewriteaofCommand
,1,REDIS_CMD_INLINE
},
712 {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
},
713 {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
},
714 {"type",typeCommand
,2,REDIS_CMD_INLINE
},
715 {"multi",multiCommand
,1,REDIS_CMD_INLINE
},
716 {"exec",execCommand
,1,REDIS_CMD_INLINE
},
717 {"sync",syncCommand
,1,REDIS_CMD_INLINE
},
718 {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
},
719 {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
},
720 {"sort",sortCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
721 {"info",infoCommand
,1,REDIS_CMD_INLINE
},
722 {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
},
723 {"ttl",ttlCommand
,2,REDIS_CMD_INLINE
},
724 {"slaveof",slaveofCommand
,3,REDIS_CMD_INLINE
},
725 {"debug",debugCommand
,-2,REDIS_CMD_INLINE
},
729 /*============================ Utility functions ============================ */
731 /* Glob-style pattern matching. */
732 int stringmatchlen(const char *pattern
, int patternLen
,
733 const char *string
, int stringLen
, int nocase
)
738 while (pattern
[1] == '*') {
743 return 1; /* match */
745 if (stringmatchlen(pattern
+1, patternLen
-1,
746 string
, stringLen
, nocase
))
747 return 1; /* match */
751 return 0; /* no match */
755 return 0; /* no match */
765 not = pattern
[0] == '^';
772 if (pattern
[0] == '\\') {
775 if (pattern
[0] == string
[0])
777 } else if (pattern
[0] == ']') {
779 } else if (patternLen
== 0) {
783 } else if (pattern
[1] == '-' && patternLen
>= 3) {
784 int start
= pattern
[0];
785 int end
= pattern
[2];
793 start
= tolower(start
);
799 if (c
>= start
&& c
<= end
)
803 if (pattern
[0] == string
[0])
806 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
816 return 0; /* no match */
822 if (patternLen
>= 2) {
829 if (pattern
[0] != string
[0])
830 return 0; /* no match */
832 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
833 return 0; /* no match */
841 if (stringLen
== 0) {
842 while(*pattern
== '*') {
849 if (patternLen
== 0 && stringLen
== 0)
854 static void redisLog(int level
, const char *fmt
, ...) {
858 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
862 if (level
>= server
.verbosity
) {
868 strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
));
869 fprintf(fp
,"%s %c ",buf
,c
[level
]);
870 vfprintf(fp
, fmt
, ap
);
876 if (server
.logfile
) fclose(fp
);
879 /*====================== Hash table type implementation ==================== */
881 /* This is an hash table type that uses the SDS dynamic strings libary as
882 * keys and radis objects as values (objects can hold SDS strings,
885 static void dictVanillaFree(void *privdata
, void *val
)
887 DICT_NOTUSED(privdata
);
891 static void dictListDestructor(void *privdata
, void *val
)
893 DICT_NOTUSED(privdata
);
894 listRelease((list
*)val
);
897 static int sdsDictKeyCompare(void *privdata
, const void *key1
,
901 DICT_NOTUSED(privdata
);
903 l1
= sdslen((sds
)key1
);
904 l2
= sdslen((sds
)key2
);
905 if (l1
!= l2
) return 0;
906 return memcmp(key1
, key2
, l1
) == 0;
909 static void dictRedisObjectDestructor(void *privdata
, void *val
)
911 DICT_NOTUSED(privdata
);
913 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
917 static int dictObjKeyCompare(void *privdata
, const void *key1
,
920 const robj
*o1
= key1
, *o2
= key2
;
921 return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
924 static unsigned int dictObjHash(const void *key
) {
926 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
929 static int dictEncObjKeyCompare(void *privdata
, const void *key1
,
932 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
935 o1
= getDecodedObject(o1
);
936 o2
= getDecodedObject(o2
);
937 cmp
= sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
943 static unsigned int dictEncObjHash(const void *key
) {
944 robj
*o
= (robj
*) key
;
946 o
= getDecodedObject(o
);
947 unsigned int hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
952 static dictType setDictType
= {
953 dictEncObjHash
, /* hash function */
956 dictEncObjKeyCompare
, /* key compare */
957 dictRedisObjectDestructor
, /* key destructor */
958 NULL
/* val destructor */
961 static dictType zsetDictType
= {
962 dictEncObjHash
, /* hash function */
965 dictEncObjKeyCompare
, /* key compare */
966 dictRedisObjectDestructor
, /* key destructor */
967 dictVanillaFree
/* val destructor of malloc(sizeof(double)) */
970 static dictType hashDictType
= {
971 dictObjHash
, /* hash function */
974 dictObjKeyCompare
, /* key compare */
975 dictRedisObjectDestructor
, /* key destructor */
976 dictRedisObjectDestructor
/* val destructor */
979 /* Keylist hash table type has unencoded redis objects as keys and
980 * lists as values. It's used for blocking operations (BLPOP) */
981 static dictType keylistDictType
= {
982 dictObjHash
, /* hash function */
985 dictObjKeyCompare
, /* key compare */
986 dictRedisObjectDestructor
, /* key destructor */
987 dictListDestructor
/* val destructor */
990 /* ========================= Random utility functions ======================= */
992 /* Redis generally does not try to recover from out of memory conditions
993 * when allocating objects or strings, it is not clear if it will be possible
994 * to report this condition to the client since the networking layer itself
995 * is based on heap allocation for send buffers, so we simply abort.
996 * At least the code will be simpler to read... */
997 static void oom(const char *msg
) {
998 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
1003 /* ====================== Redis server networking stuff ===================== */
1004 static void closeTimedoutClients(void) {
1007 time_t now
= time(NULL
);
1009 listRewind(server
.clients
);
1010 while ((ln
= listYield(server
.clients
)) != NULL
) {
1011 c
= listNodeValue(ln
);
1012 if (server
.maxidletime
&&
1013 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
1014 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
1015 (now
- c
->lastinteraction
> server
.maxidletime
))
1017 redisLog(REDIS_VERBOSE
,"Closing idle client");
1019 } else if (c
->flags
& REDIS_BLOCKED
) {
1020 if (c
->blockingto
!= 0 && c
->blockingto
< now
) {
1021 addReply(c
,shared
.nullmultibulk
);
1028 static int htNeedsResize(dict
*dict
) {
1029 long long size
, used
;
1031 size
= dictSlots(dict
);
1032 used
= dictSize(dict
);
1033 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
1034 (used
*100/size
< REDIS_HT_MINFILL
));
1037 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
1038 * we resize the hash table to save memory */
1039 static void tryResizeHashTables(void) {
1042 for (j
= 0; j
< server
.dbnum
; j
++) {
1043 if (htNeedsResize(server
.db
[j
].dict
)) {
1044 redisLog(REDIS_VERBOSE
,"The hash table %d is too sparse, resize it...",j
);
1045 dictResize(server
.db
[j
].dict
);
1046 redisLog(REDIS_VERBOSE
,"Hash table %d resized.",j
);
1048 if (htNeedsResize(server
.db
[j
].expires
))
1049 dictResize(server
.db
[j
].expires
);
1053 /* A background saving child (BGSAVE) terminated its work. Handle this. */
1054 void backgroundSaveDoneHandler(int statloc
) {
1055 int exitcode
= WEXITSTATUS(statloc
);
1056 int bysignal
= WIFSIGNALED(statloc
);
1058 if (!bysignal
&& exitcode
== 0) {
1059 redisLog(REDIS_NOTICE
,
1060 "Background saving terminated with success");
1062 server
.lastsave
= time(NULL
);
1063 } else if (!bysignal
&& exitcode
!= 0) {
1064 redisLog(REDIS_WARNING
, "Background saving error");
1066 redisLog(REDIS_WARNING
,
1067 "Background saving terminated by signal");
1068 rdbRemoveTempFile(server
.bgsavechildpid
);
1070 server
.bgsavechildpid
= -1;
1071 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1072 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1073 updateSlavesWaitingBgsave(exitcode
== 0 ? REDIS_OK
: REDIS_ERR
);
1076 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1078 void backgroundRewriteDoneHandler(int statloc
) {
1079 int exitcode
= WEXITSTATUS(statloc
);
1080 int bysignal
= WIFSIGNALED(statloc
);
1082 if (!bysignal
&& exitcode
== 0) {
1086 redisLog(REDIS_NOTICE
,
1087 "Background append only file rewriting terminated with success");
1088 /* Now it's time to flush the differences accumulated by the parent */
1089 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) server
.bgrewritechildpid
);
1090 fd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
1092 redisLog(REDIS_WARNING
, "Not able to open the temp append only file produced by the child: %s", strerror(errno
));
1095 /* Flush our data... */
1096 if (write(fd
,server
.bgrewritebuf
,sdslen(server
.bgrewritebuf
)) !=
1097 (signed) sdslen(server
.bgrewritebuf
)) {
1098 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
));
1102 redisLog(REDIS_NOTICE
,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server
.bgrewritebuf
));
1103 /* Now our work is to rename the temp file into the stable file. And
1104 * switch the file descriptor used by the server for append only. */
1105 if (rename(tmpfile
,server
.appendfilename
) == -1) {
1106 redisLog(REDIS_WARNING
,"Can't rename the temp append only file into the stable one: %s", strerror(errno
));
1110 /* Mission completed... almost */
1111 redisLog(REDIS_NOTICE
,"Append only file successfully rewritten.");
1112 if (server
.appendfd
!= -1) {
1113 /* If append only is actually enabled... */
1114 close(server
.appendfd
);
1115 server
.appendfd
= fd
;
1117 server
.appendseldb
= -1; /* Make sure it will issue SELECT */
1118 redisLog(REDIS_NOTICE
,"The new append only file was selected for future appends.");
1120 /* If append only is disabled we just generate a dump in this
1121 * format. Why not? */
1124 } else if (!bysignal
&& exitcode
!= 0) {
1125 redisLog(REDIS_WARNING
, "Background append only file rewriting error");
1127 redisLog(REDIS_WARNING
,
1128 "Background append only file rewriting terminated by signal");
1131 sdsfree(server
.bgrewritebuf
);
1132 server
.bgrewritebuf
= sdsempty();
1133 aofRemoveTempFile(server
.bgrewritechildpid
);
1134 server
.bgrewritechildpid
= -1;
1137 static int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
1138 int j
, loops
= server
.cronloops
++;
1139 REDIS_NOTUSED(eventLoop
);
1141 REDIS_NOTUSED(clientData
);
1143 /* We take a cached value of the unix time in the global state because
1144 * with virtual memory and aging there is to store the current time
1145 * in objects at every object access, and accuracy is not needed.
1146 * To access a global var is faster than calling time(NULL) */
1147 server
.unixtime
= time(NULL
);
1149 /* Update the global state with the amount of used memory */
1150 server
.usedmemory
= zmalloc_used_memory();
1152 /* Show some info about non-empty databases */
1153 for (j
= 0; j
< server
.dbnum
; j
++) {
1154 long long size
, used
, vkeys
;
1156 size
= dictSlots(server
.db
[j
].dict
);
1157 used
= dictSize(server
.db
[j
].dict
);
1158 vkeys
= dictSize(server
.db
[j
].expires
);
1159 if (!(loops
% 5) && (used
|| vkeys
)) {
1160 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
1161 /* dictPrintStats(server.dict); */
1165 /* We don't want to resize the hash tables while a bacground saving
1166 * is in progress: the saving child is created using fork() that is
1167 * implemented with a copy-on-write semantic in most modern systems, so
1168 * if we resize the HT while there is the saving child at work actually
1169 * a lot of memory movements in the parent will cause a lot of pages
1171 if (server
.bgsavechildpid
== -1) tryResizeHashTables();
1173 /* Show information about connected clients */
1175 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use, %d shared objects",
1176 listLength(server
.clients
)-listLength(server
.slaves
),
1177 listLength(server
.slaves
),
1179 dictSize(server
.sharingpool
));
1182 /* Close connections of timedout clients */
1183 if ((server
.maxidletime
&& !(loops
% 10)) || server
.blockedclients
)
1184 closeTimedoutClients();
1186 /* Check if a background saving or AOF rewrite in progress terminated */
1187 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
1191 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
1192 if (pid
== server
.bgsavechildpid
) {
1193 backgroundSaveDoneHandler(statloc
);
1195 backgroundRewriteDoneHandler(statloc
);
1199 /* If there is not a background saving in progress check if
1200 * we have to save now */
1201 time_t now
= time(NULL
);
1202 for (j
= 0; j
< server
.saveparamslen
; j
++) {
1203 struct saveparam
*sp
= server
.saveparams
+j
;
1205 if (server
.dirty
>= sp
->changes
&&
1206 now
-server
.lastsave
> sp
->seconds
) {
1207 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
1208 sp
->changes
, sp
->seconds
);
1209 rdbSaveBackground(server
.dbfilename
);
1215 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1216 * will use few CPU cycles if there are few expiring keys, otherwise
1217 * it will get more aggressive to avoid that too much memory is used by
1218 * keys that can be removed from the keyspace. */
1219 for (j
= 0; j
< server
.dbnum
; j
++) {
1221 redisDb
*db
= server
.db
+j
;
1223 /* Continue to expire if at the end of the cycle more than 25%
1224 * of the keys were expired. */
1226 long num
= dictSize(db
->expires
);
1227 time_t now
= time(NULL
);
1230 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
1231 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
1236 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
1237 t
= (time_t) dictGetEntryVal(de
);
1239 deleteKey(db
,dictGetEntryKey(de
));
1243 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
1246 /* Swap a few keys on disk if we are over the memory limit and VM
1247 * is enbled. Try to free objects from the free list first. */
1248 if (vmCanSwapOut()) {
1249 while (server
.vm_enabled
&& zmalloc_used_memory() >
1250 server
.vm_max_memory
)
1252 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
1253 if (vmSwapOneObjectThreaded() == REDIS_ERR
) {
1254 if ((loops
% 30) == 0 && zmalloc_used_memory() >
1255 (server
.vm_max_memory
+server
.vm_max_memory
/10)) {
1256 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
1259 /* Note that we freed just one object, because anyway when
1260 * the I/O thread in charge to swap this object out will
1261 * do its work, the handler of completed jobs will try to swap
1262 * more objects if we are out of memory. */
1267 /* Check if we should connect to a MASTER */
1268 if (server
.replstate
== REDIS_REPL_CONNECT
) {
1269 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
1270 if (syncWithMaster() == REDIS_OK
) {
1271 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
1277 static void createSharedObjects(void) {
1278 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
1279 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
1280 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
1281 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
1282 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
1283 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
1284 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
1285 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
1286 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
1287 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
1288 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
1289 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
1290 "-ERR Operation against a key holding the wrong kind of value\r\n"));
1291 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
1292 "-ERR no such key\r\n"));
1293 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
1294 "-ERR syntax error\r\n"));
1295 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
1296 "-ERR source and destination objects are the same\r\n"));
1297 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
1298 "-ERR index out of range\r\n"));
1299 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
1300 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
1301 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
1302 shared
.select0
= createStringObject("select 0\r\n",10);
1303 shared
.select1
= createStringObject("select 1\r\n",10);
1304 shared
.select2
= createStringObject("select 2\r\n",10);
1305 shared
.select3
= createStringObject("select 3\r\n",10);
1306 shared
.select4
= createStringObject("select 4\r\n",10);
1307 shared
.select5
= createStringObject("select 5\r\n",10);
1308 shared
.select6
= createStringObject("select 6\r\n",10);
1309 shared
.select7
= createStringObject("select 7\r\n",10);
1310 shared
.select8
= createStringObject("select 8\r\n",10);
1311 shared
.select9
= createStringObject("select 9\r\n",10);
1314 static void appendServerSaveParams(time_t seconds
, int changes
) {
1315 server
.saveparams
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1));
1316 server
.saveparams
[server
.saveparamslen
].seconds
= seconds
;
1317 server
.saveparams
[server
.saveparamslen
].changes
= changes
;
1318 server
.saveparamslen
++;
1321 static void resetServerSaveParams() {
1322 zfree(server
.saveparams
);
1323 server
.saveparams
= NULL
;
1324 server
.saveparamslen
= 0;
1327 static void initServerConfig() {
1328 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
1329 server
.port
= REDIS_SERVERPORT
;
1330 server
.verbosity
= REDIS_VERBOSE
;
1331 server
.maxidletime
= REDIS_MAXIDLETIME
;
1332 server
.saveparams
= NULL
;
1333 server
.logfile
= NULL
; /* NULL = log on standard output */
1334 server
.bindaddr
= NULL
;
1335 server
.glueoutputbuf
= 1;
1336 server
.daemonize
= 0;
1337 server
.appendonly
= 0;
1338 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1339 server
.lastfsync
= time(NULL
);
1340 server
.appendfd
= -1;
1341 server
.appendseldb
= -1; /* Make sure the first time will not match */
1342 server
.pidfile
= "/var/run/redis.pid";
1343 server
.dbfilename
= "dump.rdb";
1344 server
.appendfilename
= "appendonly.aof";
1345 server
.requirepass
= NULL
;
1346 server
.shareobjects
= 0;
1347 server
.rdbcompression
= 1;
1348 server
.sharingpoolsize
= 1024;
1349 server
.maxclients
= 0;
1350 server
.blockedclients
= 0;
1351 server
.maxmemory
= 0;
1352 server
.vm_enabled
= 0;
1353 server
.vm_page_size
= 256; /* 256 bytes per page */
1354 server
.vm_pages
= 1024*1024*100; /* 104 millions of pages */
1355 server
.vm_max_memory
= 1024LL*1024*1024*1; /* 1 GB of RAM */
1356 server
.vm_max_threads
= 4;
1358 resetServerSaveParams();
1360 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1361 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1362 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1363 /* Replication related */
1365 server
.masterauth
= NULL
;
1366 server
.masterhost
= NULL
;
1367 server
.masterport
= 6379;
1368 server
.master
= NULL
;
1369 server
.replstate
= REDIS_REPL_NONE
;
1371 /* Double constants initialization */
1373 R_PosInf
= 1.0/R_Zero
;
1374 R_NegInf
= -1.0/R_Zero
;
1375 R_Nan
= R_Zero
/R_Zero
;
1378 static void initServer() {
1381 signal(SIGHUP
, SIG_IGN
);
1382 signal(SIGPIPE
, SIG_IGN
);
1383 setupSigSegvAction();
1385 server
.devnull
= fopen("/dev/null","w");
1386 if (server
.devnull
== NULL
) {
1387 redisLog(REDIS_WARNING
, "Can't open /dev/null: %s", server
.neterr
);
1390 server
.clients
= listCreate();
1391 server
.slaves
= listCreate();
1392 server
.monitors
= listCreate();
1393 server
.objfreelist
= listCreate();
1394 createSharedObjects();
1395 server
.el
= aeCreateEventLoop();
1396 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
1397 server
.sharingpool
= dictCreate(&setDictType
,NULL
);
1398 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
1399 if (server
.fd
== -1) {
1400 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
1403 for (j
= 0; j
< server
.dbnum
; j
++) {
1404 server
.db
[j
].dict
= dictCreate(&hashDictType
,NULL
);
1405 server
.db
[j
].expires
= dictCreate(&setDictType
,NULL
);
1406 server
.db
[j
].blockingkeys
= dictCreate(&keylistDictType
,NULL
);
1407 server
.db
[j
].id
= j
;
1409 server
.cronloops
= 0;
1410 server
.bgsavechildpid
= -1;
1411 server
.bgrewritechildpid
= -1;
1412 server
.bgrewritebuf
= sdsempty();
1413 server
.lastsave
= time(NULL
);
1415 server
.usedmemory
= 0;
1416 server
.stat_numcommands
= 0;
1417 server
.stat_numconnections
= 0;
1418 server
.stat_starttime
= time(NULL
);
1419 server
.unixtime
= time(NULL
);
1420 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
1421 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
1422 acceptHandler
, NULL
) == AE_ERR
) oom("creating file event");
1424 if (server
.appendonly
) {
1425 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
1426 if (server
.appendfd
== -1) {
1427 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
1433 if (server
.vm_enabled
) vmInit();
1436 /* Empty the whole database */
1437 static long long emptyDb() {
1439 long long removed
= 0;
1441 for (j
= 0; j
< server
.dbnum
; j
++) {
1442 removed
+= dictSize(server
.db
[j
].dict
);
1443 dictEmpty(server
.db
[j
].dict
);
1444 dictEmpty(server
.db
[j
].expires
);
1449 static int yesnotoi(char *s
) {
1450 if (!strcasecmp(s
,"yes")) return 1;
1451 else if (!strcasecmp(s
,"no")) return 0;
1455 /* I agree, this is a very rudimental way to load a configuration...
1456 will improve later if the config gets more complex */
1457 static void loadServerConfig(char *filename
) {
1459 char buf
[REDIS_CONFIGLINE_MAX
+1], *err
= NULL
;
1463 if (filename
[0] == '-' && filename
[1] == '\0')
1466 if ((fp
= fopen(filename
,"r")) == NULL
) {
1467 redisLog(REDIS_WARNING
,"Fatal error, can't open config file");
1472 while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) {
1478 line
= sdstrim(line
," \t\r\n");
1480 /* Skip comments and blank lines*/
1481 if (line
[0] == '#' || line
[0] == '\0') {
1486 /* Split into arguments */
1487 argv
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
);
1488 sdstolower(argv
[0]);
1490 /* Execute config directives */
1491 if (!strcasecmp(argv
[0],"timeout") && argc
== 2) {
1492 server
.maxidletime
= atoi(argv
[1]);
1493 if (server
.maxidletime
< 0) {
1494 err
= "Invalid timeout value"; goto loaderr
;
1496 } else if (!strcasecmp(argv
[0],"port") && argc
== 2) {
1497 server
.port
= atoi(argv
[1]);
1498 if (server
.port
< 1 || server
.port
> 65535) {
1499 err
= "Invalid port"; goto loaderr
;
1501 } else if (!strcasecmp(argv
[0],"bind") && argc
== 2) {
1502 server
.bindaddr
= zstrdup(argv
[1]);
1503 } else if (!strcasecmp(argv
[0],"save") && argc
== 3) {
1504 int seconds
= atoi(argv
[1]);
1505 int changes
= atoi(argv
[2]);
1506 if (seconds
< 1 || changes
< 0) {
1507 err
= "Invalid save parameters"; goto loaderr
;
1509 appendServerSaveParams(seconds
,changes
);
1510 } else if (!strcasecmp(argv
[0],"dir") && argc
== 2) {
1511 if (chdir(argv
[1]) == -1) {
1512 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s",
1513 argv
[1], strerror(errno
));
1516 } else if (!strcasecmp(argv
[0],"loglevel") && argc
== 2) {
1517 if (!strcasecmp(argv
[1],"debug")) server
.verbosity
= REDIS_DEBUG
;
1518 else if (!strcasecmp(argv
[1],"verbose")) server
.verbosity
= REDIS_VERBOSE
;
1519 else if (!strcasecmp(argv
[1],"notice")) server
.verbosity
= REDIS_NOTICE
;
1520 else if (!strcasecmp(argv
[1],"warning")) server
.verbosity
= REDIS_WARNING
;
1522 err
= "Invalid log level. Must be one of debug, notice, warning";
1525 } else if (!strcasecmp(argv
[0],"logfile") && argc
== 2) {
1528 server
.logfile
= zstrdup(argv
[1]);
1529 if (!strcasecmp(server
.logfile
,"stdout")) {
1530 zfree(server
.logfile
);
1531 server
.logfile
= NULL
;
1533 if (server
.logfile
) {
1534 /* Test if we are able to open the file. The server will not
1535 * be able to abort just for this problem later... */
1536 logfp
= fopen(server
.logfile
,"a");
1537 if (logfp
== NULL
) {
1538 err
= sdscatprintf(sdsempty(),
1539 "Can't open the log file: %s", strerror(errno
));
1544 } else if (!strcasecmp(argv
[0],"databases") && argc
== 2) {
1545 server
.dbnum
= atoi(argv
[1]);
1546 if (server
.dbnum
< 1) {
1547 err
= "Invalid number of databases"; goto loaderr
;
1549 } else if (!strcasecmp(argv
[0],"maxclients") && argc
== 2) {
1550 server
.maxclients
= atoi(argv
[1]);
1551 } else if (!strcasecmp(argv
[0],"maxmemory") && argc
== 2) {
1552 server
.maxmemory
= strtoll(argv
[1], NULL
, 10);
1553 } else if (!strcasecmp(argv
[0],"slaveof") && argc
== 3) {
1554 server
.masterhost
= sdsnew(argv
[1]);
1555 server
.masterport
= atoi(argv
[2]);
1556 server
.replstate
= REDIS_REPL_CONNECT
;
1557 } else if (!strcasecmp(argv
[0],"masterauth") && argc
== 2) {
1558 server
.masterauth
= zstrdup(argv
[1]);
1559 } else if (!strcasecmp(argv
[0],"glueoutputbuf") && argc
== 2) {
1560 if ((server
.glueoutputbuf
= yesnotoi(argv
[1])) == -1) {
1561 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1563 } else if (!strcasecmp(argv
[0],"shareobjects") && argc
== 2) {
1564 if ((server
.shareobjects
= yesnotoi(argv
[1])) == -1) {
1565 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1567 } else if (!strcasecmp(argv
[0],"rdbcompression") && argc
== 2) {
1568 if ((server
.rdbcompression
= yesnotoi(argv
[1])) == -1) {
1569 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1571 } else if (!strcasecmp(argv
[0],"shareobjectspoolsize") && argc
== 2) {
1572 server
.sharingpoolsize
= atoi(argv
[1]);
1573 if (server
.sharingpoolsize
< 1) {
1574 err
= "invalid object sharing pool size"; goto loaderr
;
1576 } else if (!strcasecmp(argv
[0],"daemonize") && argc
== 2) {
1577 if ((server
.daemonize
= yesnotoi(argv
[1])) == -1) {
1578 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1580 } else if (!strcasecmp(argv
[0],"appendonly") && argc
== 2) {
1581 if ((server
.appendonly
= yesnotoi(argv
[1])) == -1) {
1582 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1584 } else if (!strcasecmp(argv
[0],"appendfsync") && argc
== 2) {
1585 if (!strcasecmp(argv
[1],"no")) {
1586 server
.appendfsync
= APPENDFSYNC_NO
;
1587 } else if (!strcasecmp(argv
[1],"always")) {
1588 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1589 } else if (!strcasecmp(argv
[1],"everysec")) {
1590 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
1592 err
= "argument must be 'no', 'always' or 'everysec'";
1595 } else if (!strcasecmp(argv
[0],"requirepass") && argc
== 2) {
1596 server
.requirepass
= zstrdup(argv
[1]);
1597 } else if (!strcasecmp(argv
[0],"pidfile") && argc
== 2) {
1598 server
.pidfile
= zstrdup(argv
[1]);
1599 } else if (!strcasecmp(argv
[0],"dbfilename") && argc
== 2) {
1600 server
.dbfilename
= zstrdup(argv
[1]);
1601 } else if (!strcasecmp(argv
[0],"vm-enabled") && argc
== 2) {
1602 if ((server
.vm_enabled
= yesnotoi(argv
[1])) == -1) {
1603 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1605 } else if (!strcasecmp(argv
[0],"vm-max-memory") && argc
== 2) {
1606 server
.vm_max_memory
= strtoll(argv
[1], NULL
, 10);
1607 } else if (!strcasecmp(argv
[0],"vm-page-size") && argc
== 2) {
1608 server
.vm_page_size
= strtoll(argv
[1], NULL
, 10);
1609 } else if (!strcasecmp(argv
[0],"vm-pages") && argc
== 2) {
1610 server
.vm_pages
= strtoll(argv
[1], NULL
, 10);
1611 } else if (!strcasecmp(argv
[0],"vm-max-threads") && argc
== 2) {
1612 server
.vm_max_threads
= strtoll(argv
[1], NULL
, 10);
1614 err
= "Bad directive or wrong number of arguments"; goto loaderr
;
1616 for (j
= 0; j
< argc
; j
++)
1621 if (fp
!= stdin
) fclose(fp
);
1625 fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n");
1626 fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
);
1627 fprintf(stderr
, ">>> '%s'\n", line
);
1628 fprintf(stderr
, "%s\n", err
);
1632 static void freeClientArgv(redisClient
*c
) {
1635 for (j
= 0; j
< c
->argc
; j
++)
1636 decrRefCount(c
->argv
[j
]);
1637 for (j
= 0; j
< c
->mbargc
; j
++)
1638 decrRefCount(c
->mbargv
[j
]);
1643 static void freeClient(redisClient
*c
) {
1646 /* Note that if the client we are freeing is blocked into a blocking
1647 * call, we have to set querybuf to NULL *before* to call unblockClient()
1648 * to avoid processInputBuffer() will get called. Also it is important
1649 * to remove the file events after this, because this call adds
1650 * the READABLE event. */
1651 sdsfree(c
->querybuf
);
1653 if (c
->flags
& REDIS_BLOCKED
)
1656 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
1657 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1658 listRelease(c
->reply
);
1661 /* Remove from the list of clients */
1662 ln
= listSearchKey(server
.clients
,c
);
1663 redisAssert(ln
!= NULL
);
1664 listDelNode(server
.clients
,ln
);
1665 /* Remove from the list of clients waiting for VM operations */
1666 if (server
.vm_enabled
&& listLength(c
->io_keys
)) {
1667 ln
= listSearchKey(server
.io_clients
,c
);
1668 if (ln
) listDelNode(server
.io_clients
,ln
);
1669 listRelease(c
->io_keys
);
1671 listRelease(c
->io_keys
);
1673 if (c
->flags
& REDIS_SLAVE
) {
1674 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
1676 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
1677 ln
= listSearchKey(l
,c
);
1678 redisAssert(ln
!= NULL
);
1681 if (c
->flags
& REDIS_MASTER
) {
1682 server
.master
= NULL
;
1683 server
.replstate
= REDIS_REPL_CONNECT
;
1687 freeClientMultiState(c
);
1691 #define GLUEREPLY_UP_TO (1024)
1692 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
1694 char buf
[GLUEREPLY_UP_TO
];
1698 listRewind(c
->reply
);
1699 while((ln
= listYield(c
->reply
))) {
1703 objlen
= sdslen(o
->ptr
);
1704 if (copylen
+ objlen
<= GLUEREPLY_UP_TO
) {
1705 memcpy(buf
+copylen
,o
->ptr
,objlen
);
1707 listDelNode(c
->reply
,ln
);
1709 if (copylen
== 0) return;
1713 /* Now the output buffer is empty, add the new single element */
1714 o
= createObject(REDIS_STRING
,sdsnewlen(buf
,copylen
));
1715 listAddNodeHead(c
->reply
,o
);
1718 static void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1719 redisClient
*c
= privdata
;
1720 int nwritten
= 0, totwritten
= 0, objlen
;
1723 REDIS_NOTUSED(mask
);
1725 /* Use writev() if we have enough buffers to send */
1726 if (!server
.glueoutputbuf
&&
1727 listLength(c
->reply
) > REDIS_WRITEV_THRESHOLD
&&
1728 !(c
->flags
& REDIS_MASTER
))
1730 sendReplyToClientWritev(el
, fd
, privdata
, mask
);
1734 while(listLength(c
->reply
)) {
1735 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
1736 glueReplyBuffersIfNeeded(c
);
1738 o
= listNodeValue(listFirst(c
->reply
));
1739 objlen
= sdslen(o
->ptr
);
1742 listDelNode(c
->reply
,listFirst(c
->reply
));
1746 if (c
->flags
& REDIS_MASTER
) {
1747 /* Don't reply to a master */
1748 nwritten
= objlen
- c
->sentlen
;
1750 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen
- c
->sentlen
);
1751 if (nwritten
<= 0) break;
1753 c
->sentlen
+= nwritten
;
1754 totwritten
+= nwritten
;
1755 /* If we fully sent the object on head go to the next one */
1756 if (c
->sentlen
== objlen
) {
1757 listDelNode(c
->reply
,listFirst(c
->reply
));
1760 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
1761 * bytes, in a single threaded server it's a good idea to serve
1762 * other clients as well, even if a very large request comes from
1763 * super fast link that is always able to accept data (in real world
1764 * scenario think about 'KEYS *' against the loopback interfae) */
1765 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
) break;
1767 if (nwritten
== -1) {
1768 if (errno
== EAGAIN
) {
1771 redisLog(REDIS_VERBOSE
,
1772 "Error writing to client: %s", strerror(errno
));
1777 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
1778 if (listLength(c
->reply
) == 0) {
1780 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1784 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
)
1786 redisClient
*c
= privdata
;
1787 int nwritten
= 0, totwritten
= 0, objlen
, willwrite
;
1789 struct iovec iov
[REDIS_WRITEV_IOVEC_COUNT
];
1790 int offset
, ion
= 0;
1792 REDIS_NOTUSED(mask
);
1795 while (listLength(c
->reply
)) {
1796 offset
= c
->sentlen
;
1800 /* fill-in the iov[] array */
1801 for(node
= listFirst(c
->reply
); node
; node
= listNextNode(node
)) {
1802 o
= listNodeValue(node
);
1803 objlen
= sdslen(o
->ptr
);
1805 if (totwritten
+ objlen
- offset
> REDIS_MAX_WRITE_PER_EVENT
)
1808 if(ion
== REDIS_WRITEV_IOVEC_COUNT
)
1809 break; /* no more iovecs */
1811 iov
[ion
].iov_base
= ((char*)o
->ptr
) + offset
;
1812 iov
[ion
].iov_len
= objlen
- offset
;
1813 willwrite
+= objlen
- offset
;
1814 offset
= 0; /* just for the first item */
1821 /* write all collected blocks at once */
1822 if((nwritten
= writev(fd
, iov
, ion
)) < 0) {
1823 if (errno
!= EAGAIN
) {
1824 redisLog(REDIS_VERBOSE
,
1825 "Error writing to client: %s", strerror(errno
));
1832 totwritten
+= nwritten
;
1833 offset
= c
->sentlen
;
1835 /* remove written robjs from c->reply */
1836 while (nwritten
&& listLength(c
->reply
)) {
1837 o
= listNodeValue(listFirst(c
->reply
));
1838 objlen
= sdslen(o
->ptr
);
1840 if(nwritten
>= objlen
- offset
) {
1841 listDelNode(c
->reply
, listFirst(c
->reply
));
1842 nwritten
-= objlen
- offset
;
1846 c
->sentlen
+= nwritten
;
1854 c
->lastinteraction
= time(NULL
);
1856 if (listLength(c
->reply
) == 0) {
1858 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1862 static struct redisCommand
*lookupCommand(char *name
) {
1864 while(cmdTable
[j
].name
!= NULL
) {
1865 if (!strcasecmp(name
,cmdTable
[j
].name
)) return &cmdTable
[j
];
1871 /* resetClient prepare the client to process the next command */
1872 static void resetClient(redisClient
*c
) {
1878 /* Call() is the core of Redis execution of a command */
1879 static void call(redisClient
*c
, struct redisCommand
*cmd
) {
1882 dirty
= server
.dirty
;
1884 if (server
.appendonly
&& server
.dirty
-dirty
)
1885 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1886 if (server
.dirty
-dirty
&& listLength(server
.slaves
))
1887 replicationFeedSlaves(server
.slaves
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1888 if (listLength(server
.monitors
))
1889 replicationFeedSlaves(server
.monitors
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1890 server
.stat_numcommands
++;
1893 /* If this function gets called we already read a whole
1894 * command, argments are in the client argv/argc fields.
1895 * processCommand() execute the command or prepare the
1896 * server for a bulk read from the client.
1898 * If 1 is returned the client is still alive and valid and
1899 * and other operations can be performed by the caller. Otherwise
1900 * if 0 is returned the client was destroied (i.e. after QUIT). */
1901 static int processCommand(redisClient
*c
) {
1902 struct redisCommand
*cmd
;
1904 /* Free some memory if needed (maxmemory setting) */
1905 if (server
.maxmemory
) freeMemoryIfNeeded();
1907 /* Handle the multi bulk command type. This is an alternative protocol
1908 * supported by Redis in order to receive commands that are composed of
1909 * multiple binary-safe "bulk" arguments. The latency of processing is
1910 * a bit higher but this allows things like multi-sets, so if this
1911 * protocol is used only for MSET and similar commands this is a big win. */
1912 if (c
->multibulk
== 0 && c
->argc
== 1 && ((char*)(c
->argv
[0]->ptr
))[0] == '*') {
1913 c
->multibulk
= atoi(((char*)c
->argv
[0]->ptr
)+1);
1914 if (c
->multibulk
<= 0) {
1918 decrRefCount(c
->argv
[c
->argc
-1]);
1922 } else if (c
->multibulk
) {
1923 if (c
->bulklen
== -1) {
1924 if (((char*)c
->argv
[0]->ptr
)[0] != '$') {
1925 addReplySds(c
,sdsnew("-ERR multi bulk protocol error\r\n"));
1929 int bulklen
= atoi(((char*)c
->argv
[0]->ptr
)+1);
1930 decrRefCount(c
->argv
[0]);
1931 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
1933 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
1938 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
1942 c
->mbargv
= zrealloc(c
->mbargv
,(sizeof(robj
*))*(c
->mbargc
+1));
1943 c
->mbargv
[c
->mbargc
] = c
->argv
[0];
1947 if (c
->multibulk
== 0) {
1951 /* Here we need to swap the multi-bulk argc/argv with the
1952 * normal argc/argv of the client structure. */
1954 c
->argv
= c
->mbargv
;
1955 c
->mbargv
= auxargv
;
1958 c
->argc
= c
->mbargc
;
1959 c
->mbargc
= auxargc
;
1961 /* We need to set bulklen to something different than -1
1962 * in order for the code below to process the command without
1963 * to try to read the last argument of a bulk command as
1964 * a special argument. */
1966 /* continue below and process the command */
1973 /* -- end of multi bulk commands processing -- */
1975 /* The QUIT command is handled as a special case. Normal command
1976 * procs are unable to close the client connection safely */
1977 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
1981 cmd
= lookupCommand(c
->argv
[0]->ptr
);
1984 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
1985 (char*)c
->argv
[0]->ptr
));
1988 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
1989 (c
->argc
< -cmd
->arity
)) {
1991 sdscatprintf(sdsempty(),
1992 "-ERR wrong number of arguments for '%s' command\r\n",
1996 } else if (server
.maxmemory
&& cmd
->flags
& REDIS_CMD_DENYOOM
&& zmalloc_used_memory() > server
.maxmemory
) {
1997 addReplySds(c
,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
2000 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
2001 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
2003 decrRefCount(c
->argv
[c
->argc
-1]);
2004 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
2006 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
2011 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
2012 /* It is possible that the bulk read is already in the
2013 * buffer. Check this condition and handle it accordingly.
2014 * This is just a fast path, alternative to call processInputBuffer().
2015 * It's a good idea since the code is small and this condition
2016 * happens most of the times. */
2017 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
2018 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2020 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2025 /* Let's try to share objects on the command arguments vector */
2026 if (server
.shareobjects
) {
2028 for(j
= 1; j
< c
->argc
; j
++)
2029 c
->argv
[j
] = tryObjectSharing(c
->argv
[j
]);
2031 /* Let's try to encode the bulk object to save space. */
2032 if (cmd
->flags
& REDIS_CMD_BULK
)
2033 tryObjectEncoding(c
->argv
[c
->argc
-1]);
2035 /* Check if the user is authenticated */
2036 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
2037 addReplySds(c
,sdsnew("-ERR operation not permitted\r\n"));
2042 /* Exec the command */
2043 if (c
->flags
& REDIS_MULTI
&& cmd
->proc
!= execCommand
) {
2044 queueMultiCommand(c
,cmd
);
2045 addReply(c
,shared
.queued
);
2050 /* Prepare the client for the next command */
2051 if (c
->flags
& REDIS_CLOSE
) {
2059 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
2063 /* (args*2)+1 is enough room for args, spaces, newlines */
2064 robj
*static_outv
[REDIS_STATIC_ARGS
*2+1];
2066 if (argc
<= REDIS_STATIC_ARGS
) {
2069 outv
= zmalloc(sizeof(robj
*)*(argc
*2+1));
2072 for (j
= 0; j
< argc
; j
++) {
2073 if (j
!= 0) outv
[outc
++] = shared
.space
;
2074 if ((cmd
->flags
& REDIS_CMD_BULK
) && j
== argc
-1) {
2077 lenobj
= createObject(REDIS_STRING
,
2078 sdscatprintf(sdsempty(),"%lu\r\n",
2079 (unsigned long) stringObjectLen(argv
[j
])));
2080 lenobj
->refcount
= 0;
2081 outv
[outc
++] = lenobj
;
2083 outv
[outc
++] = argv
[j
];
2085 outv
[outc
++] = shared
.crlf
;
2087 /* Increment all the refcounts at start and decrement at end in order to
2088 * be sure to free objects if there is no slave in a replication state
2089 * able to be feed with commands */
2090 for (j
= 0; j
< outc
; j
++) incrRefCount(outv
[j
]);
2092 while((ln
= listYield(slaves
))) {
2093 redisClient
*slave
= ln
->value
;
2095 /* Don't feed slaves that are still waiting for BGSAVE to start */
2096 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) continue;
2098 /* Feed all the other slaves, MONITORs and so on */
2099 if (slave
->slaveseldb
!= dictid
) {
2103 case 0: selectcmd
= shared
.select0
; break;
2104 case 1: selectcmd
= shared
.select1
; break;
2105 case 2: selectcmd
= shared
.select2
; break;
2106 case 3: selectcmd
= shared
.select3
; break;
2107 case 4: selectcmd
= shared
.select4
; break;
2108 case 5: selectcmd
= shared
.select5
; break;
2109 case 6: selectcmd
= shared
.select6
; break;
2110 case 7: selectcmd
= shared
.select7
; break;
2111 case 8: selectcmd
= shared
.select8
; break;
2112 case 9: selectcmd
= shared
.select9
; break;
2114 selectcmd
= createObject(REDIS_STRING
,
2115 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
2116 selectcmd
->refcount
= 0;
2119 addReply(slave
,selectcmd
);
2120 slave
->slaveseldb
= dictid
;
2122 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
2124 for (j
= 0; j
< outc
; j
++) decrRefCount(outv
[j
]);
2125 if (outv
!= static_outv
) zfree(outv
);
2128 static void processInputBuffer(redisClient
*c
) {
2130 /* Before to process the input buffer, make sure the client is not
2131 * waitig for a blocking operation such as BLPOP. Note that the first
2132 * iteration the client is never blocked, otherwise the processInputBuffer
2133 * would not be called at all, but after the execution of the first commands
2134 * in the input buffer the client may be blocked, and the "goto again"
2135 * will try to reiterate. The following line will make it return asap. */
2136 if (c
->flags
& REDIS_BLOCKED
|| c
->flags
& REDIS_IO_WAIT
) return;
2137 if (c
->bulklen
== -1) {
2138 /* Read the first line of the query */
2139 char *p
= strchr(c
->querybuf
,'\n');
2146 query
= c
->querybuf
;
2147 c
->querybuf
= sdsempty();
2148 querylen
= 1+(p
-(query
));
2149 if (sdslen(query
) > querylen
) {
2150 /* leave data after the first line of the query in the buffer */
2151 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
2153 *p
= '\0'; /* remove "\n" */
2154 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
2155 sdsupdatelen(query
);
2157 /* Now we can split the query in arguments */
2158 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
2161 if (c
->argv
) zfree(c
->argv
);
2162 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
2164 for (j
= 0; j
< argc
; j
++) {
2165 if (sdslen(argv
[j
])) {
2166 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
2174 /* Execute the command. If the client is still valid
2175 * after processCommand() return and there is something
2176 * on the query buffer try to process the next command. */
2177 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2179 /* Nothing to process, argc == 0. Just process the query
2180 * buffer if it's not empty or return to the caller */
2181 if (sdslen(c
->querybuf
)) goto again
;
2184 } else if (sdslen(c
->querybuf
) >= REDIS_REQUEST_MAX_SIZE
) {
2185 redisLog(REDIS_VERBOSE
, "Client protocol error");
2190 /* Bulk read handling. Note that if we are at this point
2191 the client already sent a command terminated with a newline,
2192 we are reading the bulk data that is actually the last
2193 argument of the command. */
2194 int qbl
= sdslen(c
->querybuf
);
2196 if (c
->bulklen
<= qbl
) {
2197 /* Copy everything but the final CRLF as final argument */
2198 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2200 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2201 /* Process the command. If the client is still valid after
2202 * the processing and there is more data in the buffer
2203 * try to parse it. */
2204 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2210 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2211 redisClient
*c
= (redisClient
*) privdata
;
2212 char buf
[REDIS_IOBUF_LEN
];
2215 REDIS_NOTUSED(mask
);
2217 nread
= read(fd
, buf
, REDIS_IOBUF_LEN
);
2219 if (errno
== EAGAIN
) {
2222 redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
));
2226 } else if (nread
== 0) {
2227 redisLog(REDIS_VERBOSE
, "Client closed connection");
2232 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
2233 c
->lastinteraction
= time(NULL
);
2237 processInputBuffer(c
);
2240 static int selectDb(redisClient
*c
, int id
) {
2241 if (id
< 0 || id
>= server
.dbnum
)
2243 c
->db
= &server
.db
[id
];
2247 static void *dupClientReplyValue(void *o
) {
2248 incrRefCount((robj
*)o
);
2252 static redisClient
*createClient(int fd
) {
2253 redisClient
*c
= zmalloc(sizeof(*c
));
2255 anetNonBlock(NULL
,fd
);
2256 anetTcpNoDelay(NULL
,fd
);
2257 if (!c
) return NULL
;
2260 c
->querybuf
= sdsempty();
2269 c
->lastinteraction
= time(NULL
);
2270 c
->authenticated
= 0;
2271 c
->replstate
= REDIS_REPL_NONE
;
2272 c
->reply
= listCreate();
2273 listSetFreeMethod(c
->reply
,decrRefCount
);
2274 listSetDupMethod(c
->reply
,dupClientReplyValue
);
2275 c
->blockingkeys
= NULL
;
2276 c
->blockingkeysnum
= 0;
2277 c
->io_keys
= listCreate();
2278 listSetFreeMethod(c
->io_keys
,decrRefCount
);
2279 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
2280 readQueryFromClient
, c
) == AE_ERR
) {
2284 listAddNodeTail(server
.clients
,c
);
2285 initClientMultiState(c
);
2289 static void addReply(redisClient
*c
, robj
*obj
) {
2290 if (listLength(c
->reply
) == 0 &&
2291 (c
->replstate
== REDIS_REPL_NONE
||
2292 c
->replstate
== REDIS_REPL_ONLINE
) &&
2293 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
2294 sendReplyToClient
, c
) == AE_ERR
) return;
2296 if (server
.vm_enabled
&& obj
->storage
!= REDIS_VM_MEMORY
) {
2297 obj
= dupStringObject(obj
);
2298 obj
->refcount
= 0; /* getDecodedObject() will increment the refcount */
2300 listAddNodeTail(c
->reply
,getDecodedObject(obj
));
2303 static void addReplySds(redisClient
*c
, sds s
) {
2304 robj
*o
= createObject(REDIS_STRING
,s
);
2309 static void addReplyDouble(redisClient
*c
, double d
) {
2312 snprintf(buf
,sizeof(buf
),"%.17g",d
);
2313 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
2314 (unsigned long) strlen(buf
),buf
));
2317 static void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
2320 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
2321 len
= sdslen(obj
->ptr
);
2323 long n
= (long)obj
->ptr
;
2325 /* Compute how many bytes will take this integer as a radix 10 string */
2331 while((n
= n
/10) != 0) {
2335 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",(unsigned long)len
));
2338 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2343 REDIS_NOTUSED(mask
);
2344 REDIS_NOTUSED(privdata
);
2346 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
2347 if (cfd
== AE_ERR
) {
2348 redisLog(REDIS_VERBOSE
,"Accepting client connection: %s", server
.neterr
);
2351 redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
);
2352 if ((c
= createClient(cfd
)) == NULL
) {
2353 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
2354 close(cfd
); /* May be already closed, just ingore errors */
2357 /* If maxclient directive is set and this is one client more... close the
2358 * connection. Note that we create the client instead to check before
2359 * for this condition, since now the socket is already set in nonblocking
2360 * mode and we can send an error for free using the Kernel I/O */
2361 if (server
.maxclients
&& listLength(server
.clients
) > server
.maxclients
) {
2362 char *err
= "-ERR max number of clients reached\r\n";
2364 /* That's a best effort error message, don't check write errors */
2365 if (write(c
->fd
,err
,strlen(err
)) == -1) {
2366 /* Nothing to do, Just to avoid the warning... */
2371 server
.stat_numconnections
++;
2374 /* ======================= Redis objects implementation ===================== */
2376 static robj
*createObject(int type
, void *ptr
) {
2379 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
2380 if (listLength(server
.objfreelist
)) {
2381 listNode
*head
= listFirst(server
.objfreelist
);
2382 o
= listNodeValue(head
);
2383 listDelNode(server
.objfreelist
,head
);
2384 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2386 if (server
.vm_enabled
) {
2387 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2388 o
= zmalloc(sizeof(*o
));
2390 o
= zmalloc(sizeof(*o
)-sizeof(struct redisObjectVM
));
2394 o
->encoding
= REDIS_ENCODING_RAW
;
2397 if (server
.vm_enabled
) {
2398 o
->vm
.atime
= server
.unixtime
;
2399 o
->storage
= REDIS_VM_MEMORY
;
2404 static robj
*createStringObject(char *ptr
, size_t len
) {
2405 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
2408 static robj
*dupStringObject(robj
*o
) {
2409 assert(o
->encoding
== REDIS_ENCODING_RAW
);
2410 return createStringObject(o
->ptr
,sdslen(o
->ptr
));
2413 static robj
*createListObject(void) {
2414 list
*l
= listCreate();
2416 listSetFreeMethod(l
,decrRefCount
);
2417 return createObject(REDIS_LIST
,l
);
2420 static robj
*createSetObject(void) {
2421 dict
*d
= dictCreate(&setDictType
,NULL
);
2422 return createObject(REDIS_SET
,d
);
2425 static robj
*createZsetObject(void) {
2426 zset
*zs
= zmalloc(sizeof(*zs
));
2428 zs
->dict
= dictCreate(&zsetDictType
,NULL
);
2429 zs
->zsl
= zslCreate();
2430 return createObject(REDIS_ZSET
,zs
);
2433 static void freeStringObject(robj
*o
) {
2434 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2439 static void freeListObject(robj
*o
) {
2440 listRelease((list
*) o
->ptr
);
2443 static void freeSetObject(robj
*o
) {
2444 dictRelease((dict
*) o
->ptr
);
2447 static void freeZsetObject(robj
*o
) {
2450 dictRelease(zs
->dict
);
2455 static void freeHashObject(robj
*o
) {
2456 dictRelease((dict
*) o
->ptr
);
2459 static void incrRefCount(robj
*o
) {
2460 redisAssert(!server
.vm_enabled
|| o
->storage
== REDIS_VM_MEMORY
);
2464 static void decrRefCount(void *obj
) {
2467 /* Object is swapped out, or in the process of being loaded. */
2468 if (server
.vm_enabled
&&
2469 (o
->storage
== REDIS_VM_SWAPPED
|| o
->storage
== REDIS_VM_LOADING
))
2471 if (o
->storage
== REDIS_VM_SWAPPED
|| o
->storage
== REDIS_VM_LOADING
) {
2472 redisAssert(o
->refcount
== 1);
2474 if (o
->storage
== REDIS_VM_LOADING
) vmCancelThreadedIOJob(obj
);
2475 redisAssert(o
->type
== REDIS_STRING
);
2476 freeStringObject(o
);
2477 vmMarkPagesFree(o
->vm
.page
,o
->vm
.usedpages
);
2478 pthread_mutex_lock(&server
.obj_freelist_mutex
);
2479 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2480 !listAddNodeHead(server
.objfreelist
,o
))
2482 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2483 server
.vm_stats_swapped_objects
--;
2486 /* Object is in memory, or in the process of being swapped out. */
2487 if (--(o
->refcount
) == 0) {
2488 if (server
.vm_enabled
&& o
->storage
== REDIS_VM_SWAPPING
)
2489 vmCancelThreadedIOJob(obj
);
2491 case REDIS_STRING
: freeStringObject(o
); break;
2492 case REDIS_LIST
: freeListObject(o
); break;
2493 case REDIS_SET
: freeSetObject(o
); break;
2494 case REDIS_ZSET
: freeZsetObject(o
); break;
2495 case REDIS_HASH
: freeHashObject(o
); break;
2496 default: redisAssert(0 != 0); break;
2498 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
2499 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2500 !listAddNodeHead(server
.objfreelist
,o
))
2502 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2506 static robj
*lookupKey(redisDb
*db
, robj
*key
) {
2507 dictEntry
*de
= dictFind(db
->dict
,key
);
2509 robj
*key
= dictGetEntryKey(de
);
2510 robj
*val
= dictGetEntryVal(de
);
2512 if (server
.vm_enabled
) {
2513 if (key
->storage
== REDIS_VM_MEMORY
||
2514 key
->storage
== REDIS_VM_SWAPPING
)
2516 /* If we were swapping the object out, stop it, this key
2518 if (key
->storage
== REDIS_VM_SWAPPING
)
2519 vmCancelThreadedIOJob(key
);
2520 /* Update the access time of the key for the aging algorithm. */
2521 key
->vm
.atime
= server
.unixtime
;
2523 /* Our value was swapped on disk. Bring it at home. */
2524 redisAssert(val
== NULL
);
2525 val
= vmLoadObject(key
);
2526 dictGetEntryVal(de
) = val
;
2535 static robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
2536 expireIfNeeded(db
,key
);
2537 return lookupKey(db
,key
);
2540 static robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
2541 deleteIfVolatile(db
,key
);
2542 return lookupKey(db
,key
);
2545 static int deleteKey(redisDb
*db
, robj
*key
) {
2548 /* We need to protect key from destruction: after the first dictDelete()
2549 * it may happen that 'key' is no longer valid if we don't increment
2550 * it's count. This may happen when we get the object reference directly
2551 * from the hash table with dictRandomKey() or dict iterators */
2553 if (dictSize(db
->expires
)) dictDelete(db
->expires
,key
);
2554 retval
= dictDelete(db
->dict
,key
);
2557 return retval
== DICT_OK
;
2560 /* Try to share an object against the shared objects pool */
2561 static robj
*tryObjectSharing(robj
*o
) {
2562 struct dictEntry
*de
;
2565 if (o
== NULL
|| server
.shareobjects
== 0) return o
;
2567 redisAssert(o
->type
== REDIS_STRING
);
2568 de
= dictFind(server
.sharingpool
,o
);
2570 robj
*shared
= dictGetEntryKey(de
);
2572 c
= ((unsigned long) dictGetEntryVal(de
))+1;
2573 dictGetEntryVal(de
) = (void*) c
;
2574 incrRefCount(shared
);
2578 /* Here we are using a stream algorihtm: Every time an object is
2579 * shared we increment its count, everytime there is a miss we
2580 * recrement the counter of a random object. If this object reaches
2581 * zero we remove the object and put the current object instead. */
2582 if (dictSize(server
.sharingpool
) >=
2583 server
.sharingpoolsize
) {
2584 de
= dictGetRandomKey(server
.sharingpool
);
2585 redisAssert(de
!= NULL
);
2586 c
= ((unsigned long) dictGetEntryVal(de
))-1;
2587 dictGetEntryVal(de
) = (void*) c
;
2589 dictDelete(server
.sharingpool
,de
->key
);
2592 c
= 0; /* If the pool is empty we want to add this object */
2597 retval
= dictAdd(server
.sharingpool
,o
,(void*)1);
2598 redisAssert(retval
== DICT_OK
);
2605 /* Check if the nul-terminated string 's' can be represented by a long
2606 * (that is, is a number that fits into long without any other space or
2607 * character before or after the digits).
2609 * If so, the function returns REDIS_OK and *longval is set to the value
2610 * of the number. Otherwise REDIS_ERR is returned */
2611 static int isStringRepresentableAsLong(sds s
, long *longval
) {
2612 char buf
[32], *endptr
;
2616 value
= strtol(s
, &endptr
, 10);
2617 if (endptr
[0] != '\0') return REDIS_ERR
;
2618 slen
= snprintf(buf
,32,"%ld",value
);
2620 /* If the number converted back into a string is not identical
2621 * then it's not possible to encode the string as integer */
2622 if (sdslen(s
) != (unsigned)slen
|| memcmp(buf
,s
,slen
)) return REDIS_ERR
;
2623 if (longval
) *longval
= value
;
2627 /* Try to encode a string object in order to save space */
2628 static int tryObjectEncoding(robj
*o
) {
2632 if (o
->encoding
!= REDIS_ENCODING_RAW
)
2633 return REDIS_ERR
; /* Already encoded */
2635 /* It's not save to encode shared objects: shared objects can be shared
2636 * everywhere in the "object space" of Redis. Encoded objects can only
2637 * appear as "values" (and not, for instance, as keys) */
2638 if (o
->refcount
> 1) return REDIS_ERR
;
2640 /* Currently we try to encode only strings */
2641 redisAssert(o
->type
== REDIS_STRING
);
2643 /* Check if we can represent this string as a long integer */
2644 if (isStringRepresentableAsLong(s
,&value
) == REDIS_ERR
) return REDIS_ERR
;
2646 /* Ok, this object can be encoded */
2647 o
->encoding
= REDIS_ENCODING_INT
;
2649 o
->ptr
= (void*) value
;
2653 /* Get a decoded version of an encoded object (returned as a new object).
2654 * If the object is already raw-encoded just increment the ref count. */
2655 static robj
*getDecodedObject(robj
*o
) {
2658 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2662 if (o
->type
== REDIS_STRING
&& o
->encoding
== REDIS_ENCODING_INT
) {
2665 snprintf(buf
,32,"%ld",(long)o
->ptr
);
2666 dec
= createStringObject(buf
,strlen(buf
));
2669 redisAssert(1 != 1);
2673 /* Compare two string objects via strcmp() or alike.
2674 * Note that the objects may be integer-encoded. In such a case we
2675 * use snprintf() to get a string representation of the numbers on the stack
2676 * and compare the strings, it's much faster than calling getDecodedObject().
2678 * Important note: if objects are not integer encoded, but binary-safe strings,
2679 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
2681 static int compareStringObjects(robj
*a
, robj
*b
) {
2682 redisAssert(a
->type
== REDIS_STRING
&& b
->type
== REDIS_STRING
);
2683 char bufa
[128], bufb
[128], *astr
, *bstr
;
2686 if (a
== b
) return 0;
2687 if (a
->encoding
!= REDIS_ENCODING_RAW
) {
2688 snprintf(bufa
,sizeof(bufa
),"%ld",(long) a
->ptr
);
2694 if (b
->encoding
!= REDIS_ENCODING_RAW
) {
2695 snprintf(bufb
,sizeof(bufb
),"%ld",(long) b
->ptr
);
2701 return bothsds
? sdscmp(astr
,bstr
) : strcmp(astr
,bstr
);
2704 static size_t stringObjectLen(robj
*o
) {
2705 redisAssert(o
->type
== REDIS_STRING
);
2706 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2707 return sdslen(o
->ptr
);
2711 return snprintf(buf
,32,"%ld",(long)o
->ptr
);
2715 /*============================ RDB saving/loading =========================== */
2717 static int rdbSaveType(FILE *fp
, unsigned char type
) {
2718 if (fwrite(&type
,1,1,fp
) == 0) return -1;
2722 static int rdbSaveTime(FILE *fp
, time_t t
) {
2723 int32_t t32
= (int32_t) t
;
2724 if (fwrite(&t32
,4,1,fp
) == 0) return -1;
2728 /* check rdbLoadLen() comments for more info */
2729 static int rdbSaveLen(FILE *fp
, uint32_t len
) {
2730 unsigned char buf
[2];
2733 /* Save a 6 bit len */
2734 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
2735 if (fwrite(buf
,1,1,fp
) == 0) return -1;
2736 } else if (len
< (1<<14)) {
2737 /* Save a 14 bit len */
2738 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
2740 if (fwrite(buf
,2,1,fp
) == 0) return -1;
2742 /* Save a 32 bit len */
2743 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
2744 if (fwrite(buf
,1,1,fp
) == 0) return -1;
2746 if (fwrite(&len
,4,1,fp
) == 0) return -1;
2751 /* String objects in the form "2391" "-100" without any space and with a
2752 * range of values that can fit in an 8, 16 or 32 bit signed value can be
2753 * encoded as integers to save space */
2754 static int rdbTryIntegerEncoding(sds s
, unsigned char *enc
) {
2756 char *endptr
, buf
[32];
2758 /* Check if it's possible to encode this value as a number */
2759 value
= strtoll(s
, &endptr
, 10);
2760 if (endptr
[0] != '\0') return 0;
2761 snprintf(buf
,32,"%lld",value
);
2763 /* If the number converted back into a string is not identical
2764 * then it's not possible to encode the string as integer */
2765 if (strlen(buf
) != sdslen(s
) || memcmp(buf
,s
,sdslen(s
))) return 0;
2767 /* Finally check if it fits in our ranges */
2768 if (value
>= -(1<<7) && value
<= (1<<7)-1) {
2769 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT8
;
2770 enc
[1] = value
&0xFF;
2772 } else if (value
>= -(1<<15) && value
<= (1<<15)-1) {
2773 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
;
2774 enc
[1] = value
&0xFF;
2775 enc
[2] = (value
>>8)&0xFF;
2777 } else if (value
>= -((long long)1<<31) && value
<= ((long long)1<<31)-1) {
2778 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT32
;
2779 enc
[1] = value
&0xFF;
2780 enc
[2] = (value
>>8)&0xFF;
2781 enc
[3] = (value
>>16)&0xFF;
2782 enc
[4] = (value
>>24)&0xFF;
2789 static int rdbSaveLzfStringObject(FILE *fp
, robj
*obj
) {
2790 unsigned int comprlen
, outlen
;
2794 /* We require at least four bytes compression for this to be worth it */
2795 outlen
= sdslen(obj
->ptr
)-4;
2796 if (outlen
<= 0) return 0;
2797 if ((out
= zmalloc(outlen
+1)) == NULL
) return 0;
2798 comprlen
= lzf_compress(obj
->ptr
, sdslen(obj
->ptr
), out
, outlen
);
2799 if (comprlen
== 0) {
2803 /* Data compressed! Let's save it on disk */
2804 byte
= (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_LZF
;
2805 if (fwrite(&byte
,1,1,fp
) == 0) goto writeerr
;
2806 if (rdbSaveLen(fp
,comprlen
) == -1) goto writeerr
;
2807 if (rdbSaveLen(fp
,sdslen(obj
->ptr
)) == -1) goto writeerr
;
2808 if (fwrite(out
,comprlen
,1,fp
) == 0) goto writeerr
;
2817 /* Save a string objet as [len][data] on disk. If the object is a string
2818 * representation of an integer value we try to safe it in a special form */
2819 static int rdbSaveStringObjectRaw(FILE *fp
, robj
*obj
) {
2823 len
= sdslen(obj
->ptr
);
2825 /* Try integer encoding */
2827 unsigned char buf
[5];
2828 if ((enclen
= rdbTryIntegerEncoding(obj
->ptr
,buf
)) > 0) {
2829 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
2834 /* Try LZF compression - under 20 bytes it's unable to compress even
2835 * aaaaaaaaaaaaaaaaaa so skip it */
2836 if (server
.rdbcompression
&& len
> 20) {
2839 retval
= rdbSaveLzfStringObject(fp
,obj
);
2840 if (retval
== -1) return -1;
2841 if (retval
> 0) return 0;
2842 /* retval == 0 means data can't be compressed, save the old way */
2845 /* Store verbatim */
2846 if (rdbSaveLen(fp
,len
) == -1) return -1;
2847 if (len
&& fwrite(obj
->ptr
,len
,1,fp
) == 0) return -1;
2851 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
2852 static int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
2855 if (obj
->storage
== REDIS_VM_MEMORY
&&
2856 obj
->encoding
!= REDIS_ENCODING_RAW
)
2858 obj
= getDecodedObject(obj
);
2859 retval
= rdbSaveStringObjectRaw(fp
,obj
);
2862 /* This is a fast path when we are sure the object is not encoded.
2863 * Note that's any *faster* actually as we needed to add the conditional
2864 * but because this may happen in a background process we don't want
2865 * to touch the object fields with incr/decrRefCount in order to
2866 * preveny copy on write of pages.
2868 * Also incrRefCount() will have a failing assert() if we try to call
2869 * it against an object with storage != REDIS_VM_MEMORY. */
2870 retval
= rdbSaveStringObjectRaw(fp
,obj
);
2875 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
2876 * 8 bit integer specifing the length of the representation.
2877 * This 8 bit integer has special values in order to specify the following
2883 static int rdbSaveDoubleValue(FILE *fp
, double val
) {
2884 unsigned char buf
[128];
2890 } else if (!isfinite(val
)) {
2892 buf
[0] = (val
< 0) ? 255 : 254;
2894 snprintf((char*)buf
+1,sizeof(buf
)-1,"%.17g",val
);
2895 buf
[0] = strlen((char*)buf
+1);
2898 if (fwrite(buf
,len
,1,fp
) == 0) return -1;
2902 /* Save a Redis object. */
2903 static int rdbSaveObject(FILE *fp
, robj
*o
) {
2904 if (o
->type
== REDIS_STRING
) {
2905 /* Save a string value */
2906 if (rdbSaveStringObject(fp
,o
) == -1) return -1;
2907 } else if (o
->type
== REDIS_LIST
) {
2908 /* Save a list value */
2909 list
*list
= o
->ptr
;
2913 if (rdbSaveLen(fp
,listLength(list
)) == -1) return -1;
2914 while((ln
= listYield(list
))) {
2915 robj
*eleobj
= listNodeValue(ln
);
2917 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2919 } else if (o
->type
== REDIS_SET
) {
2920 /* Save a set value */
2922 dictIterator
*di
= dictGetIterator(set
);
2925 if (rdbSaveLen(fp
,dictSize(set
)) == -1) return -1;
2926 while((de
= dictNext(di
)) != NULL
) {
2927 robj
*eleobj
= dictGetEntryKey(de
);
2929 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2931 dictReleaseIterator(di
);
2932 } else if (o
->type
== REDIS_ZSET
) {
2933 /* Save a set value */
2935 dictIterator
*di
= dictGetIterator(zs
->dict
);
2938 if (rdbSaveLen(fp
,dictSize(zs
->dict
)) == -1) return -1;
2939 while((de
= dictNext(di
)) != NULL
) {
2940 robj
*eleobj
= dictGetEntryKey(de
);
2941 double *score
= dictGetEntryVal(de
);
2943 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2944 if (rdbSaveDoubleValue(fp
,*score
) == -1) return -1;
2946 dictReleaseIterator(di
);
2948 redisAssert(0 != 0);
2953 /* Return the length the object will have on disk if saved with
2954 * the rdbSaveObject() function. Currently we use a trick to get
2955 * this length with very little changes to the code. In the future
2956 * we could switch to a faster solution. */
2957 static off_t
rdbSavedObjectLen(robj
*o
, FILE *fp
) {
2958 if (fp
== NULL
) fp
= server
.devnull
;
2960 assert(rdbSaveObject(fp
,o
) != 1);
2964 /* Return the number of pages required to save this object in the swap file */
2965 static off_t
rdbSavedObjectPages(robj
*o
, FILE *fp
) {
2966 off_t bytes
= rdbSavedObjectLen(o
,fp
);
2968 return (bytes
+(server
.vm_page_size
-1))/server
.vm_page_size
;
2971 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
2972 static int rdbSave(char *filename
) {
2973 dictIterator
*di
= NULL
;
2978 time_t now
= time(NULL
);
2980 snprintf(tmpfile
,256,"temp-%d.rdb", (int) getpid());
2981 fp
= fopen(tmpfile
,"w");
2983 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
2986 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
2987 for (j
= 0; j
< server
.dbnum
; j
++) {
2988 redisDb
*db
= server
.db
+j
;
2990 if (dictSize(d
) == 0) continue;
2991 di
= dictGetIterator(d
);
2997 /* Write the SELECT DB opcode */
2998 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
2999 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
3001 /* Iterate this DB writing every entry */
3002 while((de
= dictNext(di
)) != NULL
) {
3003 robj
*key
= dictGetEntryKey(de
);
3004 robj
*o
= dictGetEntryVal(de
);
3005 time_t expiretime
= getExpire(db
,key
);
3007 /* Save the expire time */
3008 if (expiretime
!= -1) {
3009 /* If this key is already expired skip it */
3010 if (expiretime
< now
) continue;
3011 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
;
3012 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
;
3014 /* Save the key and associated value. This requires special
3015 * handling if the value is swapped out. */
3016 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
3017 key
->storage
== REDIS_VM_SWAPPING
) {
3018 /* Save type, key, value */
3019 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
3020 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3021 if (rdbSaveObject(fp
,o
) == -1) goto werr
;
3023 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
3025 /* Get a preview of the object in memory */
3026 po
= vmPreviewObject(key
);
3027 /* Save type, key, value */
3028 if (rdbSaveType(fp
,key
->vtype
) == -1) goto werr
;
3029 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3030 if (rdbSaveObject(fp
,po
) == -1) goto werr
;
3031 /* Remove the loaded object from memory */
3035 dictReleaseIterator(di
);
3038 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
3040 /* Make sure data will not remain on the OS's output buffers */
3045 /* Use RENAME to make sure the DB file is changed atomically only
3046 * if the generate DB file is ok. */
3047 if (rename(tmpfile
,filename
) == -1) {
3048 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destination: %s", strerror(errno
));
3052 redisLog(REDIS_NOTICE
,"DB saved on disk");
3054 server
.lastsave
= time(NULL
);
3060 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
3061 if (di
) dictReleaseIterator(di
);
3065 static int rdbSaveBackground(char *filename
) {
3068 if (server
.bgsavechildpid
!= -1) return REDIS_ERR
;
3069 if ((childpid
= fork()) == 0) {
3072 if (rdbSave(filename
) == REDIS_OK
) {
3079 if (childpid
== -1) {
3080 redisLog(REDIS_WARNING
,"Can't save in background: fork: %s",
3084 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
3085 server
.bgsavechildpid
= childpid
;
3088 return REDIS_OK
; /* unreached */
3091 static void rdbRemoveTempFile(pid_t childpid
) {
3094 snprintf(tmpfile
,256,"temp-%d.rdb", (int) childpid
);
3098 static int rdbLoadType(FILE *fp
) {
3100 if (fread(&type
,1,1,fp
) == 0) return -1;
3104 static time_t rdbLoadTime(FILE *fp
) {
3106 if (fread(&t32
,4,1,fp
) == 0) return -1;
3107 return (time_t) t32
;
3110 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
3111 * of this file for a description of how this are stored on disk.
3113 * isencoded is set to 1 if the readed length is not actually a length but
3114 * an "encoding type", check the above comments for more info */
3115 static uint32_t rdbLoadLen(FILE *fp
, int *isencoded
) {
3116 unsigned char buf
[2];
3120 if (isencoded
) *isencoded
= 0;
3121 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3122 type
= (buf
[0]&0xC0)>>6;
3123 if (type
== REDIS_RDB_6BITLEN
) {
3124 /* Read a 6 bit len */
3126 } else if (type
== REDIS_RDB_ENCVAL
) {
3127 /* Read a 6 bit len encoding type */
3128 if (isencoded
) *isencoded
= 1;
3130 } else if (type
== REDIS_RDB_14BITLEN
) {
3131 /* Read a 14 bit len */
3132 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3133 return ((buf
[0]&0x3F)<<8)|buf
[1];
3135 /* Read a 32 bit len */
3136 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
3141 static robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
) {
3142 unsigned char enc
[4];
3145 if (enctype
== REDIS_RDB_ENC_INT8
) {
3146 if (fread(enc
,1,1,fp
) == 0) return NULL
;
3147 val
= (signed char)enc
[0];
3148 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
3150 if (fread(enc
,2,1,fp
) == 0) return NULL
;
3151 v
= enc
[0]|(enc
[1]<<8);
3153 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
3155 if (fread(enc
,4,1,fp
) == 0) return NULL
;
3156 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
3159 val
= 0; /* anti-warning */
3162 return createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",val
));
3165 static robj
*rdbLoadLzfStringObject(FILE*fp
) {
3166 unsigned int len
, clen
;
3167 unsigned char *c
= NULL
;
3170 if ((clen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3171 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3172 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
3173 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
3174 if (fread(c
,clen
,1,fp
) == 0) goto err
;
3175 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
3177 return createObject(REDIS_STRING
,val
);
3184 static robj
*rdbLoadStringObject(FILE*fp
) {
3189 len
= rdbLoadLen(fp
,&isencoded
);
3192 case REDIS_RDB_ENC_INT8
:
3193 case REDIS_RDB_ENC_INT16
:
3194 case REDIS_RDB_ENC_INT32
:
3195 return tryObjectSharing(rdbLoadIntegerObject(fp
,len
));
3196 case REDIS_RDB_ENC_LZF
:
3197 return tryObjectSharing(rdbLoadLzfStringObject(fp
));
3203 if (len
== REDIS_RDB_LENERR
) return NULL
;
3204 val
= sdsnewlen(NULL
,len
);
3205 if (len
&& fread(val
,len
,1,fp
) == 0) {
3209 return tryObjectSharing(createObject(REDIS_STRING
,val
));
3212 /* For information about double serialization check rdbSaveDoubleValue() */
3213 static int rdbLoadDoubleValue(FILE *fp
, double *val
) {
3217 if (fread(&len
,1,1,fp
) == 0) return -1;
3219 case 255: *val
= R_NegInf
; return 0;
3220 case 254: *val
= R_PosInf
; return 0;
3221 case 253: *val
= R_Nan
; return 0;
3223 if (fread(buf
,len
,1,fp
) == 0) return -1;
3225 sscanf(buf
, "%lg", val
);
3230 /* Load a Redis object of the specified type from the specified file.
3231 * On success a newly allocated object is returned, otherwise NULL. */
3232 static robj
*rdbLoadObject(int type
, FILE *fp
) {
3235 if (type
== REDIS_STRING
) {
3236 /* Read string value */
3237 if ((o
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3238 tryObjectEncoding(o
);
3239 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
3240 /* Read list/set value */
3243 if ((listlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3244 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
3245 /* Load every single element of the list/set */
3249 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3250 tryObjectEncoding(ele
);
3251 if (type
== REDIS_LIST
) {
3252 listAddNodeTail((list
*)o
->ptr
,ele
);
3254 dictAdd((dict
*)o
->ptr
,ele
,NULL
);
3257 } else if (type
== REDIS_ZSET
) {
3258 /* Read list/set value */
3262 if ((zsetlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3263 o
= createZsetObject();
3265 /* Load every single element of the list/set */
3268 double *score
= zmalloc(sizeof(double));
3270 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3271 tryObjectEncoding(ele
);
3272 if (rdbLoadDoubleValue(fp
,score
) == -1) return NULL
;
3273 dictAdd(zs
->dict
,ele
,score
);
3274 zslInsert(zs
->zsl
,*score
,ele
);
3275 incrRefCount(ele
); /* added to skiplist */
3278 redisAssert(0 != 0);
3283 static int rdbLoad(char *filename
) {
3285 robj
*keyobj
= NULL
;
3287 int type
, retval
, rdbver
;
3288 dict
*d
= server
.db
[0].dict
;
3289 redisDb
*db
= server
.db
+0;
3291 time_t expiretime
= -1, now
= time(NULL
);
3292 long long loadedkeys
= 0;
3294 fp
= fopen(filename
,"r");
3295 if (!fp
) return REDIS_ERR
;
3296 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
3298 if (memcmp(buf
,"REDIS",5) != 0) {
3300 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
3303 rdbver
= atoi(buf
+5);
3306 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
3313 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3314 if (type
== REDIS_EXPIRETIME
) {
3315 if ((expiretime
= rdbLoadTime(fp
)) == -1) goto eoferr
;
3316 /* We read the time so we need to read the object type again */
3317 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3319 if (type
== REDIS_EOF
) break;
3320 /* Handle SELECT DB opcode as a special case */
3321 if (type
== REDIS_SELECTDB
) {
3322 if ((dbid
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
)
3324 if (dbid
>= (unsigned)server
.dbnum
) {
3325 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
3328 db
= server
.db
+dbid
;
3333 if ((keyobj
= rdbLoadStringObject(fp
)) == NULL
) goto eoferr
;
3335 if ((o
= rdbLoadObject(type
,fp
)) == NULL
) goto eoferr
;
3336 /* Add the new object in the hash table */
3337 retval
= dictAdd(d
,keyobj
,o
);
3338 if (retval
== DICT_ERR
) {
3339 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj
->ptr
);
3342 /* Set the expire time if needed */
3343 if (expiretime
!= -1) {
3344 setExpire(db
,keyobj
,expiretime
);
3345 /* Delete this key if already expired */
3346 if (expiretime
< now
) deleteKey(db
,keyobj
);
3350 /* Handle swapping while loading big datasets when VM is on */
3352 if (server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
3353 while (zmalloc_used_memory() > server
.vm_max_memory
) {
3354 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
3361 eoferr
: /* unexpected end of file is handled here with a fatal exit */
3362 if (keyobj
) decrRefCount(keyobj
);
3363 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
3365 return REDIS_ERR
; /* Just to avoid warning */
3368 /*================================== Commands =============================== */
3370 static void authCommand(redisClient
*c
) {
3371 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
3372 c
->authenticated
= 1;
3373 addReply(c
,shared
.ok
);
3375 c
->authenticated
= 0;
3376 addReplySds(c
,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
3380 static void pingCommand(redisClient
*c
) {
3381 addReply(c
,shared
.pong
);
3384 static void echoCommand(redisClient
*c
) {
3385 addReplyBulkLen(c
,c
->argv
[1]);
3386 addReply(c
,c
->argv
[1]);
3387 addReply(c
,shared
.crlf
);
3390 /*=================================== Strings =============================== */
3392 static void setGenericCommand(redisClient
*c
, int nx
) {
3395 if (nx
) deleteIfVolatile(c
->db
,c
->argv
[1]);
3396 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3397 if (retval
== DICT_ERR
) {
3399 /* If the key is about a swapped value, we want a new key object
3400 * to overwrite the old. So we delete the old key in the database.
3401 * This will also make sure that swap pages about the old object
3402 * will be marked as free. */
3403 if (deleteIfSwapped(c
->db
,c
->argv
[1]))
3404 incrRefCount(c
->argv
[1]);
3405 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3406 incrRefCount(c
->argv
[2]);
3408 addReply(c
,shared
.czero
);
3412 incrRefCount(c
->argv
[1]);
3413 incrRefCount(c
->argv
[2]);
3416 removeExpire(c
->db
,c
->argv
[1]);
3417 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3420 static void setCommand(redisClient
*c
) {
3421 setGenericCommand(c
,0);
3424 static void setnxCommand(redisClient
*c
) {
3425 setGenericCommand(c
,1);
3428 static int getGenericCommand(redisClient
*c
) {
3429 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3432 addReply(c
,shared
.nullbulk
);
3435 if (o
->type
!= REDIS_STRING
) {
3436 addReply(c
,shared
.wrongtypeerr
);
3439 addReplyBulkLen(c
,o
);
3441 addReply(c
,shared
.crlf
);
3447 static void getCommand(redisClient
*c
) {
3448 getGenericCommand(c
);
3451 static void getsetCommand(redisClient
*c
) {
3452 if (getGenericCommand(c
) == REDIS_ERR
) return;
3453 if (dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]) == DICT_ERR
) {
3454 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3456 incrRefCount(c
->argv
[1]);
3458 incrRefCount(c
->argv
[2]);
3460 removeExpire(c
->db
,c
->argv
[1]);
3463 static void mgetCommand(redisClient
*c
) {
3466 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
3467 for (j
= 1; j
< c
->argc
; j
++) {
3468 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[j
]);
3470 addReply(c
,shared
.nullbulk
);
3472 if (o
->type
!= REDIS_STRING
) {
3473 addReply(c
,shared
.nullbulk
);
3475 addReplyBulkLen(c
,o
);
3477 addReply(c
,shared
.crlf
);
3483 static void msetGenericCommand(redisClient
*c
, int nx
) {
3484 int j
, busykeys
= 0;
3486 if ((c
->argc
% 2) == 0) {
3487 addReplySds(c
,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
3490 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
3491 * set nothing at all if at least one already key exists. */
3493 for (j
= 1; j
< c
->argc
; j
+= 2) {
3494 if (lookupKeyWrite(c
->db
,c
->argv
[j
]) != NULL
) {
3500 addReply(c
, shared
.czero
);
3504 for (j
= 1; j
< c
->argc
; j
+= 2) {
3507 tryObjectEncoding(c
->argv
[j
+1]);
3508 retval
= dictAdd(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3509 if (retval
== DICT_ERR
) {
3510 dictReplace(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3511 incrRefCount(c
->argv
[j
+1]);
3513 incrRefCount(c
->argv
[j
]);
3514 incrRefCount(c
->argv
[j
+1]);
3516 removeExpire(c
->db
,c
->argv
[j
]);
3518 server
.dirty
+= (c
->argc
-1)/2;
3519 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3522 static void msetCommand(redisClient
*c
) {
3523 msetGenericCommand(c
,0);
3526 static void msetnxCommand(redisClient
*c
) {
3527 msetGenericCommand(c
,1);
3530 static void incrDecrCommand(redisClient
*c
, long long incr
) {
3535 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3539 if (o
->type
!= REDIS_STRING
) {
3544 if (o
->encoding
== REDIS_ENCODING_RAW
)
3545 value
= strtoll(o
->ptr
, &eptr
, 10);
3546 else if (o
->encoding
== REDIS_ENCODING_INT
)
3547 value
= (long)o
->ptr
;
3549 redisAssert(1 != 1);
3554 o
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
));
3555 tryObjectEncoding(o
);
3556 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],o
);
3557 if (retval
== DICT_ERR
) {
3558 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
3559 removeExpire(c
->db
,c
->argv
[1]);
3561 incrRefCount(c
->argv
[1]);
3564 addReply(c
,shared
.colon
);
3566 addReply(c
,shared
.crlf
);
3569 static void incrCommand(redisClient
*c
) {
3570 incrDecrCommand(c
,1);
3573 static void decrCommand(redisClient
*c
) {
3574 incrDecrCommand(c
,-1);
3577 static void incrbyCommand(redisClient
*c
) {
3578 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3579 incrDecrCommand(c
,incr
);
3582 static void decrbyCommand(redisClient
*c
) {
3583 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3584 incrDecrCommand(c
,-incr
);
3587 /* ========================= Type agnostic commands ========================= */
3589 static void delCommand(redisClient
*c
) {
3592 for (j
= 1; j
< c
->argc
; j
++) {
3593 if (deleteKey(c
->db
,c
->argv
[j
])) {
3600 addReply(c
,shared
.czero
);
3603 addReply(c
,shared
.cone
);
3606 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",deleted
));
3611 static void existsCommand(redisClient
*c
) {
3612 addReply(c
,lookupKeyRead(c
->db
,c
->argv
[1]) ? shared
.cone
: shared
.czero
);
3615 static void selectCommand(redisClient
*c
) {
3616 int id
= atoi(c
->argv
[1]->ptr
);
3618 if (selectDb(c
,id
) == REDIS_ERR
) {
3619 addReplySds(c
,sdsnew("-ERR invalid DB index\r\n"));
3621 addReply(c
,shared
.ok
);
3625 static void randomkeyCommand(redisClient
*c
) {
3629 de
= dictGetRandomKey(c
->db
->dict
);
3630 if (!de
|| expireIfNeeded(c
->db
,dictGetEntryKey(de
)) == 0) break;
3633 addReply(c
,shared
.plus
);
3634 addReply(c
,shared
.crlf
);
3636 addReply(c
,shared
.plus
);
3637 addReply(c
,dictGetEntryKey(de
));
3638 addReply(c
,shared
.crlf
);
3642 static void keysCommand(redisClient
*c
) {
3645 sds pattern
= c
->argv
[1]->ptr
;
3646 int plen
= sdslen(pattern
);
3647 unsigned long numkeys
= 0, keyslen
= 0;
3648 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
3650 di
= dictGetIterator(c
->db
->dict
);
3652 decrRefCount(lenobj
);
3653 while((de
= dictNext(di
)) != NULL
) {
3654 robj
*keyobj
= dictGetEntryKey(de
);
3656 sds key
= keyobj
->ptr
;
3657 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
3658 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
3659 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
3661 addReply(c
,shared
.space
);
3664 keyslen
+= sdslen(key
);
3668 dictReleaseIterator(di
);
3669 lenobj
->ptr
= sdscatprintf(sdsempty(),"$%lu\r\n",keyslen
+(numkeys
? (numkeys
-1) : 0));
3670 addReply(c
,shared
.crlf
);
3673 static void dbsizeCommand(redisClient
*c
) {
3675 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c
->db
->dict
)));
3678 static void lastsaveCommand(redisClient
*c
) {
3680 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
3683 static void typeCommand(redisClient
*c
) {
3687 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3692 case REDIS_STRING
: type
= "+string"; break;
3693 case REDIS_LIST
: type
= "+list"; break;
3694 case REDIS_SET
: type
= "+set"; break;
3695 case REDIS_ZSET
: type
= "+zset"; break;
3696 default: type
= "unknown"; break;
3699 addReplySds(c
,sdsnew(type
));
3700 addReply(c
,shared
.crlf
);
3703 static void saveCommand(redisClient
*c
) {
3704 if (server
.bgsavechildpid
!= -1) {
3705 addReplySds(c
,sdsnew("-ERR background save in progress\r\n"));
3708 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
3709 addReply(c
,shared
.ok
);
3711 addReply(c
,shared
.err
);
3715 static void bgsaveCommand(redisClient
*c
) {
3716 if (server
.bgsavechildpid
!= -1) {
3717 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
3720 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
3721 char *status
= "+Background saving started\r\n";
3722 addReplySds(c
,sdsnew(status
));
3724 addReply(c
,shared
.err
);
3728 static void shutdownCommand(redisClient
*c
) {
3729 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
3730 /* Kill the saving child if there is a background saving in progress.
3731 We want to avoid race conditions, for instance our saving child may
3732 overwrite the synchronous saving did by SHUTDOWN. */
3733 if (server
.bgsavechildpid
!= -1) {
3734 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
3735 kill(server
.bgsavechildpid
,SIGKILL
);
3736 rdbRemoveTempFile(server
.bgsavechildpid
);
3738 if (server
.appendonly
) {
3739 /* Append only file: fsync() the AOF and exit */
3740 fsync(server
.appendfd
);
3743 /* Snapshotting. Perform a SYNC SAVE and exit */
3744 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
3745 if (server
.daemonize
)
3746 unlink(server
.pidfile
);
3747 redisLog(REDIS_WARNING
,"%zu bytes used at exit",zmalloc_used_memory());
3748 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
3751 /* Ooops.. error saving! The best we can do is to continue operating.
3752 * Note that if there was a background saving process, in the next
3753 * cron() Redis will be notified that the background saving aborted,
3754 * handling special stuff like slaves pending for synchronization... */
3755 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
3756 addReplySds(c
,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
3761 static void renameGenericCommand(redisClient
*c
, int nx
) {
3764 /* To use the same key as src and dst is probably an error */
3765 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
3766 addReply(c
,shared
.sameobjecterr
);
3770 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3772 addReply(c
,shared
.nokeyerr
);
3776 deleteIfVolatile(c
->db
,c
->argv
[2]);
3777 if (dictAdd(c
->db
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
3780 addReply(c
,shared
.czero
);
3783 dictReplace(c
->db
->dict
,c
->argv
[2],o
);
3785 incrRefCount(c
->argv
[2]);
3787 deleteKey(c
->db
,c
->argv
[1]);
3789 addReply(c
,nx
? shared
.cone
: shared
.ok
);
3792 static void renameCommand(redisClient
*c
) {
3793 renameGenericCommand(c
,0);
3796 static void renamenxCommand(redisClient
*c
) {
3797 renameGenericCommand(c
,1);
3800 static void moveCommand(redisClient
*c
) {
3805 /* Obtain source and target DB pointers */
3808 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
3809 addReply(c
,shared
.outofrangeerr
);
3813 selectDb(c
,srcid
); /* Back to the source DB */
3815 /* If the user is moving using as target the same
3816 * DB as the source DB it is probably an error. */
3818 addReply(c
,shared
.sameobjecterr
);
3822 /* Check if the element exists and get a reference */
3823 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3825 addReply(c
,shared
.czero
);
3829 /* Try to add the element to the target DB */
3830 deleteIfVolatile(dst
,c
->argv
[1]);
3831 if (dictAdd(dst
->dict
,c
->argv
[1],o
) == DICT_ERR
) {
3832 addReply(c
,shared
.czero
);
3835 incrRefCount(c
->argv
[1]);
3838 /* OK! key moved, free the entry in the source DB */
3839 deleteKey(src
,c
->argv
[1]);
3841 addReply(c
,shared
.cone
);
3844 /* =================================== Lists ================================ */
3845 static void pushGenericCommand(redisClient
*c
, int where
) {
3849 lobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3851 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
3852 addReply(c
,shared
.ok
);
3855 lobj
= createListObject();
3857 if (where
== REDIS_HEAD
) {
3858 listAddNodeHead(list
,c
->argv
[2]);
3860 listAddNodeTail(list
,c
->argv
[2]);
3862 dictAdd(c
->db
->dict
,c
->argv
[1],lobj
);
3863 incrRefCount(c
->argv
[1]);
3864 incrRefCount(c
->argv
[2]);
3866 if (lobj
->type
!= REDIS_LIST
) {
3867 addReply(c
,shared
.wrongtypeerr
);
3870 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
3871 addReply(c
,shared
.ok
);
3875 if (where
== REDIS_HEAD
) {
3876 listAddNodeHead(list
,c
->argv
[2]);
3878 listAddNodeTail(list
,c
->argv
[2]);
3880 incrRefCount(c
->argv
[2]);
3883 addReply(c
,shared
.ok
);
3886 static void lpushCommand(redisClient
*c
) {
3887 pushGenericCommand(c
,REDIS_HEAD
);
3890 static void rpushCommand(redisClient
*c
) {
3891 pushGenericCommand(c
,REDIS_TAIL
);
3894 static void llenCommand(redisClient
*c
) {
3898 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3900 addReply(c
,shared
.czero
);
3903 if (o
->type
!= REDIS_LIST
) {
3904 addReply(c
,shared
.wrongtypeerr
);
3907 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(l
)));
3912 static void lindexCommand(redisClient
*c
) {
3914 int index
= atoi(c
->argv
[2]->ptr
);
3916 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3918 addReply(c
,shared
.nullbulk
);
3920 if (o
->type
!= REDIS_LIST
) {
3921 addReply(c
,shared
.wrongtypeerr
);
3923 list
*list
= o
->ptr
;
3926 ln
= listIndex(list
, index
);
3928 addReply(c
,shared
.nullbulk
);
3930 robj
*ele
= listNodeValue(ln
);
3931 addReplyBulkLen(c
,ele
);
3933 addReply(c
,shared
.crlf
);
3939 static void lsetCommand(redisClient
*c
) {
3941 int index
= atoi(c
->argv
[2]->ptr
);
3943 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3945 addReply(c
,shared
.nokeyerr
);
3947 if (o
->type
!= REDIS_LIST
) {
3948 addReply(c
,shared
.wrongtypeerr
);
3950 list
*list
= o
->ptr
;
3953 ln
= listIndex(list
, index
);
3955 addReply(c
,shared
.outofrangeerr
);
3957 robj
*ele
= listNodeValue(ln
);
3960 listNodeValue(ln
) = c
->argv
[3];
3961 incrRefCount(c
->argv
[3]);
3962 addReply(c
,shared
.ok
);
3969 static void popGenericCommand(redisClient
*c
, int where
) {
3972 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3974 addReply(c
,shared
.nullbulk
);
3976 if (o
->type
!= REDIS_LIST
) {
3977 addReply(c
,shared
.wrongtypeerr
);
3979 list
*list
= o
->ptr
;
3982 if (where
== REDIS_HEAD
)
3983 ln
= listFirst(list
);
3985 ln
= listLast(list
);
3988 addReply(c
,shared
.nullbulk
);
3990 robj
*ele
= listNodeValue(ln
);
3991 addReplyBulkLen(c
,ele
);
3993 addReply(c
,shared
.crlf
);
3994 listDelNode(list
,ln
);
4001 static void lpopCommand(redisClient
*c
) {
4002 popGenericCommand(c
,REDIS_HEAD
);
4005 static void rpopCommand(redisClient
*c
) {
4006 popGenericCommand(c
,REDIS_TAIL
);
4009 static void lrangeCommand(redisClient
*c
) {
4011 int start
= atoi(c
->argv
[2]->ptr
);
4012 int end
= atoi(c
->argv
[3]->ptr
);
4014 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4016 addReply(c
,shared
.nullmultibulk
);
4018 if (o
->type
!= REDIS_LIST
) {
4019 addReply(c
,shared
.wrongtypeerr
);
4021 list
*list
= o
->ptr
;
4023 int llen
= listLength(list
);
4027 /* convert negative indexes */
4028 if (start
< 0) start
= llen
+start
;
4029 if (end
< 0) end
= llen
+end
;
4030 if (start
< 0) start
= 0;
4031 if (end
< 0) end
= 0;
4033 /* indexes sanity checks */
4034 if (start
> end
|| start
>= llen
) {
4035 /* Out of range start or start > end result in empty list */
4036 addReply(c
,shared
.emptymultibulk
);
4039 if (end
>= llen
) end
= llen
-1;
4040 rangelen
= (end
-start
)+1;
4042 /* Return the result in form of a multi-bulk reply */
4043 ln
= listIndex(list
, start
);
4044 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
4045 for (j
= 0; j
< rangelen
; j
++) {
4046 ele
= listNodeValue(ln
);
4047 addReplyBulkLen(c
,ele
);
4049 addReply(c
,shared
.crlf
);
4056 static void ltrimCommand(redisClient
*c
) {
4058 int start
= atoi(c
->argv
[2]->ptr
);
4059 int end
= atoi(c
->argv
[3]->ptr
);
4061 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4063 addReply(c
,shared
.ok
);
4065 if (o
->type
!= REDIS_LIST
) {
4066 addReply(c
,shared
.wrongtypeerr
);
4068 list
*list
= o
->ptr
;
4070 int llen
= listLength(list
);
4071 int j
, ltrim
, rtrim
;
4073 /* convert negative indexes */
4074 if (start
< 0) start
= llen
+start
;
4075 if (end
< 0) end
= llen
+end
;
4076 if (start
< 0) start
= 0;
4077 if (end
< 0) end
= 0;
4079 /* indexes sanity checks */
4080 if (start
> end
|| start
>= llen
) {
4081 /* Out of range start or start > end result in empty list */
4085 if (end
>= llen
) end
= llen
-1;
4090 /* Remove list elements to perform the trim */
4091 for (j
= 0; j
< ltrim
; j
++) {
4092 ln
= listFirst(list
);
4093 listDelNode(list
,ln
);
4095 for (j
= 0; j
< rtrim
; j
++) {
4096 ln
= listLast(list
);
4097 listDelNode(list
,ln
);
4100 addReply(c
,shared
.ok
);
4105 static void lremCommand(redisClient
*c
) {
4108 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4110 addReply(c
,shared
.czero
);
4112 if (o
->type
!= REDIS_LIST
) {
4113 addReply(c
,shared
.wrongtypeerr
);
4115 list
*list
= o
->ptr
;
4116 listNode
*ln
, *next
;
4117 int toremove
= atoi(c
->argv
[2]->ptr
);
4122 toremove
= -toremove
;
4125 ln
= fromtail
? list
->tail
: list
->head
;
4127 robj
*ele
= listNodeValue(ln
);
4129 next
= fromtail
? ln
->prev
: ln
->next
;
4130 if (compareStringObjects(ele
,c
->argv
[3]) == 0) {
4131 listDelNode(list
,ln
);
4134 if (toremove
&& removed
== toremove
) break;
4138 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
4143 /* This is the semantic of this command:
4144 * RPOPLPUSH srclist dstlist:
4145 * IF LLEN(srclist) > 0
4146 * element = RPOP srclist
4147 * LPUSH dstlist element
4154 * The idea is to be able to get an element from a list in a reliable way
4155 * since the element is not just returned but pushed against another list
4156 * as well. This command was originally proposed by Ezra Zygmuntowicz.
4158 static void rpoplpushcommand(redisClient
*c
) {
4161 sobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4163 addReply(c
,shared
.nullbulk
);
4165 if (sobj
->type
!= REDIS_LIST
) {
4166 addReply(c
,shared
.wrongtypeerr
);
4168 list
*srclist
= sobj
->ptr
;
4169 listNode
*ln
= listLast(srclist
);
4172 addReply(c
,shared
.nullbulk
);
4174 robj
*dobj
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4175 robj
*ele
= listNodeValue(ln
);
4178 if (dobj
&& dobj
->type
!= REDIS_LIST
) {
4179 addReply(c
,shared
.wrongtypeerr
);
4183 /* Add the element to the target list (unless it's directly
4184 * passed to some BLPOP-ing client */
4185 if (!handleClientsWaitingListPush(c
,c
->argv
[2],ele
)) {
4187 /* Create the list if the key does not exist */
4188 dobj
= createListObject();
4189 dictAdd(c
->db
->dict
,c
->argv
[2],dobj
);
4190 incrRefCount(c
->argv
[2]);
4192 dstlist
= dobj
->ptr
;
4193 listAddNodeHead(dstlist
,ele
);
4197 /* Send the element to the client as reply as well */
4198 addReplyBulkLen(c
,ele
);
4200 addReply(c
,shared
.crlf
);
4202 /* Finally remove the element from the source list */
4203 listDelNode(srclist
,ln
);
4211 /* ==================================== Sets ================================ */
4213 static void saddCommand(redisClient
*c
) {
4216 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4218 set
= createSetObject();
4219 dictAdd(c
->db
->dict
,c
->argv
[1],set
);
4220 incrRefCount(c
->argv
[1]);
4222 if (set
->type
!= REDIS_SET
) {
4223 addReply(c
,shared
.wrongtypeerr
);
4227 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
4228 incrRefCount(c
->argv
[2]);
4230 addReply(c
,shared
.cone
);
4232 addReply(c
,shared
.czero
);
4236 static void sremCommand(redisClient
*c
) {
4239 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4241 addReply(c
,shared
.czero
);
4243 if (set
->type
!= REDIS_SET
) {
4244 addReply(c
,shared
.wrongtypeerr
);
4247 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
4249 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4250 addReply(c
,shared
.cone
);
4252 addReply(c
,shared
.czero
);
4257 static void smoveCommand(redisClient
*c
) {
4258 robj
*srcset
, *dstset
;
4260 srcset
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4261 dstset
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4263 /* If the source key does not exist return 0, if it's of the wrong type
4265 if (srcset
== NULL
|| srcset
->type
!= REDIS_SET
) {
4266 addReply(c
, srcset
? shared
.wrongtypeerr
: shared
.czero
);
4269 /* Error if the destination key is not a set as well */
4270 if (dstset
&& dstset
->type
!= REDIS_SET
) {
4271 addReply(c
,shared
.wrongtypeerr
);
4274 /* Remove the element from the source set */
4275 if (dictDelete(srcset
->ptr
,c
->argv
[3]) == DICT_ERR
) {
4276 /* Key not found in the src set! return zero */
4277 addReply(c
,shared
.czero
);
4281 /* Add the element to the destination set */
4283 dstset
= createSetObject();
4284 dictAdd(c
->db
->dict
,c
->argv
[2],dstset
);
4285 incrRefCount(c
->argv
[2]);
4287 if (dictAdd(dstset
->ptr
,c
->argv
[3],NULL
) == DICT_OK
)
4288 incrRefCount(c
->argv
[3]);
4289 addReply(c
,shared
.cone
);
4292 static void sismemberCommand(redisClient
*c
) {
4295 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
4297 addReply(c
,shared
.czero
);
4299 if (set
->type
!= REDIS_SET
) {
4300 addReply(c
,shared
.wrongtypeerr
);
4303 if (dictFind(set
->ptr
,c
->argv
[2]))
4304 addReply(c
,shared
.cone
);
4306 addReply(c
,shared
.czero
);
4310 static void scardCommand(redisClient
*c
) {
4314 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4316 addReply(c
,shared
.czero
);
4319 if (o
->type
!= REDIS_SET
) {
4320 addReply(c
,shared
.wrongtypeerr
);
4323 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4329 static void spopCommand(redisClient
*c
) {
4333 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4335 addReply(c
,shared
.nullbulk
);
4337 if (set
->type
!= REDIS_SET
) {
4338 addReply(c
,shared
.wrongtypeerr
);
4341 de
= dictGetRandomKey(set
->ptr
);
4343 addReply(c
,shared
.nullbulk
);
4345 robj
*ele
= dictGetEntryKey(de
);
4347 addReplyBulkLen(c
,ele
);
4349 addReply(c
,shared
.crlf
);
4350 dictDelete(set
->ptr
,ele
);
4351 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4357 static void srandmemberCommand(redisClient
*c
) {
4361 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
4363 addReply(c
,shared
.nullbulk
);
4365 if (set
->type
!= REDIS_SET
) {
4366 addReply(c
,shared
.wrongtypeerr
);
4369 de
= dictGetRandomKey(set
->ptr
);
4371 addReply(c
,shared
.nullbulk
);
4373 robj
*ele
= dictGetEntryKey(de
);
4375 addReplyBulkLen(c
,ele
);
4377 addReply(c
,shared
.crlf
);
4382 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
4383 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
4385 return dictSize(*d1
)-dictSize(*d2
);
4388 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, unsigned long setsnum
, robj
*dstkey
) {
4389 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4392 robj
*lenobj
= NULL
, *dstset
= NULL
;
4393 unsigned long j
, cardinality
= 0;
4395 for (j
= 0; j
< setsnum
; j
++) {
4399 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4400 lookupKeyRead(c
->db
,setskeys
[j
]);
4404 if (deleteKey(c
->db
,dstkey
))
4406 addReply(c
,shared
.czero
);
4408 addReply(c
,shared
.nullmultibulk
);
4412 if (setobj
->type
!= REDIS_SET
) {
4414 addReply(c
,shared
.wrongtypeerr
);
4417 dv
[j
] = setobj
->ptr
;
4419 /* Sort sets from the smallest to largest, this will improve our
4420 * algorithm's performace */
4421 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
4423 /* The first thing we should output is the total number of elements...
4424 * since this is a multi-bulk write, but at this stage we don't know
4425 * the intersection set size, so we use a trick, append an empty object
4426 * to the output list and save the pointer to later modify it with the
4429 lenobj
= createObject(REDIS_STRING
,NULL
);
4431 decrRefCount(lenobj
);
4433 /* If we have a target key where to store the resulting set
4434 * create this key with an empty set inside */
4435 dstset
= createSetObject();
4438 /* Iterate all the elements of the first (smallest) set, and test
4439 * the element against all the other sets, if at least one set does
4440 * not include the element it is discarded */
4441 di
= dictGetIterator(dv
[0]);
4443 while((de
= dictNext(di
)) != NULL
) {
4446 for (j
= 1; j
< setsnum
; j
++)
4447 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
4449 continue; /* at least one set does not contain the member */
4450 ele
= dictGetEntryKey(de
);
4452 addReplyBulkLen(c
,ele
);
4454 addReply(c
,shared
.crlf
);
4457 dictAdd(dstset
->ptr
,ele
,NULL
);
4461 dictReleaseIterator(di
);
4464 /* Store the resulting set into the target */
4465 deleteKey(c
->db
,dstkey
);
4466 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4467 incrRefCount(dstkey
);
4471 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",cardinality
);
4473 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4474 dictSize((dict
*)dstset
->ptr
)));
4480 static void sinterCommand(redisClient
*c
) {
4481 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
4484 static void sinterstoreCommand(redisClient
*c
) {
4485 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
4488 #define REDIS_OP_UNION 0
4489 #define REDIS_OP_DIFF 1
4491 static void sunionDiffGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
, int op
) {
4492 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4495 robj
*dstset
= NULL
;
4496 int j
, cardinality
= 0;
4498 for (j
= 0; j
< setsnum
; j
++) {
4502 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4503 lookupKeyRead(c
->db
,setskeys
[j
]);
4508 if (setobj
->type
!= REDIS_SET
) {
4510 addReply(c
,shared
.wrongtypeerr
);
4513 dv
[j
] = setobj
->ptr
;
4516 /* We need a temp set object to store our union. If the dstkey
4517 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
4518 * this set object will be the resulting object to set into the target key*/
4519 dstset
= createSetObject();
4521 /* Iterate all the elements of all the sets, add every element a single
4522 * time to the result set */
4523 for (j
= 0; j
< setsnum
; j
++) {
4524 if (op
== REDIS_OP_DIFF
&& j
== 0 && !dv
[j
]) break; /* result set is empty */
4525 if (!dv
[j
]) continue; /* non existing keys are like empty sets */
4527 di
= dictGetIterator(dv
[j
]);
4529 while((de
= dictNext(di
)) != NULL
) {
4532 /* dictAdd will not add the same element multiple times */
4533 ele
= dictGetEntryKey(de
);
4534 if (op
== REDIS_OP_UNION
|| j
== 0) {
4535 if (dictAdd(dstset
->ptr
,ele
,NULL
) == DICT_OK
) {
4539 } else if (op
== REDIS_OP_DIFF
) {
4540 if (dictDelete(dstset
->ptr
,ele
) == DICT_OK
) {
4545 dictReleaseIterator(di
);
4547 if (op
== REDIS_OP_DIFF
&& cardinality
== 0) break; /* result set is empty */
4550 /* Output the content of the resulting set, if not in STORE mode */
4552 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",cardinality
));
4553 di
= dictGetIterator(dstset
->ptr
);
4554 while((de
= dictNext(di
)) != NULL
) {
4557 ele
= dictGetEntryKey(de
);
4558 addReplyBulkLen(c
,ele
);
4560 addReply(c
,shared
.crlf
);
4562 dictReleaseIterator(di
);
4564 /* If we have a target key where to store the resulting set
4565 * create this key with the result set inside */
4566 deleteKey(c
->db
,dstkey
);
4567 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4568 incrRefCount(dstkey
);
4573 decrRefCount(dstset
);
4575 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4576 dictSize((dict
*)dstset
->ptr
)));
4582 static void sunionCommand(redisClient
*c
) {
4583 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_UNION
);
4586 static void sunionstoreCommand(redisClient
*c
) {
4587 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_UNION
);
4590 static void sdiffCommand(redisClient
*c
) {
4591 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_DIFF
);
4594 static void sdiffstoreCommand(redisClient
*c
) {
4595 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_DIFF
);
4598 /* ==================================== ZSets =============================== */
4600 /* ZSETs are ordered sets using two data structures to hold the same elements
4601 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
4604 * The elements are added to an hash table mapping Redis objects to scores.
4605 * At the same time the elements are added to a skip list mapping scores
4606 * to Redis objects (so objects are sorted by scores in this "view"). */
4608 /* This skiplist implementation is almost a C translation of the original
4609 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
4610 * Alternative to Balanced Trees", modified in three ways:
4611 * a) this implementation allows for repeated values.
4612 * b) the comparison is not just by key (our 'score') but by satellite data.
4613 * c) there is a back pointer, so it's a doubly linked list with the back
4614 * pointers being only at "level 1". This allows to traverse the list
4615 * from tail to head, useful for ZREVRANGE. */
4617 static zskiplistNode
*zslCreateNode(int level
, double score
, robj
*obj
) {
4618 zskiplistNode
*zn
= zmalloc(sizeof(*zn
));
4620 zn
->forward
= zmalloc(sizeof(zskiplistNode
*) * level
);
4626 static zskiplist
*zslCreate(void) {
4630 zsl
= zmalloc(sizeof(*zsl
));
4633 zsl
->header
= zslCreateNode(ZSKIPLIST_MAXLEVEL
,0,NULL
);
4634 for (j
= 0; j
< ZSKIPLIST_MAXLEVEL
; j
++)
4635 zsl
->header
->forward
[j
] = NULL
;
4636 zsl
->header
->backward
= NULL
;
4641 static void zslFreeNode(zskiplistNode
*node
) {
4642 decrRefCount(node
->obj
);
4643 zfree(node
->forward
);
4647 static void zslFree(zskiplist
*zsl
) {
4648 zskiplistNode
*node
= zsl
->header
->forward
[0], *next
;
4650 zfree(zsl
->header
->forward
);
4653 next
= node
->forward
[0];
4660 static int zslRandomLevel(void) {
4662 while ((random()&0xFFFF) < (ZSKIPLIST_P
* 0xFFFF))
4667 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
) {
4668 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4672 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4673 while (x
->forward
[i
] &&
4674 (x
->forward
[i
]->score
< score
||
4675 (x
->forward
[i
]->score
== score
&&
4676 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
4680 /* we assume the key is not already inside, since we allow duplicated
4681 * scores, and the re-insertion of score and redis object should never
4682 * happpen since the caller of zslInsert() should test in the hash table
4683 * if the element is already inside or not. */
4684 level
= zslRandomLevel();
4685 if (level
> zsl
->level
) {
4686 for (i
= zsl
->level
; i
< level
; i
++)
4687 update
[i
] = zsl
->header
;
4690 x
= zslCreateNode(level
,score
,obj
);
4691 for (i
= 0; i
< level
; i
++) {
4692 x
->forward
[i
] = update
[i
]->forward
[i
];
4693 update
[i
]->forward
[i
] = x
;
4695 x
->backward
= (update
[0] == zsl
->header
) ? NULL
: update
[0];
4697 x
->forward
[0]->backward
= x
;
4703 /* Delete an element with matching score/object from the skiplist. */
4704 static int zslDelete(zskiplist
*zsl
, double score
, robj
*obj
) {
4705 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4709 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4710 while (x
->forward
[i
] &&
4711 (x
->forward
[i
]->score
< score
||
4712 (x
->forward
[i
]->score
== score
&&
4713 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
4717 /* We may have multiple elements with the same score, what we need
4718 * is to find the element with both the right score and object. */
4720 if (x
&& score
== x
->score
&& compareStringObjects(x
->obj
,obj
) == 0) {
4721 for (i
= 0; i
< zsl
->level
; i
++) {
4722 if (update
[i
]->forward
[i
] != x
) break;
4723 update
[i
]->forward
[i
] = x
->forward
[i
];
4725 if (x
->forward
[0]) {
4726 x
->forward
[0]->backward
= (x
->backward
== zsl
->header
) ?
4729 zsl
->tail
= x
->backward
;
4732 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
4737 return 0; /* not found */
4739 return 0; /* not found */
4742 /* Delete all the elements with score between min and max from the skiplist.
4743 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
4744 * Note that this function takes the reference to the hash table view of the
4745 * sorted set, in order to remove the elements from the hash table too. */
4746 static unsigned long zslDeleteRange(zskiplist
*zsl
, double min
, double max
, dict
*dict
) {
4747 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4748 unsigned long removed
= 0;
4752 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4753 while (x
->forward
[i
] && x
->forward
[i
]->score
< min
)
4757 /* We may have multiple elements with the same score, what we need
4758 * is to find the element with both the right score and object. */
4760 while (x
&& x
->score
<= max
) {
4761 zskiplistNode
*next
;
4763 for (i
= 0; i
< zsl
->level
; i
++) {
4764 if (update
[i
]->forward
[i
] != x
) break;
4765 update
[i
]->forward
[i
] = x
->forward
[i
];
4767 if (x
->forward
[0]) {
4768 x
->forward
[0]->backward
= (x
->backward
== zsl
->header
) ?
4771 zsl
->tail
= x
->backward
;
4773 next
= x
->forward
[0];
4774 dictDelete(dict
,x
->obj
);
4776 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
4782 return removed
; /* not found */
4785 /* Find the first node having a score equal or greater than the specified one.
4786 * Returns NULL if there is no match. */
4787 static zskiplistNode
*zslFirstWithScore(zskiplist
*zsl
, double score
) {
4792 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4793 while (x
->forward
[i
] && x
->forward
[i
]->score
< score
)
4796 /* We may have multiple elements with the same score, what we need
4797 * is to find the element with both the right score and object. */
4798 return x
->forward
[0];
4801 /* The actual Z-commands implementations */
4803 /* This generic command implements both ZADD and ZINCRBY.
4804 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
4805 * the increment if the operation is a ZINCRBY (doincrement == 1). */
4806 static void zaddGenericCommand(redisClient
*c
, robj
*key
, robj
*ele
, double scoreval
, int doincrement
) {
4811 zsetobj
= lookupKeyWrite(c
->db
,key
);
4812 if (zsetobj
== NULL
) {
4813 zsetobj
= createZsetObject();
4814 dictAdd(c
->db
->dict
,key
,zsetobj
);
4817 if (zsetobj
->type
!= REDIS_ZSET
) {
4818 addReply(c
,shared
.wrongtypeerr
);
4824 /* Ok now since we implement both ZADD and ZINCRBY here the code
4825 * needs to handle the two different conditions. It's all about setting
4826 * '*score', that is, the new score to set, to the right value. */
4827 score
= zmalloc(sizeof(double));
4831 /* Read the old score. If the element was not present starts from 0 */
4832 de
= dictFind(zs
->dict
,ele
);
4834 double *oldscore
= dictGetEntryVal(de
);
4835 *score
= *oldscore
+ scoreval
;
4843 /* What follows is a simple remove and re-insert operation that is common
4844 * to both ZADD and ZINCRBY... */
4845 if (dictAdd(zs
->dict
,ele
,score
) == DICT_OK
) {
4846 /* case 1: New element */
4847 incrRefCount(ele
); /* added to hash */
4848 zslInsert(zs
->zsl
,*score
,ele
);
4849 incrRefCount(ele
); /* added to skiplist */
4852 addReplyDouble(c
,*score
);
4854 addReply(c
,shared
.cone
);
4859 /* case 2: Score update operation */
4860 de
= dictFind(zs
->dict
,ele
);
4861 redisAssert(de
!= NULL
);
4862 oldscore
= dictGetEntryVal(de
);
4863 if (*score
!= *oldscore
) {
4866 /* Remove and insert the element in the skip list with new score */
4867 deleted
= zslDelete(zs
->zsl
,*oldscore
,ele
);
4868 redisAssert(deleted
!= 0);
4869 zslInsert(zs
->zsl
,*score
,ele
);
4871 /* Update the score in the hash table */
4872 dictReplace(zs
->dict
,ele
,score
);
4878 addReplyDouble(c
,*score
);
4880 addReply(c
,shared
.czero
);
4884 static void zaddCommand(redisClient
*c
) {
4887 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
4888 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,0);
4891 static void zincrbyCommand(redisClient
*c
) {
4894 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
4895 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,1);
4898 static void zremCommand(redisClient
*c
) {
4902 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4903 if (zsetobj
== NULL
) {
4904 addReply(c
,shared
.czero
);
4910 if (zsetobj
->type
!= REDIS_ZSET
) {
4911 addReply(c
,shared
.wrongtypeerr
);
4915 de
= dictFind(zs
->dict
,c
->argv
[2]);
4917 addReply(c
,shared
.czero
);
4920 /* Delete from the skiplist */
4921 oldscore
= dictGetEntryVal(de
);
4922 deleted
= zslDelete(zs
->zsl
,*oldscore
,c
->argv
[2]);
4923 redisAssert(deleted
!= 0);
4925 /* Delete from the hash table */
4926 dictDelete(zs
->dict
,c
->argv
[2]);
4927 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
4929 addReply(c
,shared
.cone
);
4933 static void zremrangebyscoreCommand(redisClient
*c
) {
4934 double min
= strtod(c
->argv
[2]->ptr
,NULL
);
4935 double max
= strtod(c
->argv
[3]->ptr
,NULL
);
4939 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4940 if (zsetobj
== NULL
) {
4941 addReply(c
,shared
.czero
);
4945 if (zsetobj
->type
!= REDIS_ZSET
) {
4946 addReply(c
,shared
.wrongtypeerr
);
4950 deleted
= zslDeleteRange(zs
->zsl
,min
,max
,zs
->dict
);
4951 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
4952 server
.dirty
+= deleted
;
4953 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",deleted
));
4957 static void zrangeGenericCommand(redisClient
*c
, int reverse
) {
4959 int start
= atoi(c
->argv
[2]->ptr
);
4960 int end
= atoi(c
->argv
[3]->ptr
);
4963 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
4965 } else if (c
->argc
>= 5) {
4966 addReply(c
,shared
.syntaxerr
);
4970 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4972 addReply(c
,shared
.nullmultibulk
);
4974 if (o
->type
!= REDIS_ZSET
) {
4975 addReply(c
,shared
.wrongtypeerr
);
4977 zset
*zsetobj
= o
->ptr
;
4978 zskiplist
*zsl
= zsetobj
->zsl
;
4981 int llen
= zsl
->length
;
4985 /* convert negative indexes */
4986 if (start
< 0) start
= llen
+start
;
4987 if (end
< 0) end
= llen
+end
;
4988 if (start
< 0) start
= 0;
4989 if (end
< 0) end
= 0;
4991 /* indexes sanity checks */
4992 if (start
> end
|| start
>= llen
) {
4993 /* Out of range start or start > end result in empty list */
4994 addReply(c
,shared
.emptymultibulk
);
4997 if (end
>= llen
) end
= llen
-1;
4998 rangelen
= (end
-start
)+1;
5000 /* Return the result in form of a multi-bulk reply */
5006 ln
= zsl
->header
->forward
[0];
5008 ln
= ln
->forward
[0];
5011 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",
5012 withscores
? (rangelen
*2) : rangelen
));
5013 for (j
= 0; j
< rangelen
; j
++) {
5015 addReplyBulkLen(c
,ele
);
5017 addReply(c
,shared
.crlf
);
5019 addReplyDouble(c
,ln
->score
);
5020 ln
= reverse
? ln
->backward
: ln
->forward
[0];
5026 static void zrangeCommand(redisClient
*c
) {
5027 zrangeGenericCommand(c
,0);
5030 static void zrevrangeCommand(redisClient
*c
) {
5031 zrangeGenericCommand(c
,1);
5034 static void zrangebyscoreCommand(redisClient
*c
) {
5036 double min
= strtod(c
->argv
[2]->ptr
,NULL
);
5037 double max
= strtod(c
->argv
[3]->ptr
,NULL
);
5038 int offset
= 0, limit
= -1;
5040 if (c
->argc
!= 4 && c
->argc
!= 7) {
5042 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
5044 } else if (c
->argc
== 7 && strcasecmp(c
->argv
[4]->ptr
,"limit")) {
5045 addReply(c
,shared
.syntaxerr
);
5047 } else if (c
->argc
== 7) {
5048 offset
= atoi(c
->argv
[5]->ptr
);
5049 limit
= atoi(c
->argv
[6]->ptr
);
5050 if (offset
< 0) offset
= 0;
5053 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5055 addReply(c
,shared
.nullmultibulk
);
5057 if (o
->type
!= REDIS_ZSET
) {
5058 addReply(c
,shared
.wrongtypeerr
);
5060 zset
*zsetobj
= o
->ptr
;
5061 zskiplist
*zsl
= zsetobj
->zsl
;
5064 unsigned int rangelen
= 0;
5066 /* Get the first node with the score >= min */
5067 ln
= zslFirstWithScore(zsl
,min
);
5069 /* No element matching the speciifed interval */
5070 addReply(c
,shared
.emptymultibulk
);
5074 /* We don't know in advance how many matching elements there
5075 * are in the list, so we push this object that will represent
5076 * the multi-bulk length in the output buffer, and will "fix"
5078 lenobj
= createObject(REDIS_STRING
,NULL
);
5080 decrRefCount(lenobj
);
5082 while(ln
&& ln
->score
<= max
) {
5085 ln
= ln
->forward
[0];
5088 if (limit
== 0) break;
5090 addReplyBulkLen(c
,ele
);
5092 addReply(c
,shared
.crlf
);
5093 ln
= ln
->forward
[0];
5095 if (limit
> 0) limit
--;
5097 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%d\r\n",rangelen
);
5102 static void zcardCommand(redisClient
*c
) {
5106 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5108 addReply(c
,shared
.czero
);
5111 if (o
->type
!= REDIS_ZSET
) {
5112 addReply(c
,shared
.wrongtypeerr
);
5115 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",zs
->zsl
->length
));
5120 static void zscoreCommand(redisClient
*c
) {
5124 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5126 addReply(c
,shared
.nullbulk
);
5129 if (o
->type
!= REDIS_ZSET
) {
5130 addReply(c
,shared
.wrongtypeerr
);
5135 de
= dictFind(zs
->dict
,c
->argv
[2]);
5137 addReply(c
,shared
.nullbulk
);
5139 double *score
= dictGetEntryVal(de
);
5141 addReplyDouble(c
,*score
);
5147 /* ========================= Non type-specific commands ==================== */
5149 static void flushdbCommand(redisClient
*c
) {
5150 server
.dirty
+= dictSize(c
->db
->dict
);
5151 dictEmpty(c
->db
->dict
);
5152 dictEmpty(c
->db
->expires
);
5153 addReply(c
,shared
.ok
);
5156 static void flushallCommand(redisClient
*c
) {
5157 server
.dirty
+= emptyDb();
5158 addReply(c
,shared
.ok
);
5159 rdbSave(server
.dbfilename
);
5163 static redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
5164 redisSortOperation
*so
= zmalloc(sizeof(*so
));
5166 so
->pattern
= pattern
;
5170 /* Return the value associated to the key with a name obtained
5171 * substituting the first occurence of '*' in 'pattern' with 'subst' */
5172 static robj
*lookupKeyByPattern(redisDb
*db
, robj
*pattern
, robj
*subst
) {
5176 int prefixlen
, sublen
, postfixlen
;
5177 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
5181 char buf
[REDIS_SORTKEY_MAX
+1];
5184 /* If the pattern is "#" return the substitution object itself in order
5185 * to implement the "SORT ... GET #" feature. */
5186 spat
= pattern
->ptr
;
5187 if (spat
[0] == '#' && spat
[1] == '\0') {
5191 /* The substitution object may be specially encoded. If so we create
5192 * a decoded object on the fly. Otherwise getDecodedObject will just
5193 * increment the ref count, that we'll decrement later. */
5194 subst
= getDecodedObject(subst
);
5197 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
5198 p
= strchr(spat
,'*');
5200 decrRefCount(subst
);
5205 sublen
= sdslen(ssub
);
5206 postfixlen
= sdslen(spat
)-(prefixlen
+1);
5207 memcpy(keyname
.buf
,spat
,prefixlen
);
5208 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
5209 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
5210 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
5211 keyname
.len
= prefixlen
+sublen
+postfixlen
;
5213 initStaticStringObject(keyobj
,((char*)&keyname
)+(sizeof(long)*2))
5214 decrRefCount(subst
);
5216 /* printf("lookup '%s' => %p\n", keyname.buf,de); */
5217 return lookupKeyRead(db
,&keyobj
);
5220 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
5221 * the additional parameter is not standard but a BSD-specific we have to
5222 * pass sorting parameters via the global 'server' structure */
5223 static int sortCompare(const void *s1
, const void *s2
) {
5224 const redisSortObject
*so1
= s1
, *so2
= s2
;
5227 if (!server
.sort_alpha
) {
5228 /* Numeric sorting. Here it's trivial as we precomputed scores */
5229 if (so1
->u
.score
> so2
->u
.score
) {
5231 } else if (so1
->u
.score
< so2
->u
.score
) {
5237 /* Alphanumeric sorting */
5238 if (server
.sort_bypattern
) {
5239 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
5240 /* At least one compare object is NULL */
5241 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
5243 else if (so1
->u
.cmpobj
== NULL
)
5248 /* We have both the objects, use strcoll */
5249 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
5252 /* Compare elements directly */
5255 dec1
= getDecodedObject(so1
->obj
);
5256 dec2
= getDecodedObject(so2
->obj
);
5257 cmp
= strcoll(dec1
->ptr
,dec2
->ptr
);
5262 return server
.sort_desc
? -cmp
: cmp
;
5265 /* The SORT command is the most complex command in Redis. Warning: this code
5266 * is optimized for speed and a bit less for readability */
5267 static void sortCommand(redisClient
*c
) {
5270 int desc
= 0, alpha
= 0;
5271 int limit_start
= 0, limit_count
= -1, start
, end
;
5272 int j
, dontsort
= 0, vectorlen
;
5273 int getop
= 0; /* GET operation counter */
5274 robj
*sortval
, *sortby
= NULL
, *storekey
= NULL
;
5275 redisSortObject
*vector
; /* Resulting vector to sort */
5277 /* Lookup the key to sort. It must be of the right types */
5278 sortval
= lookupKeyRead(c
->db
,c
->argv
[1]);
5279 if (sortval
== NULL
) {
5280 addReply(c
,shared
.nullmultibulk
);
5283 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
&&
5284 sortval
->type
!= REDIS_ZSET
)
5286 addReply(c
,shared
.wrongtypeerr
);
5290 /* Create a list of operations to perform for every sorted element.
5291 * Operations can be GET/DEL/INCR/DECR */
5292 operations
= listCreate();
5293 listSetFreeMethod(operations
,zfree
);
5296 /* Now we need to protect sortval incrementing its count, in the future
5297 * SORT may have options able to overwrite/delete keys during the sorting
5298 * and the sorted key itself may get destroied */
5299 incrRefCount(sortval
);
5301 /* The SORT command has an SQL-alike syntax, parse it */
5302 while(j
< c
->argc
) {
5303 int leftargs
= c
->argc
-j
-1;
5304 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
5306 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
5308 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
5310 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
5311 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
5312 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
5314 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"store") && leftargs
>= 1) {
5315 storekey
= c
->argv
[j
+1];
5317 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
5318 sortby
= c
->argv
[j
+1];
5319 /* If the BY pattern does not contain '*', i.e. it is constant,
5320 * we don't need to sort nor to lookup the weight keys. */
5321 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
5323 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
5324 listAddNodeTail(operations
,createSortOperation(
5325 REDIS_SORT_GET
,c
->argv
[j
+1]));
5329 decrRefCount(sortval
);
5330 listRelease(operations
);
5331 addReply(c
,shared
.syntaxerr
);
5337 /* Load the sorting vector with all the objects to sort */
5338 switch(sortval
->type
) {
5339 case REDIS_LIST
: vectorlen
= listLength((list
*)sortval
->ptr
); break;
5340 case REDIS_SET
: vectorlen
= dictSize((dict
*)sortval
->ptr
); break;
5341 case REDIS_ZSET
: vectorlen
= dictSize(((zset
*)sortval
->ptr
)->dict
); break;
5342 default: vectorlen
= 0; redisAssert(0); /* Avoid GCC warning */
5344 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
5347 if (sortval
->type
== REDIS_LIST
) {
5348 list
*list
= sortval
->ptr
;
5352 while((ln
= listYield(list
))) {
5353 robj
*ele
= ln
->value
;
5354 vector
[j
].obj
= ele
;
5355 vector
[j
].u
.score
= 0;
5356 vector
[j
].u
.cmpobj
= NULL
;
5364 if (sortval
->type
== REDIS_SET
) {
5367 zset
*zs
= sortval
->ptr
;
5371 di
= dictGetIterator(set
);
5372 while((setele
= dictNext(di
)) != NULL
) {
5373 vector
[j
].obj
= dictGetEntryKey(setele
);
5374 vector
[j
].u
.score
= 0;
5375 vector
[j
].u
.cmpobj
= NULL
;
5378 dictReleaseIterator(di
);
5380 redisAssert(j
== vectorlen
);
5382 /* Now it's time to load the right scores in the sorting vector */
5383 if (dontsort
== 0) {
5384 for (j
= 0; j
< vectorlen
; j
++) {
5388 byval
= lookupKeyByPattern(c
->db
,sortby
,vector
[j
].obj
);
5389 if (!byval
|| byval
->type
!= REDIS_STRING
) continue;
5391 vector
[j
].u
.cmpobj
= getDecodedObject(byval
);
5393 if (byval
->encoding
== REDIS_ENCODING_RAW
) {
5394 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
5396 /* Don't need to decode the object if it's
5397 * integer-encoded (the only encoding supported) so
5398 * far. We can just cast it */
5399 if (byval
->encoding
== REDIS_ENCODING_INT
) {
5400 vector
[j
].u
.score
= (long)byval
->ptr
;
5402 redisAssert(1 != 1);
5407 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_RAW
)
5408 vector
[j
].u
.score
= strtod(vector
[j
].obj
->ptr
,NULL
);
5410 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_INT
)
5411 vector
[j
].u
.score
= (long) vector
[j
].obj
->ptr
;
5413 redisAssert(1 != 1);
5420 /* We are ready to sort the vector... perform a bit of sanity check
5421 * on the LIMIT option too. We'll use a partial version of quicksort. */
5422 start
= (limit_start
< 0) ? 0 : limit_start
;
5423 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
5424 if (start
>= vectorlen
) {
5425 start
= vectorlen
-1;
5428 if (end
>= vectorlen
) end
= vectorlen
-1;
5430 if (dontsort
== 0) {
5431 server
.sort_desc
= desc
;
5432 server
.sort_alpha
= alpha
;
5433 server
.sort_bypattern
= sortby
? 1 : 0;
5434 if (sortby
&& (start
!= 0 || end
!= vectorlen
-1))
5435 pqsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
, start
,end
);
5437 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
5440 /* Send command output to the output buffer, performing the specified
5441 * GET/DEL/INCR/DECR operations if any. */
5442 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
5443 if (storekey
== NULL
) {
5444 /* STORE option not specified, sent the sorting result to client */
5445 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
5446 for (j
= start
; j
<= end
; j
++) {
5449 addReplyBulkLen(c
,vector
[j
].obj
);
5450 addReply(c
,vector
[j
].obj
);
5451 addReply(c
,shared
.crlf
);
5453 listRewind(operations
);
5454 while((ln
= listYield(operations
))) {
5455 redisSortOperation
*sop
= ln
->value
;
5456 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
5459 if (sop
->type
== REDIS_SORT_GET
) {
5460 if (!val
|| val
->type
!= REDIS_STRING
) {
5461 addReply(c
,shared
.nullbulk
);
5463 addReplyBulkLen(c
,val
);
5465 addReply(c
,shared
.crlf
);
5468 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
5473 robj
*listObject
= createListObject();
5474 list
*listPtr
= (list
*) listObject
->ptr
;
5476 /* STORE option specified, set the sorting result as a List object */
5477 for (j
= start
; j
<= end
; j
++) {
5480 listAddNodeTail(listPtr
,vector
[j
].obj
);
5481 incrRefCount(vector
[j
].obj
);
5483 listRewind(operations
);
5484 while((ln
= listYield(operations
))) {
5485 redisSortOperation
*sop
= ln
->value
;
5486 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
5489 if (sop
->type
== REDIS_SORT_GET
) {
5490 if (!val
|| val
->type
!= REDIS_STRING
) {
5491 listAddNodeTail(listPtr
,createStringObject("",0));
5493 listAddNodeTail(listPtr
,val
);
5497 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
5501 if (dictReplace(c
->db
->dict
,storekey
,listObject
)) {
5502 incrRefCount(storekey
);
5504 /* Note: we add 1 because the DB is dirty anyway since even if the
5505 * SORT result is empty a new key is set and maybe the old content
5507 server
.dirty
+= 1+outputlen
;
5508 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",outputlen
));
5512 decrRefCount(sortval
);
5513 listRelease(operations
);
5514 for (j
= 0; j
< vectorlen
; j
++) {
5515 if (sortby
&& alpha
&& vector
[j
].u
.cmpobj
)
5516 decrRefCount(vector
[j
].u
.cmpobj
);
5521 /* Convert an amount of bytes into a human readable string in the form
5522 * of 100B, 2G, 100M, 4K, and so forth. */
5523 static void bytesToHuman(char *s
, unsigned long long n
) {
5528 sprintf(s
,"%lluB",n
);
5530 } else if (n
< (1024*1024)) {
5531 d
= (double)n
/(1024);
5532 sprintf(s
,"%.2fK",d
);
5533 } else if (n
< (1024LL*1024*1024)) {
5534 d
= (double)n
/(1024*1024);
5535 sprintf(s
,"%.2fM",d
);
5536 } else if (n
< (1024LL*1024*1024*1024)) {
5537 d
= (double)n
/(1024LL*1024*1024);
5538 sprintf(s
,"%.2fM",d
);
5542 /* Create the string returned by the INFO command. This is decoupled
5543 * by the INFO command itself as we need to report the same information
5544 * on memory corruption problems. */
5545 static sds
genRedisInfoString(void) {
5547 time_t uptime
= time(NULL
)-server
.stat_starttime
;
5551 bytesToHuman(hmem
,server
.usedmemory
);
5552 info
= sdscatprintf(sdsempty(),
5553 "redis_version:%s\r\n"
5555 "multiplexing_api:%s\r\n"
5556 "process_id:%ld\r\n"
5557 "uptime_in_seconds:%ld\r\n"
5558 "uptime_in_days:%ld\r\n"
5559 "connected_clients:%d\r\n"
5560 "connected_slaves:%d\r\n"
5561 "blocked_clients:%d\r\n"
5562 "used_memory:%zu\r\n"
5563 "used_memory_human:%s\r\n"
5564 "changes_since_last_save:%lld\r\n"
5565 "bgsave_in_progress:%d\r\n"
5566 "last_save_time:%ld\r\n"
5567 "bgrewriteaof_in_progress:%d\r\n"
5568 "total_connections_received:%lld\r\n"
5569 "total_commands_processed:%lld\r\n"
5573 (sizeof(long) == 8) ? "64" : "32",
5578 listLength(server
.clients
)-listLength(server
.slaves
),
5579 listLength(server
.slaves
),
5580 server
.blockedclients
,
5584 server
.bgsavechildpid
!= -1,
5586 server
.bgrewritechildpid
!= -1,
5587 server
.stat_numconnections
,
5588 server
.stat_numcommands
,
5589 server
.vm_enabled
!= 0,
5590 server
.masterhost
== NULL
? "master" : "slave"
5592 if (server
.masterhost
) {
5593 info
= sdscatprintf(info
,
5594 "master_host:%s\r\n"
5595 "master_port:%d\r\n"
5596 "master_link_status:%s\r\n"
5597 "master_last_io_seconds_ago:%d\r\n"
5600 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
5602 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1
5605 if (server
.vm_enabled
) {
5606 info
= sdscatprintf(info
,
5607 "vm_conf_max_memory:%llu\r\n"
5608 "vm_conf_page_size:%llu\r\n"
5609 "vm_conf_pages:%llu\r\n"
5610 "vm_stats_used_pages:%llu\r\n"
5611 "vm_stats_swapped_objects:%llu\r\n"
5612 "vm_stats_swappin_count:%llu\r\n"
5613 "vm_stats_swappout_count:%llu\r\n"
5614 "vm_stats_io_newjobs_len:%lu\r\n"
5615 "vm_stats_io_processing_len:%lu\r\n"
5616 "vm_stats_io_processed_len:%lu\r\n"
5617 "vm_stats_io_waiting_clients:%lu\r\n"
5618 ,(unsigned long long) server
.vm_max_memory
,
5619 (unsigned long long) server
.vm_page_size
,
5620 (unsigned long long) server
.vm_pages
,
5621 (unsigned long long) server
.vm_stats_used_pages
,
5622 (unsigned long long) server
.vm_stats_swapped_objects
,
5623 (unsigned long long) server
.vm_stats_swapins
,
5624 (unsigned long long) server
.vm_stats_swapouts
,
5625 (unsigned long) listLength(server
.io_newjobs
),
5626 (unsigned long) listLength(server
.io_processing
),
5627 (unsigned long) listLength(server
.io_processed
),
5628 (unsigned long) listLength(server
.io_clients
)
5631 for (j
= 0; j
< server
.dbnum
; j
++) {
5632 long long keys
, vkeys
;
5634 keys
= dictSize(server
.db
[j
].dict
);
5635 vkeys
= dictSize(server
.db
[j
].expires
);
5636 if (keys
|| vkeys
) {
5637 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
5644 static void infoCommand(redisClient
*c
) {
5645 sds info
= genRedisInfoString();
5646 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
5647 (unsigned long)sdslen(info
)));
5648 addReplySds(c
,info
);
5649 addReply(c
,shared
.crlf
);
5652 static void monitorCommand(redisClient
*c
) {
5653 /* ignore MONITOR if aleady slave or in monitor mode */
5654 if (c
->flags
& REDIS_SLAVE
) return;
5656 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
5658 listAddNodeTail(server
.monitors
,c
);
5659 addReply(c
,shared
.ok
);
5662 /* ================================= Expire ================================= */
5663 static int removeExpire(redisDb
*db
, robj
*key
) {
5664 if (dictDelete(db
->expires
,key
) == DICT_OK
) {
5671 static int setExpire(redisDb
*db
, robj
*key
, time_t when
) {
5672 if (dictAdd(db
->expires
,key
,(void*)when
) == DICT_ERR
) {
5680 /* Return the expire time of the specified key, or -1 if no expire
5681 * is associated with this key (i.e. the key is non volatile) */
5682 static time_t getExpire(redisDb
*db
, robj
*key
) {
5685 /* No expire? return ASAP */
5686 if (dictSize(db
->expires
) == 0 ||
5687 (de
= dictFind(db
->expires
,key
)) == NULL
) return -1;
5689 return (time_t) dictGetEntryVal(de
);
5692 static int expireIfNeeded(redisDb
*db
, robj
*key
) {
5696 /* No expire? return ASAP */
5697 if (dictSize(db
->expires
) == 0 ||
5698 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
5700 /* Lookup the expire */
5701 when
= (time_t) dictGetEntryVal(de
);
5702 if (time(NULL
) <= when
) return 0;
5704 /* Delete the key */
5705 dictDelete(db
->expires
,key
);
5706 return dictDelete(db
->dict
,key
) == DICT_OK
;
5709 static int deleteIfVolatile(redisDb
*db
, robj
*key
) {
5712 /* No expire? return ASAP */
5713 if (dictSize(db
->expires
) == 0 ||
5714 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
5716 /* Delete the key */
5718 dictDelete(db
->expires
,key
);
5719 return dictDelete(db
->dict
,key
) == DICT_OK
;
5722 static void expireGenericCommand(redisClient
*c
, robj
*key
, time_t seconds
) {
5725 de
= dictFind(c
->db
->dict
,key
);
5727 addReply(c
,shared
.czero
);
5731 if (deleteKey(c
->db
,key
)) server
.dirty
++;
5732 addReply(c
, shared
.cone
);
5735 time_t when
= time(NULL
)+seconds
;
5736 if (setExpire(c
->db
,key
,when
)) {
5737 addReply(c
,shared
.cone
);
5740 addReply(c
,shared
.czero
);
5746 static void expireCommand(redisClient
*c
) {
5747 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10));
5750 static void expireatCommand(redisClient
*c
) {
5751 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10)-time(NULL
));
5754 static void ttlCommand(redisClient
*c
) {
5758 expire
= getExpire(c
->db
,c
->argv
[1]);
5760 ttl
= (int) (expire
-time(NULL
));
5761 if (ttl
< 0) ttl
= -1;
5763 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",ttl
));
5766 /* ================================ MULTI/EXEC ============================== */
5768 /* Client state initialization for MULTI/EXEC */
5769 static void initClientMultiState(redisClient
*c
) {
5770 c
->mstate
.commands
= NULL
;
5771 c
->mstate
.count
= 0;
5774 /* Release all the resources associated with MULTI/EXEC state */
5775 static void freeClientMultiState(redisClient
*c
) {
5778 for (j
= 0; j
< c
->mstate
.count
; j
++) {
5780 multiCmd
*mc
= c
->mstate
.commands
+j
;
5782 for (i
= 0; i
< mc
->argc
; i
++)
5783 decrRefCount(mc
->argv
[i
]);
5786 zfree(c
->mstate
.commands
);
5789 /* Add a new command into the MULTI commands queue */
5790 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
) {
5794 c
->mstate
.commands
= zrealloc(c
->mstate
.commands
,
5795 sizeof(multiCmd
)*(c
->mstate
.count
+1));
5796 mc
= c
->mstate
.commands
+c
->mstate
.count
;
5799 mc
->argv
= zmalloc(sizeof(robj
*)*c
->argc
);
5800 memcpy(mc
->argv
,c
->argv
,sizeof(robj
*)*c
->argc
);
5801 for (j
= 0; j
< c
->argc
; j
++)
5802 incrRefCount(mc
->argv
[j
]);
5806 static void multiCommand(redisClient
*c
) {
5807 c
->flags
|= REDIS_MULTI
;
5808 addReply(c
,shared
.ok
);
5811 static void execCommand(redisClient
*c
) {
5816 if (!(c
->flags
& REDIS_MULTI
)) {
5817 addReplySds(c
,sdsnew("-ERR EXEC without MULTI\r\n"));
5821 orig_argv
= c
->argv
;
5822 orig_argc
= c
->argc
;
5823 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->mstate
.count
));
5824 for (j
= 0; j
< c
->mstate
.count
; j
++) {
5825 c
->argc
= c
->mstate
.commands
[j
].argc
;
5826 c
->argv
= c
->mstate
.commands
[j
].argv
;
5827 call(c
,c
->mstate
.commands
[j
].cmd
);
5829 c
->argv
= orig_argv
;
5830 c
->argc
= orig_argc
;
5831 freeClientMultiState(c
);
5832 initClientMultiState(c
);
5833 c
->flags
&= (~REDIS_MULTI
);
5836 /* =========================== Blocking Operations ========================= */
5838 /* Currently Redis blocking operations support is limited to list POP ops,
5839 * so the current implementation is not fully generic, but it is also not
5840 * completely specific so it will not require a rewrite to support new
5841 * kind of blocking operations in the future.
5843 * Still it's important to note that list blocking operations can be already
5844 * used as a notification mechanism in order to implement other blocking
5845 * operations at application level, so there must be a very strong evidence
5846 * of usefulness and generality before new blocking operations are implemented.
5848 * This is how the current blocking POP works, we use BLPOP as example:
5849 * - If the user calls BLPOP and the key exists and contains a non empty list
5850 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
5851 * if there is not to block.
5852 * - If instead BLPOP is called and the key does not exists or the list is
5853 * empty we need to block. In order to do so we remove the notification for
5854 * new data to read in the client socket (so that we'll not serve new
5855 * requests if the blocking request is not served). Also we put the client
5856 * in a dictionary (db->blockingkeys) mapping keys to a list of clients
5857 * blocking for this keys.
5858 * - If a PUSH operation against a key with blocked clients waiting is
5859 * performed, we serve the first in the list: basically instead to push
5860 * the new element inside the list we return it to the (first / oldest)
5861 * blocking client, unblock the client, and remove it form the list.
5863 * The above comment and the source code should be enough in order to understand
5864 * the implementation and modify / fix it later.
5867 /* Set a client in blocking mode for the specified key, with the specified
5869 static void blockForKeys(redisClient
*c
, robj
**keys
, int numkeys
, time_t timeout
) {
5874 c
->blockingkeys
= zmalloc(sizeof(robj
*)*numkeys
);
5875 c
->blockingkeysnum
= numkeys
;
5876 c
->blockingto
= timeout
;
5877 for (j
= 0; j
< numkeys
; j
++) {
5878 /* Add the key in the client structure, to map clients -> keys */
5879 c
->blockingkeys
[j
] = keys
[j
];
5880 incrRefCount(keys
[j
]);
5882 /* And in the other "side", to map keys -> clients */
5883 de
= dictFind(c
->db
->blockingkeys
,keys
[j
]);
5887 /* For every key we take a list of clients blocked for it */
5889 retval
= dictAdd(c
->db
->blockingkeys
,keys
[j
],l
);
5890 incrRefCount(keys
[j
]);
5891 assert(retval
== DICT_OK
);
5893 l
= dictGetEntryVal(de
);
5895 listAddNodeTail(l
,c
);
5897 /* Mark the client as a blocked client */
5898 c
->flags
|= REDIS_BLOCKED
;
5899 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
5900 server
.blockedclients
++;
5903 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
5904 static void unblockClient(redisClient
*c
) {
5909 assert(c
->blockingkeys
!= NULL
);
5910 /* The client may wait for multiple keys, so unblock it for every key. */
5911 for (j
= 0; j
< c
->blockingkeysnum
; j
++) {
5912 /* Remove this client from the list of clients waiting for this key. */
5913 de
= dictFind(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
5915 l
= dictGetEntryVal(de
);
5916 listDelNode(l
,listSearchKey(l
,c
));
5917 /* If the list is empty we need to remove it to avoid wasting memory */
5918 if (listLength(l
) == 0)
5919 dictDelete(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
5920 decrRefCount(c
->blockingkeys
[j
]);
5922 /* Cleanup the client structure */
5923 zfree(c
->blockingkeys
);
5924 c
->blockingkeys
= NULL
;
5925 c
->flags
&= (~REDIS_BLOCKED
);
5926 server
.blockedclients
--;
5927 /* Ok now we are ready to get read events from socket, note that we
5928 * can't trap errors here as it's possible that unblockClients() is
5929 * called from freeClient() itself, and the only thing we can do
5930 * if we failed to register the READABLE event is to kill the client.
5931 * Still the following function should never fail in the real world as
5932 * we are sure the file descriptor is sane, and we exit on out of mem. */
5933 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
, readQueryFromClient
, c
);
5934 /* As a final step we want to process data if there is some command waiting
5935 * in the input buffer. Note that this is safe even if unblockClient()
5936 * gets called from freeClient() because freeClient() will be smart
5937 * enough to call this function *after* c->querybuf was set to NULL. */
5938 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0) processInputBuffer(c
);
5941 /* This should be called from any function PUSHing into lists.
5942 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
5943 * 'ele' is the element pushed.
5945 * If the function returns 0 there was no client waiting for a list push
5948 * If the function returns 1 there was a client waiting for a list push
5949 * against this key, the element was passed to this client thus it's not
5950 * needed to actually add it to the list and the caller should return asap. */
5951 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
) {
5952 struct dictEntry
*de
;
5953 redisClient
*receiver
;
5957 de
= dictFind(c
->db
->blockingkeys
,key
);
5958 if (de
== NULL
) return 0;
5959 l
= dictGetEntryVal(de
);
5962 receiver
= ln
->value
;
5964 addReplySds(receiver
,sdsnew("*2\r\n"));
5965 addReplyBulkLen(receiver
,key
);
5966 addReply(receiver
,key
);
5967 addReply(receiver
,shared
.crlf
);
5968 addReplyBulkLen(receiver
,ele
);
5969 addReply(receiver
,ele
);
5970 addReply(receiver
,shared
.crlf
);
5971 unblockClient(receiver
);
5975 /* Blocking RPOP/LPOP */
5976 static void blockingPopGenericCommand(redisClient
*c
, int where
) {
5981 for (j
= 1; j
< c
->argc
-1; j
++) {
5982 o
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
5984 if (o
->type
!= REDIS_LIST
) {
5985 addReply(c
,shared
.wrongtypeerr
);
5988 list
*list
= o
->ptr
;
5989 if (listLength(list
) != 0) {
5990 /* If the list contains elements fall back to the usual
5991 * non-blocking POP operation */
5992 robj
*argv
[2], **orig_argv
;
5995 /* We need to alter the command arguments before to call
5996 * popGenericCommand() as the command takes a single key. */
5997 orig_argv
= c
->argv
;
5998 orig_argc
= c
->argc
;
5999 argv
[1] = c
->argv
[j
];
6003 /* Also the return value is different, we need to output
6004 * the multi bulk reply header and the key name. The
6005 * "real" command will add the last element (the value)
6006 * for us. If this souds like an hack to you it's just
6007 * because it is... */
6008 addReplySds(c
,sdsnew("*2\r\n"));
6009 addReplyBulkLen(c
,argv
[1]);
6010 addReply(c
,argv
[1]);
6011 addReply(c
,shared
.crlf
);
6012 popGenericCommand(c
,where
);
6014 /* Fix the client structure with the original stuff */
6015 c
->argv
= orig_argv
;
6016 c
->argc
= orig_argc
;
6022 /* If the list is empty or the key does not exists we must block */
6023 timeout
= strtol(c
->argv
[c
->argc
-1]->ptr
,NULL
,10);
6024 if (timeout
> 0) timeout
+= time(NULL
);
6025 blockForKeys(c
,c
->argv
+1,c
->argc
-2,timeout
);
6028 static void blpopCommand(redisClient
*c
) {
6029 blockingPopGenericCommand(c
,REDIS_HEAD
);
6032 static void brpopCommand(redisClient
*c
) {
6033 blockingPopGenericCommand(c
,REDIS_TAIL
);
6036 /* =============================== Replication ============================= */
6038 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6039 ssize_t nwritten
, ret
= size
;
6040 time_t start
= time(NULL
);
6044 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
6045 nwritten
= write(fd
,ptr
,size
);
6046 if (nwritten
== -1) return -1;
6050 if ((time(NULL
)-start
) > timeout
) {
6058 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6059 ssize_t nread
, totread
= 0;
6060 time_t start
= time(NULL
);
6064 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
6065 nread
= read(fd
,ptr
,size
);
6066 if (nread
== -1) return -1;
6071 if ((time(NULL
)-start
) > timeout
) {
6079 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6086 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
6089 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
6100 static void syncCommand(redisClient
*c
) {
6101 /* ignore SYNC if aleady slave or in monitor mode */
6102 if (c
->flags
& REDIS_SLAVE
) return;
6104 /* SYNC can't be issued when the server has pending data to send to
6105 * the client about already issued commands. We need a fresh reply
6106 * buffer registering the differences between the BGSAVE and the current
6107 * dataset, so that we can copy to other slaves if needed. */
6108 if (listLength(c
->reply
) != 0) {
6109 addReplySds(c
,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
6113 redisLog(REDIS_NOTICE
,"Slave ask for synchronization");
6114 /* Here we need to check if there is a background saving operation
6115 * in progress, or if it is required to start one */
6116 if (server
.bgsavechildpid
!= -1) {
6117 /* Ok a background save is in progress. Let's check if it is a good
6118 * one for replication, i.e. if there is another slave that is
6119 * registering differences since the server forked to save */
6123 listRewind(server
.slaves
);
6124 while((ln
= listYield(server
.slaves
))) {
6126 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) break;
6129 /* Perfect, the server is already registering differences for
6130 * another slave. Set the right state, and copy the buffer. */
6131 listRelease(c
->reply
);
6132 c
->reply
= listDup(slave
->reply
);
6133 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6134 redisLog(REDIS_NOTICE
,"Waiting for end of BGSAVE for SYNC");
6136 /* No way, we need to wait for the next BGSAVE in order to
6137 * register differences */
6138 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
6139 redisLog(REDIS_NOTICE
,"Waiting for next BGSAVE for SYNC");
6142 /* Ok we don't have a BGSAVE in progress, let's start one */
6143 redisLog(REDIS_NOTICE
,"Starting BGSAVE for SYNC");
6144 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
6145 redisLog(REDIS_NOTICE
,"Replication failed, can't BGSAVE");
6146 addReplySds(c
,sdsnew("-ERR Unalbe to perform background save\r\n"));
6149 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6152 c
->flags
|= REDIS_SLAVE
;
6154 listAddNodeTail(server
.slaves
,c
);
6158 static void sendBulkToSlave(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
6159 redisClient
*slave
= privdata
;
6161 REDIS_NOTUSED(mask
);
6162 char buf
[REDIS_IOBUF_LEN
];
6163 ssize_t nwritten
, buflen
;
6165 if (slave
->repldboff
== 0) {
6166 /* Write the bulk write count before to transfer the DB. In theory here
6167 * we don't know how much room there is in the output buffer of the
6168 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
6169 * operations) will never be smaller than the few bytes we need. */
6172 bulkcount
= sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
6174 if (write(fd
,bulkcount
,sdslen(bulkcount
)) != (signed)sdslen(bulkcount
))
6182 lseek(slave
->repldbfd
,slave
->repldboff
,SEEK_SET
);
6183 buflen
= read(slave
->repldbfd
,buf
,REDIS_IOBUF_LEN
);
6185 redisLog(REDIS_WARNING
,"Read error sending DB to slave: %s",
6186 (buflen
== 0) ? "premature EOF" : strerror(errno
));
6190 if ((nwritten
= write(fd
,buf
,buflen
)) == -1) {
6191 redisLog(REDIS_VERBOSE
,"Write error sending DB to slave: %s",
6196 slave
->repldboff
+= nwritten
;
6197 if (slave
->repldboff
== slave
->repldbsize
) {
6198 close(slave
->repldbfd
);
6199 slave
->repldbfd
= -1;
6200 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
6201 slave
->replstate
= REDIS_REPL_ONLINE
;
6202 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
,
6203 sendReplyToClient
, slave
) == AE_ERR
) {
6207 addReplySds(slave
,sdsempty());
6208 redisLog(REDIS_NOTICE
,"Synchronization with slave succeeded");
6212 /* This function is called at the end of every backgrond saving.
6213 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
6214 * otherwise REDIS_ERR is passed to the function.
6216 * The goal of this function is to handle slaves waiting for a successful
6217 * background saving in order to perform non-blocking synchronization. */
6218 static void updateSlavesWaitingBgsave(int bgsaveerr
) {
6220 int startbgsave
= 0;
6222 listRewind(server
.slaves
);
6223 while((ln
= listYield(server
.slaves
))) {
6224 redisClient
*slave
= ln
->value
;
6226 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) {
6228 slave
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6229 } else if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) {
6230 struct redis_stat buf
;
6232 if (bgsaveerr
!= REDIS_OK
) {
6234 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE child returned an error");
6237 if ((slave
->repldbfd
= open(server
.dbfilename
,O_RDONLY
)) == -1 ||
6238 redis_fstat(slave
->repldbfd
,&buf
) == -1) {
6240 redisLog(REDIS_WARNING
,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno
));
6243 slave
->repldboff
= 0;
6244 slave
->repldbsize
= buf
.st_size
;
6245 slave
->replstate
= REDIS_REPL_SEND_BULK
;
6246 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
6247 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
, sendBulkToSlave
, slave
) == AE_ERR
) {
6254 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
6255 listRewind(server
.slaves
);
6256 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE failed");
6257 while((ln
= listYield(server
.slaves
))) {
6258 redisClient
*slave
= ln
->value
;
6260 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
)
6267 static int syncWithMaster(void) {
6268 char buf
[1024], tmpfile
[256], authcmd
[1024];
6270 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
6274 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
6279 /* AUTH with the master if required. */
6280 if(server
.masterauth
) {
6281 snprintf(authcmd
, 1024, "AUTH %s\r\n", server
.masterauth
);
6282 if (syncWrite(fd
, authcmd
, strlen(server
.masterauth
)+7, 5) == -1) {
6284 redisLog(REDIS_WARNING
,"Unable to AUTH to MASTER: %s",
6288 /* Read the AUTH result. */
6289 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
6291 redisLog(REDIS_WARNING
,"I/O error reading auth result from MASTER: %s",
6295 if (buf
[0] != '+') {
6297 redisLog(REDIS_WARNING
,"Cannot AUTH to MASTER, is the masterauth password correct?");
6302 /* Issue the SYNC command */
6303 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
6305 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
6309 /* Read the bulk write count */
6310 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
6312 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
6316 if (buf
[0] != '$') {
6318 redisLog(REDIS_WARNING
,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
6321 dumpsize
= atoi(buf
+1);
6322 redisLog(REDIS_NOTICE
,"Receiving %d bytes data dump from MASTER",dumpsize
);
6323 /* Read the bulk write data on a temp file */
6324 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
6325 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
,0644);
6328 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
6332 int nread
, nwritten
;
6334 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
6336 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
6342 nwritten
= write(dfd
,buf
,nread
);
6343 if (nwritten
== -1) {
6344 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
6352 if (rename(tmpfile
,server
.dbfilename
) == -1) {
6353 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
6359 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
6360 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
6364 server
.master
= createClient(fd
);
6365 server
.master
->flags
|= REDIS_MASTER
;
6366 server
.master
->authenticated
= 1;
6367 server
.replstate
= REDIS_REPL_CONNECTED
;
6371 static void slaveofCommand(redisClient
*c
) {
6372 if (!strcasecmp(c
->argv
[1]->ptr
,"no") &&
6373 !strcasecmp(c
->argv
[2]->ptr
,"one")) {
6374 if (server
.masterhost
) {
6375 sdsfree(server
.masterhost
);
6376 server
.masterhost
= NULL
;
6377 if (server
.master
) freeClient(server
.master
);
6378 server
.replstate
= REDIS_REPL_NONE
;
6379 redisLog(REDIS_NOTICE
,"MASTER MODE enabled (user request)");
6382 sdsfree(server
.masterhost
);
6383 server
.masterhost
= sdsdup(c
->argv
[1]->ptr
);
6384 server
.masterport
= atoi(c
->argv
[2]->ptr
);
6385 if (server
.master
) freeClient(server
.master
);
6386 server
.replstate
= REDIS_REPL_CONNECT
;
6387 redisLog(REDIS_NOTICE
,"SLAVE OF %s:%d enabled (user request)",
6388 server
.masterhost
, server
.masterport
);
6390 addReply(c
,shared
.ok
);
6393 /* ============================ Maxmemory directive ======================== */
6395 /* Try to free one object form the pre-allocated objects free list.
6396 * This is useful under low mem conditions as by default we take 1 million
6397 * free objects allocated. On success REDIS_OK is returned, otherwise
6399 static int tryFreeOneObjectFromFreelist(void) {
6402 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
6403 if (listLength(server
.objfreelist
)) {
6404 listNode
*head
= listFirst(server
.objfreelist
);
6405 o
= listNodeValue(head
);
6406 listDelNode(server
.objfreelist
,head
);
6407 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
6411 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
6416 /* This function gets called when 'maxmemory' is set on the config file to limit
6417 * the max memory used by the server, and we are out of memory.
6418 * This function will try to, in order:
6420 * - Free objects from the free list
6421 * - Try to remove keys with an EXPIRE set
6423 * It is not possible to free enough memory to reach used-memory < maxmemory
6424 * the server will start refusing commands that will enlarge even more the
6427 static void freeMemoryIfNeeded(void) {
6428 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
6429 int j
, k
, freed
= 0;
6431 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
6432 for (j
= 0; j
< server
.dbnum
; j
++) {
6434 robj
*minkey
= NULL
;
6435 struct dictEntry
*de
;
6437 if (dictSize(server
.db
[j
].expires
)) {
6439 /* From a sample of three keys drop the one nearest to
6440 * the natural expire */
6441 for (k
= 0; k
< 3; k
++) {
6444 de
= dictGetRandomKey(server
.db
[j
].expires
);
6445 t
= (time_t) dictGetEntryVal(de
);
6446 if (minttl
== -1 || t
< minttl
) {
6447 minkey
= dictGetEntryKey(de
);
6451 deleteKey(server
.db
+j
,minkey
);
6454 if (!freed
) return; /* nothing to free... */
6458 /* ============================== Append Only file ========================== */
6460 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
6461 sds buf
= sdsempty();
6467 /* The DB this command was targetting is not the same as the last command
6468 * we appendend. To issue a SELECT command is needed. */
6469 if (dictid
!= server
.appendseldb
) {
6472 snprintf(seldb
,sizeof(seldb
),"%d",dictid
);
6473 buf
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
6474 (unsigned long)strlen(seldb
),seldb
);
6475 server
.appendseldb
= dictid
;
6478 /* "Fix" the argv vector if the command is EXPIRE. We want to translate
6479 * EXPIREs into EXPIREATs calls */
6480 if (cmd
->proc
== expireCommand
) {
6483 tmpargv
[0] = createStringObject("EXPIREAT",8);
6484 tmpargv
[1] = argv
[1];
6485 incrRefCount(argv
[1]);
6486 when
= time(NULL
)+strtol(argv
[2]->ptr
,NULL
,10);
6487 tmpargv
[2] = createObject(REDIS_STRING
,
6488 sdscatprintf(sdsempty(),"%ld",when
));
6492 /* Append the actual command */
6493 buf
= sdscatprintf(buf
,"*%d\r\n",argc
);
6494 for (j
= 0; j
< argc
; j
++) {
6497 o
= getDecodedObject(o
);
6498 buf
= sdscatprintf(buf
,"$%lu\r\n",(unsigned long)sdslen(o
->ptr
));
6499 buf
= sdscatlen(buf
,o
->ptr
,sdslen(o
->ptr
));
6500 buf
= sdscatlen(buf
,"\r\n",2);
6504 /* Free the objects from the modified argv for EXPIREAT */
6505 if (cmd
->proc
== expireCommand
) {
6506 for (j
= 0; j
< 3; j
++)
6507 decrRefCount(argv
[j
]);
6510 /* We want to perform a single write. This should be guaranteed atomic
6511 * at least if the filesystem we are writing is a real physical one.
6512 * While this will save us against the server being killed I don't think
6513 * there is much to do about the whole server stopping for power problems
6515 nwritten
= write(server
.appendfd
,buf
,sdslen(buf
));
6516 if (nwritten
!= (signed)sdslen(buf
)) {
6517 /* Ooops, we are in troubles. The best thing to do for now is
6518 * to simply exit instead to give the illusion that everything is
6519 * working as expected. */
6520 if (nwritten
== -1) {
6521 redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
));
6523 redisLog(REDIS_WARNING
,"Exiting on short write while writing to the append-only file: %s",strerror(errno
));
6527 /* If a background append only file rewriting is in progress we want to
6528 * accumulate the differences between the child DB and the current one
6529 * in a buffer, so that when the child process will do its work we
6530 * can append the differences to the new append only file. */
6531 if (server
.bgrewritechildpid
!= -1)
6532 server
.bgrewritebuf
= sdscatlen(server
.bgrewritebuf
,buf
,sdslen(buf
));
6536 if (server
.appendfsync
== APPENDFSYNC_ALWAYS
||
6537 (server
.appendfsync
== APPENDFSYNC_EVERYSEC
&&
6538 now
-server
.lastfsync
> 1))
6540 fsync(server
.appendfd
); /* Let's try to get this data on the disk */
6541 server
.lastfsync
= now
;
6545 /* In Redis commands are always executed in the context of a client, so in
6546 * order to load the append only file we need to create a fake client. */
6547 static struct redisClient
*createFakeClient(void) {
6548 struct redisClient
*c
= zmalloc(sizeof(*c
));
6552 c
->querybuf
= sdsempty();
6556 /* We set the fake client as a slave waiting for the synchronization
6557 * so that Redis will not try to send replies to this client. */
6558 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
6559 c
->reply
= listCreate();
6560 listSetFreeMethod(c
->reply
,decrRefCount
);
6561 listSetDupMethod(c
->reply
,dupClientReplyValue
);
6565 static void freeFakeClient(struct redisClient
*c
) {
6566 sdsfree(c
->querybuf
);
6567 listRelease(c
->reply
);
6571 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
6572 * error (the append only file is zero-length) REDIS_ERR is returned. On
6573 * fatal error an error message is logged and the program exists. */
6574 int loadAppendOnlyFile(char *filename
) {
6575 struct redisClient
*fakeClient
;
6576 FILE *fp
= fopen(filename
,"r");
6577 struct redis_stat sb
;
6578 unsigned long long loadedkeys
= 0;
6580 if (redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0)
6584 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
6588 fakeClient
= createFakeClient();
6595 struct redisCommand
*cmd
;
6597 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
6603 if (buf
[0] != '*') goto fmterr
;
6605 argv
= zmalloc(sizeof(robj
*)*argc
);
6606 for (j
= 0; j
< argc
; j
++) {
6607 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
6608 if (buf
[0] != '$') goto fmterr
;
6609 len
= strtol(buf
+1,NULL
,10);
6610 argsds
= sdsnewlen(NULL
,len
);
6611 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
6612 argv
[j
] = createObject(REDIS_STRING
,argsds
);
6613 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
6616 /* Command lookup */
6617 cmd
= lookupCommand(argv
[0]->ptr
);
6619 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
6622 /* Try object sharing and encoding */
6623 if (server
.shareobjects
) {
6625 for(j
= 1; j
< argc
; j
++)
6626 argv
[j
] = tryObjectSharing(argv
[j
]);
6628 if (cmd
->flags
& REDIS_CMD_BULK
)
6629 tryObjectEncoding(argv
[argc
-1]);
6630 /* Run the command in the context of a fake client */
6631 fakeClient
->argc
= argc
;
6632 fakeClient
->argv
= argv
;
6633 cmd
->proc(fakeClient
);
6634 /* Discard the reply objects list from the fake client */
6635 while(listLength(fakeClient
->reply
))
6636 listDelNode(fakeClient
->reply
,listFirst(fakeClient
->reply
));
6637 /* Clean up, ready for the next command */
6638 for (j
= 0; j
< argc
; j
++) decrRefCount(argv
[j
]);
6640 /* Handle swapping while loading big datasets when VM is on */
6642 if (server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
6643 while (zmalloc_used_memory() > server
.vm_max_memory
) {
6644 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
6649 freeFakeClient(fakeClient
);
6654 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
6656 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
6660 redisLog(REDIS_WARNING
,"Bad file format reading the append only file");
6664 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
6665 static int fwriteBulk(FILE *fp
, robj
*obj
) {
6669 if (obj
->storage
== REDIS_VM_MEMORY
&& obj
->encoding
!= REDIS_ENCODING_RAW
){
6670 obj
= getDecodedObject(obj
);
6673 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(long)sdslen(obj
->ptr
));
6674 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) goto err
;
6675 if (sdslen(obj
->ptr
) && fwrite(obj
->ptr
,sdslen(obj
->ptr
),1,fp
) == 0)
6677 if (fwrite("\r\n",2,1,fp
) == 0) goto err
;
6678 if (decrrc
) decrRefCount(obj
);
6681 if (decrrc
) decrRefCount(obj
);
6685 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
6686 static int fwriteBulkDouble(FILE *fp
, double d
) {
6687 char buf
[128], dbuf
[128];
6689 snprintf(dbuf
,sizeof(dbuf
),"%.17g\r\n",d
);
6690 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(dbuf
)-2);
6691 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
6692 if (fwrite(dbuf
,strlen(dbuf
),1,fp
) == 0) return 0;
6696 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
6697 static int fwriteBulkLong(FILE *fp
, long l
) {
6698 char buf
[128], lbuf
[128];
6700 snprintf(lbuf
,sizeof(lbuf
),"%ld\r\n",l
);
6701 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(lbuf
)-2);
6702 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
6703 if (fwrite(lbuf
,strlen(lbuf
),1,fp
) == 0) return 0;
6707 /* Write a sequence of commands able to fully rebuild the dataset into
6708 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
6709 static int rewriteAppendOnlyFile(char *filename
) {
6710 dictIterator
*di
= NULL
;
6715 time_t now
= time(NULL
);
6717 /* Note that we have to use a different temp name here compared to the
6718 * one used by rewriteAppendOnlyFileBackground() function. */
6719 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
6720 fp
= fopen(tmpfile
,"w");
6722 redisLog(REDIS_WARNING
, "Failed rewriting the append only file: %s", strerror(errno
));
6725 for (j
= 0; j
< server
.dbnum
; j
++) {
6726 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
6727 redisDb
*db
= server
.db
+j
;
6729 if (dictSize(d
) == 0) continue;
6730 di
= dictGetIterator(d
);
6736 /* SELECT the new DB */
6737 if (fwrite(selectcmd
,sizeof(selectcmd
)-1,1,fp
) == 0) goto werr
;
6738 if (fwriteBulkLong(fp
,j
) == 0) goto werr
;
6740 /* Iterate this DB writing every entry */
6741 while((de
= dictNext(di
)) != NULL
) {
6746 key
= dictGetEntryKey(de
);
6747 /* If the value for this key is swapped, load a preview in memory.
6748 * We use a "swapped" flag to remember if we need to free the
6749 * value object instead to just increment the ref count anyway
6750 * in order to avoid copy-on-write of pages if we are forked() */
6751 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
6752 key
->storage
== REDIS_VM_SWAPPING
) {
6753 o
= dictGetEntryVal(de
);
6756 o
= vmPreviewObject(key
);
6759 expiretime
= getExpire(db
,key
);
6761 /* Save the key and associated value */
6762 if (o
->type
== REDIS_STRING
) {
6763 /* Emit a SET command */
6764 char cmd
[]="*3\r\n$3\r\nSET\r\n";
6765 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6767 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6768 if (fwriteBulk(fp
,o
) == 0) goto werr
;
6769 } else if (o
->type
== REDIS_LIST
) {
6770 /* Emit the RPUSHes needed to rebuild the list */
6771 list
*list
= o
->ptr
;
6775 while((ln
= listYield(list
))) {
6776 char cmd
[]="*3\r\n$5\r\nRPUSH\r\n";
6777 robj
*eleobj
= listNodeValue(ln
);
6779 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6780 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6781 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6783 } else if (o
->type
== REDIS_SET
) {
6784 /* Emit the SADDs needed to rebuild the set */
6786 dictIterator
*di
= dictGetIterator(set
);
6789 while((de
= dictNext(di
)) != NULL
) {
6790 char cmd
[]="*3\r\n$4\r\nSADD\r\n";
6791 robj
*eleobj
= dictGetEntryKey(de
);
6793 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6794 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6795 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6797 dictReleaseIterator(di
);
6798 } else if (o
->type
== REDIS_ZSET
) {
6799 /* Emit the ZADDs needed to rebuild the sorted set */
6801 dictIterator
*di
= dictGetIterator(zs
->dict
);
6804 while((de
= dictNext(di
)) != NULL
) {
6805 char cmd
[]="*4\r\n$4\r\nZADD\r\n";
6806 robj
*eleobj
= dictGetEntryKey(de
);
6807 double *score
= dictGetEntryVal(de
);
6809 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6810 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6811 if (fwriteBulkDouble(fp
,*score
) == 0) goto werr
;
6812 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6814 dictReleaseIterator(di
);
6816 redisAssert(0 != 0);
6818 /* Save the expire time */
6819 if (expiretime
!= -1) {
6820 char cmd
[]="*3\r\n$8\r\nEXPIREAT\r\n";
6821 /* If this key is already expired skip it */
6822 if (expiretime
< now
) continue;
6823 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6824 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6825 if (fwriteBulkLong(fp
,expiretime
) == 0) goto werr
;
6827 if (swapped
) decrRefCount(o
);
6829 dictReleaseIterator(di
);
6832 /* Make sure data will not remain on the OS's output buffers */
6837 /* Use RENAME to make sure the DB file is changed atomically only
6838 * if the generate DB file is ok. */
6839 if (rename(tmpfile
,filename
) == -1) {
6840 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
6844 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
6850 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
6851 if (di
) dictReleaseIterator(di
);
6855 /* This is how rewriting of the append only file in background works:
6857 * 1) The user calls BGREWRITEAOF
6858 * 2) Redis calls this function, that forks():
6859 * 2a) the child rewrite the append only file in a temp file.
6860 * 2b) the parent accumulates differences in server.bgrewritebuf.
6861 * 3) When the child finished '2a' exists.
6862 * 4) The parent will trap the exit code, if it's OK, will append the
6863 * data accumulated into server.bgrewritebuf into the temp file, and
6864 * finally will rename(2) the temp file in the actual file name.
6865 * The the new file is reopened as the new append only file. Profit!
6867 static int rewriteAppendOnlyFileBackground(void) {
6870 if (server
.bgrewritechildpid
!= -1) return REDIS_ERR
;
6871 if ((childpid
= fork()) == 0) {
6876 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
6877 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
6884 if (childpid
== -1) {
6885 redisLog(REDIS_WARNING
,
6886 "Can't rewrite append only file in background: fork: %s",
6890 redisLog(REDIS_NOTICE
,
6891 "Background append only file rewriting started by pid %d",childpid
);
6892 server
.bgrewritechildpid
= childpid
;
6893 /* We set appendseldb to -1 in order to force the next call to the
6894 * feedAppendOnlyFile() to issue a SELECT command, so the differences
6895 * accumulated by the parent into server.bgrewritebuf will start
6896 * with a SELECT statement and it will be safe to merge. */
6897 server
.appendseldb
= -1;
6900 return REDIS_OK
; /* unreached */
6903 static void bgrewriteaofCommand(redisClient
*c
) {
6904 if (server
.bgrewritechildpid
!= -1) {
6905 addReplySds(c
,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
6908 if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
6909 char *status
= "+Background append only file rewriting started\r\n";
6910 addReplySds(c
,sdsnew(status
));
6912 addReply(c
,shared
.err
);
6916 static void aofRemoveTempFile(pid_t childpid
) {
6919 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
6923 /* Virtual Memory is composed mainly of two subsystems:
6924 * - Blocking Virutal Memory
6925 * - Threaded Virtual Memory I/O
6926 * The two parts are not fully decoupled, but functions are split among two
6927 * different sections of the source code (delimited by comments) in order to
6928 * make more clear what functionality is about the blocking VM and what about
6929 * the threaded (not blocking) VM.
6933 * Redis VM is a blocking VM (one that blocks reading swapped values from
6934 * disk into memory when a value swapped out is needed in memory) that is made
6935 * unblocking by trying to examine the command argument vector in order to
6936 * load in background values that will likely be needed in order to exec
6937 * the command. The command is executed only once all the relevant keys
6938 * are loaded into memory.
6940 * This basically is almost as simple of a blocking VM, but almost as parallel
6941 * as a fully non-blocking VM.
6944 /* =================== Virtual Memory - Blocking Side ====================== */
6945 static void vmInit(void) {
6949 server
.vm_fp
= fopen("/tmp/redisvm","w+b");
6950 if (server
.vm_fp
== NULL
) {
6951 redisLog(REDIS_WARNING
,"Impossible to open the swap file. Exiting.");
6954 server
.vm_fd
= fileno(server
.vm_fp
);
6955 server
.vm_next_page
= 0;
6956 server
.vm_near_pages
= 0;
6957 server
.vm_stats_used_pages
= 0;
6958 server
.vm_stats_swapped_objects
= 0;
6959 server
.vm_stats_swapouts
= 0;
6960 server
.vm_stats_swapins
= 0;
6961 totsize
= server
.vm_pages
*server
.vm_page_size
;
6962 redisLog(REDIS_NOTICE
,"Allocating %lld bytes of swap file",totsize
);
6963 if (ftruncate(server
.vm_fd
,totsize
) == -1) {
6964 redisLog(REDIS_WARNING
,"Can't ftruncate swap file: %s. Exiting.",
6968 redisLog(REDIS_NOTICE
,"Swap file allocated with success");
6970 server
.vm_bitmap
= zmalloc((server
.vm_pages
+7)/8);
6971 redisLog(REDIS_VERBOSE
,"Allocated %lld bytes page table for %lld pages",
6972 (long long) (server
.vm_pages
+7)/8, server
.vm_pages
);
6973 memset(server
.vm_bitmap
,0,(server
.vm_pages
+7)/8);
6974 /* Try to remove the swap file, so the OS will really delete it from the
6975 * file system when Redis exists. */
6976 unlink("/tmp/redisvm");
6978 /* Initialize threaded I/O (used by Virtual Memory) */
6979 server
.io_newjobs
= listCreate();
6980 server
.io_processing
= listCreate();
6981 server
.io_processed
= listCreate();
6982 server
.io_clients
= listCreate();
6983 pthread_mutex_init(&server
.io_mutex
,NULL
);
6984 pthread_mutex_init(&server
.obj_freelist_mutex
,NULL
);
6985 pthread_mutex_init(&server
.io_swapfile_mutex
,NULL
);
6986 server
.io_active_threads
= 0;
6987 if (pipe(pipefds
) == -1) {
6988 redisLog(REDIS_WARNING
,"Unable to intialized VM: pipe(2): %s. Exiting."
6992 server
.io_ready_pipe_read
= pipefds
[0];
6993 server
.io_ready_pipe_write
= pipefds
[1];
6994 redisAssert(anetNonBlock(NULL
,server
.io_ready_pipe_read
) != ANET_ERR
);
6995 /* Listen for events in the threaded I/O pipe */
6996 if (aeCreateFileEvent(server
.el
, server
.io_ready_pipe_read
, AE_READABLE
,
6997 vmThreadedIOCompletedJob
, NULL
) == AE_ERR
)
6998 oom("creating file event");
7001 /* Mark the page as used */
7002 static void vmMarkPageUsed(off_t page
) {
7003 off_t byte
= page
/8;
7005 server
.vm_bitmap
[byte
] |= 1<<bit
;
7006 redisLog(REDIS_DEBUG
,"Mark used: %lld (byte:%lld bit:%d)\n",
7007 (long long)page
, (long long)byte
, bit
);
7010 /* Mark N contiguous pages as used, with 'page' being the first. */
7011 static void vmMarkPagesUsed(off_t page
, off_t count
) {
7014 for (j
= 0; j
< count
; j
++)
7015 vmMarkPageUsed(page
+j
);
7016 server
.vm_stats_used_pages
+= count
;
7019 /* Mark the page as free */
7020 static void vmMarkPageFree(off_t page
) {
7021 off_t byte
= page
/8;
7023 server
.vm_bitmap
[byte
] &= ~(1<<bit
);
7026 /* Mark N contiguous pages as free, with 'page' being the first. */
7027 static void vmMarkPagesFree(off_t page
, off_t count
) {
7030 for (j
= 0; j
< count
; j
++)
7031 vmMarkPageFree(page
+j
);
7032 server
.vm_stats_used_pages
-= count
;
7035 /* Test if the page is free */
7036 static int vmFreePage(off_t page
) {
7037 off_t byte
= page
/8;
7039 return (server
.vm_bitmap
[byte
] & (1<<bit
)) == 0;
7042 /* Find N contiguous free pages storing the first page of the cluster in *first.
7043 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
7044 * REDIS_ERR is returned.
7046 * This function uses a simple algorithm: we try to allocate
7047 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
7048 * again from the start of the swap file searching for free spaces.
7050 * If it looks pretty clear that there are no free pages near our offset
7051 * we try to find less populated places doing a forward jump of
7052 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
7053 * without hurry, and then we jump again and so forth...
7055 * This function can be improved using a free list to avoid to guess
7056 * too much, since we could collect data about freed pages.
7058 * note: I implemented this function just after watching an episode of
7059 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
7061 static int vmFindContiguousPages(off_t
*first
, int n
) {
7062 off_t base
, offset
= 0, since_jump
= 0, numfree
= 0;
7064 if (server
.vm_near_pages
== REDIS_VM_MAX_NEAR_PAGES
) {
7065 server
.vm_near_pages
= 0;
7066 server
.vm_next_page
= 0;
7068 server
.vm_near_pages
++; /* Yet another try for pages near to the old ones */
7069 base
= server
.vm_next_page
;
7071 while(offset
< server
.vm_pages
) {
7072 off_t
this = base
+offset
;
7074 redisLog(REDIS_DEBUG
, "THIS: %lld (%c)\n", (long long) this, vmFreePage(this) ? 'F' : 'X');
7075 /* If we overflow, restart from page zero */
7076 if (this >= server
.vm_pages
) {
7077 this -= server
.vm_pages
;
7079 /* Just overflowed, what we found on tail is no longer
7080 * interesting, as it's no longer contiguous. */
7084 if (vmFreePage(this)) {
7085 /* This is a free page */
7087 /* Already got N free pages? Return to the caller, with success */
7089 *first
= this-(n
-1);
7090 server
.vm_next_page
= this+1;
7094 /* The current one is not a free page */
7098 /* Fast-forward if the current page is not free and we already
7099 * searched enough near this place. */
7101 if (!numfree
&& since_jump
>= REDIS_VM_MAX_RANDOM_JUMP
/4) {
7102 offset
+= random() % REDIS_VM_MAX_RANDOM_JUMP
;
7104 /* Note that even if we rewind after the jump, we are don't need
7105 * to make sure numfree is set to zero as we only jump *if* it
7106 * is set to zero. */
7108 /* Otherwise just check the next page */
7115 /* Write the specified object at the specified page of the swap file */
7116 static int vmWriteObjectOnSwap(robj
*o
, off_t page
) {
7117 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
7118 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
7119 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
7120 redisLog(REDIS_WARNING
,
7121 "Critical VM problem in vmSwapObjectBlocking(): can't seek: %s",
7125 rdbSaveObject(server
.vm_fp
,o
);
7126 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
7130 /* Swap the 'val' object relative to 'key' into disk. Store all the information
7131 * needed to later retrieve the object into the key object.
7132 * If we can't find enough contiguous empty pages to swap the object on disk
7133 * REDIS_ERR is returned. */
7134 static int vmSwapObjectBlocking(robj
*key
, robj
*val
) {
7135 off_t pages
= rdbSavedObjectPages(val
,NULL
);
7138 assert(key
->storage
== REDIS_VM_MEMORY
);
7139 assert(key
->refcount
== 1);
7140 if (vmFindContiguousPages(&page
,pages
) == REDIS_ERR
) return REDIS_ERR
;
7141 if (vmWriteObjectOnSwap(val
,page
) == REDIS_ERR
) return REDIS_ERR
;
7142 key
->vm
.page
= page
;
7143 key
->vm
.usedpages
= pages
;
7144 key
->storage
= REDIS_VM_SWAPPED
;
7145 key
->vtype
= val
->type
;
7146 decrRefCount(val
); /* Deallocate the object from memory. */
7147 vmMarkPagesUsed(page
,pages
);
7148 redisLog(REDIS_DEBUG
,"VM: object %s swapped out at %lld (%lld pages)",
7149 (unsigned char*) key
->ptr
,
7150 (unsigned long long) page
, (unsigned long long) pages
);
7151 server
.vm_stats_swapped_objects
++;
7152 server
.vm_stats_swapouts
++;
7153 fflush(server
.vm_fp
);
7157 static robj
*vmReadObjectFromSwap(off_t page
, int type
) {
7160 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
7161 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
7162 redisLog(REDIS_WARNING
,
7163 "Unrecoverable VM problem in vmLoadObject(): can't seek: %s",
7167 o
= rdbLoadObject(type
,server
.vm_fp
);
7169 redisLog(REDIS_WARNING
, "Unrecoverable VM problem in vmLoadObject(): can't load object from swap file: %s", strerror(errno
));
7172 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
7176 /* Load the value object relative to the 'key' object from swap to memory.
7177 * The newly allocated object is returned.
7179 * If preview is true the unserialized object is returned to the caller but
7180 * no changes are made to the key object, nor the pages are marked as freed */
7181 static robj
*vmGenericLoadObject(robj
*key
, int preview
) {
7184 redisAssert(key
->storage
== REDIS_VM_SWAPPED
);
7185 val
= vmReadObjectFromSwap(key
->vm
.page
,key
->vtype
);
7187 key
->storage
= REDIS_VM_MEMORY
;
7188 key
->vm
.atime
= server
.unixtime
;
7189 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
7190 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk",
7191 (unsigned char*) key
->ptr
);
7192 server
.vm_stats_swapped_objects
--;
7194 redisLog(REDIS_DEBUG
, "VM: object %s previewed from disk",
7195 (unsigned char*) key
->ptr
);
7197 server
.vm_stats_swapins
++;
7201 /* Plain object loading, from swap to memory */
7202 static robj
*vmLoadObject(robj
*key
) {
7203 /* If we are loading the object in background, stop it, we
7204 * need to load this object synchronously ASAP. */
7205 if (key
->storage
== REDIS_VM_LOADING
)
7206 vmCancelThreadedIOJob(key
);
7207 return vmGenericLoadObject(key
,0);
7210 /* Just load the value on disk, without to modify the key.
7211 * This is useful when we want to perform some operation on the value
7212 * without to really bring it from swap to memory, like while saving the
7213 * dataset or rewriting the append only log. */
7214 static robj
*vmPreviewObject(robj
*key
) {
7215 return vmGenericLoadObject(key
,1);
7218 /* How a good candidate is this object for swapping?
7219 * The better candidate it is, the greater the returned value.
7221 * Currently we try to perform a fast estimation of the object size in
7222 * memory, and combine it with aging informations.
7224 * Basically swappability = idle-time * log(estimated size)
7226 * Bigger objects are preferred over smaller objects, but not
7227 * proportionally, this is why we use the logarithm. This algorithm is
7228 * just a first try and will probably be tuned later. */
7229 static double computeObjectSwappability(robj
*o
) {
7230 time_t age
= server
.unixtime
- o
->vm
.atime
;
7234 struct dictEntry
*de
;
7237 if (age
<= 0) return 0;
7240 if (o
->encoding
!= REDIS_ENCODING_RAW
) {
7243 asize
= sdslen(o
->ptr
)+sizeof(*o
)+sizeof(long)*2;
7248 listNode
*ln
= listFirst(l
);
7250 asize
= sizeof(list
);
7252 robj
*ele
= ln
->value
;
7255 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
7256 (sizeof(*o
)+sdslen(ele
->ptr
)) :
7258 asize
+= (sizeof(listNode
)+elesize
)*listLength(l
);
7263 z
= (o
->type
== REDIS_ZSET
);
7264 d
= z
? ((zset
*)o
->ptr
)->dict
: o
->ptr
;
7266 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
7267 if (z
) asize
+= sizeof(zset
)-sizeof(dict
);
7272 de
= dictGetRandomKey(d
);
7273 ele
= dictGetEntryKey(de
);
7274 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
7275 (sizeof(*o
)+sdslen(ele
->ptr
)) :
7277 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
7278 if (z
) asize
+= sizeof(zskiplistNode
)*dictSize(d
);
7282 return (double)asize
*log(1+asize
);
7285 /* Try to swap an object that's a good candidate for swapping.
7286 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
7287 * to swap any object at all.
7289 * If 'usethreaded' is true, Redis will try to swap the object in background
7290 * using I/O threads. */
7291 static int vmSwapOneObject(int usethreads
) {
7293 struct dictEntry
*best
= NULL
;
7294 double best_swappability
= 0;
7295 redisDb
*best_db
= NULL
;
7298 for (j
= 0; j
< server
.dbnum
; j
++) {
7299 redisDb
*db
= server
.db
+j
;
7300 int maxtries
= 1000;
7302 if (dictSize(db
->dict
) == 0) continue;
7303 for (i
= 0; i
< 5; i
++) {
7305 double swappability
;
7307 if (maxtries
) maxtries
--;
7308 de
= dictGetRandomKey(db
->dict
);
7309 key
= dictGetEntryKey(de
);
7310 val
= dictGetEntryVal(de
);
7311 if (key
->storage
!= REDIS_VM_MEMORY
) {
7312 if (maxtries
) i
--; /* don't count this try */
7315 swappability
= computeObjectSwappability(val
);
7316 if (!best
|| swappability
> best_swappability
) {
7318 best_swappability
= swappability
;
7324 redisLog(REDIS_DEBUG
,"No swappable key found!");
7327 key
= dictGetEntryKey(best
);
7328 val
= dictGetEntryVal(best
);
7330 redisLog(REDIS_DEBUG
,"Key with best swappability: %s, %f",
7331 key
->ptr
, best_swappability
);
7333 /* Unshare the key if needed */
7334 if (key
->refcount
> 1) {
7335 robj
*newkey
= dupStringObject(key
);
7337 key
= dictGetEntryKey(best
) = newkey
;
7341 vmSwapObjectThreaded(key
,val
,best_db
);
7344 if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
7345 dictGetEntryVal(best
) = NULL
;
7353 static int vmSwapOneObjectBlocking() {
7354 return vmSwapOneObject(0);
7357 static int vmSwapOneObjectThreaded() {
7358 return vmSwapOneObject(1);
7361 /* Return true if it's safe to swap out objects in a given moment.
7362 * Basically we don't want to swap objects out while there is a BGSAVE
7363 * or a BGAEOREWRITE running in backgroud. */
7364 static int vmCanSwapOut(void) {
7365 return (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1);
7368 /* Delete a key if swapped. Returns 1 if the key was found, was swapped
7369 * and was deleted. Otherwise 0 is returned. */
7370 static int deleteIfSwapped(redisDb
*db
, robj
*key
) {
7374 if ((de
= dictFind(db
->dict
,key
)) == NULL
) return 0;
7375 foundkey
= dictGetEntryKey(de
);
7376 if (foundkey
->storage
== REDIS_VM_MEMORY
) return 0;
7381 /* =================== Virtual Memory - Threaded I/O ======================= */
7383 static void freeIOJob(iojob
*j
) {
7384 if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
||
7385 j
->type
== REDIS_IOJOB_DO_SWAP
)
7386 decrRefCount(j
->val
);
7387 decrRefCount(j
->key
);
7391 /* Every time a thread finished a Job, it writes a byte into the write side
7392 * of an unix pipe in order to "awake" the main thread, and this function
7394 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
,
7401 REDIS_NOTUSED(mask
);
7402 REDIS_NOTUSED(privdata
);
7404 /* For every byte we read in the read side of the pipe, there is one
7405 * I/O job completed to process. */
7406 while((retval
= read(fd
,buf
,1)) == 1) {
7410 struct dictEntry
*de
;
7412 redisLog(REDIS_DEBUG
,"Processing I/O completed job");
7413 assert(listLength(server
.io_processed
) != 0);
7415 /* Get the processed element (the oldest one) */
7417 ln
= listFirst(server
.io_processed
);
7419 listDelNode(server
.io_processed
,ln
);
7421 /* If this job is marked as canceled, just ignore it */
7426 /* Post process it in the main thread, as there are things we
7427 * can do just here to avoid race conditions and/or invasive locks */
7428 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
);
7429 de
= dictFind(j
->db
->dict
,j
->key
);
7431 key
= dictGetEntryKey(de
);
7432 if (j
->type
== REDIS_IOJOB_LOAD
) {
7433 /* Key loaded, bring it at home */
7434 key
->storage
= REDIS_VM_MEMORY
;
7435 key
->vm
.atime
= server
.unixtime
;
7436 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
7437 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk (threaded)",
7438 (unsigned char*) key
->ptr
);
7439 server
.vm_stats_swapped_objects
--;
7440 server
.vm_stats_swapins
++;
7442 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
7443 /* Now we know the amount of pages required to swap this object.
7444 * Let's find some space for it, and queue this task again
7445 * rebranded as REDIS_IOJOB_DO_SWAP. */
7446 if (vmFindContiguousPages(&j
->page
,j
->pages
) == REDIS_ERR
) {
7447 /* Ooops... no space! */
7450 j
->type
= REDIS_IOJOB_DO_SWAP
;
7455 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
7458 /* Key swapped. We can finally free some memory. */
7459 if (key
->storage
!= REDIS_VM_SWAPPING
) {
7460 printf("key->storage: %d\n",key
->storage
);
7461 printf("key->name: %s\n",(char*)key
->ptr
);
7462 printf("key->refcount: %d\n",key
->refcount
);
7463 printf("val: %p\n",(void*)j
->val
);
7464 printf("val->type: %d\n",j
->val
->type
);
7465 printf("val->ptr: %s\n",(char*)j
->val
->ptr
);
7467 redisAssert(key
->storage
== REDIS_VM_SWAPPING
);
7468 val
= dictGetEntryVal(de
);
7469 key
->vm
.page
= j
->page
;
7470 key
->vm
.usedpages
= j
->pages
;
7471 key
->storage
= REDIS_VM_SWAPPED
;
7472 key
->vtype
= j
->val
->type
;
7473 decrRefCount(val
); /* Deallocate the object from memory. */
7474 dictGetEntryVal(de
) = NULL
;
7475 vmMarkPagesUsed(j
->page
,j
->pages
);
7476 redisLog(REDIS_DEBUG
,
7477 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
7478 (unsigned char*) key
->ptr
,
7479 (unsigned long long) j
->page
, (unsigned long long) j
->pages
);
7480 server
.vm_stats_swapped_objects
++;
7481 server
.vm_stats_swapouts
++;
7483 /* Put a few more swap requests in queue if we are still
7485 if (zmalloc_used_memory() > server
.vm_max_memory
) {
7489 more
= listLength(server
.io_newjobs
) <
7490 (unsigned) server
.vm_max_threads
;
7492 /* Don't waste CPU time if swappable objects are rare. */
7493 if (vmSwapOneObjectThreaded() == REDIS_ERR
) break;
7498 if (processed
== REDIS_MAX_COMPLETED_JOBS_PROCESSED
) return;
7500 if (retval
< 0 && errno
!= EAGAIN
) {
7501 redisLog(REDIS_WARNING
,
7502 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
7507 static void lockThreadedIO(void) {
7508 pthread_mutex_lock(&server
.io_mutex
);
7511 static void unlockThreadedIO(void) {
7512 pthread_mutex_unlock(&server
.io_mutex
);
7515 /* Remove the specified object from the threaded I/O queue if still not
7516 * processed, otherwise make sure to flag it as canceled. */
7517 static void vmCancelThreadedIOJob(robj
*o
) {
7519 server
.io_newjobs
, /* 0 */
7520 server
.io_processing
, /* 1 */
7521 server
.io_processed
/* 2 */
7525 assert(o
->storage
== REDIS_VM_LOADING
|| o
->storage
== REDIS_VM_SWAPPING
);
7527 /* Search for a matching key in one of the queues */
7528 for (i
= 0; i
< 3; i
++) {
7531 listRewind(lists
[i
]);
7532 while ((ln
= listYield(lists
[i
])) != NULL
) {
7533 iojob
*job
= ln
->value
;
7535 if (job
->canceled
) continue; /* Skip this, already canceled. */
7536 if (compareStringObjects(job
->key
,o
) == 0) {
7537 redisLog(REDIS_DEBUG
,"*** CANCELED %p (%s)\n",
7538 (void*)job
, (char*)o
->ptr
);
7540 case 0: /* io_newjobs */
7541 /* If the job was yet not processed the best thing to do
7542 * is to remove it from the queue at all */
7544 listDelNode(lists
[i
],ln
);
7546 case 1: /* io_processing */
7547 case 2: /* io_processed */
7551 if (o
->storage
== REDIS_VM_LOADING
)
7552 o
->storage
= REDIS_VM_SWAPPED
;
7553 else if (o
->storage
== REDIS_VM_SWAPPING
)
7554 o
->storage
= REDIS_VM_MEMORY
;
7561 assert(1 != 1); /* We should never reach this */
7564 static void *IOThreadEntryPoint(void *arg
) {
7569 pthread_detach(pthread_self());
7571 /* Get a new job to process */
7573 if (listLength(server
.io_newjobs
) == 0) {
7574 /* No new jobs in queue, exit. */
7575 redisLog(REDIS_DEBUG
,"Thread %lld exiting, nothing to do\n",
7576 (long long) pthread_self());
7577 server
.io_active_threads
--;
7581 ln
= listFirst(server
.io_newjobs
);
7583 listDelNode(server
.io_newjobs
,ln
);
7584 /* Add the job in the processing queue */
7585 j
->thread
= pthread_self();
7586 listAddNodeTail(server
.io_processing
,j
);
7587 ln
= listLast(server
.io_processing
); /* We use ln later to remove it */
7589 redisLog(REDIS_DEBUG
,"Thread %lld got a new job (type %d): %p about key '%s'\n",
7590 (long long) pthread_self(), j
->type
, (void*)j
, (char*)j
->key
->ptr
);
7592 /* Process the Job */
7593 if (j
->type
== REDIS_IOJOB_LOAD
) {
7594 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
7595 FILE *fp
= fopen("/dev/null","w+");
7596 j
->pages
= rdbSavedObjectPages(j
->val
,fp
);
7598 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
7599 if (vmWriteObjectOnSwap(j
->val
,j
->page
) == REDIS_ERR
)
7603 /* Done: insert the job into the processed queue */
7604 redisLog(REDIS_DEBUG
,"Thread %lld completed the job: %p (key %s)\n",
7605 (long long) pthread_self(), (void*)j
, (char*)j
->key
->ptr
);
7607 listDelNode(server
.io_processing
,ln
);
7608 listAddNodeTail(server
.io_processed
,j
);
7611 /* Signal the main thread there is new stuff to process */
7612 assert(write(server
.io_ready_pipe_write
,"x",1) == 1);
7614 return NULL
; /* never reached */
7617 static void spawnIOThread(void) {
7620 pthread_create(&thread
,NULL
,IOThreadEntryPoint
,NULL
);
7621 server
.io_active_threads
++;
7624 /* This function must be called while with threaded IO locked */
7625 static void queueIOJob(iojob
*j
) {
7626 redisLog(REDIS_DEBUG
,"Queued IO Job %p type %d about key '%s'\n",
7627 (void*)j
, j
->type
, (char*)j
->key
->ptr
);
7628 listAddNodeTail(server
.io_newjobs
,j
);
7629 if (server
.io_active_threads
< server
.vm_max_threads
)
7633 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
) {
7636 assert(key
->storage
== REDIS_VM_MEMORY
);
7637 assert(key
->refcount
== 1);
7639 j
= zmalloc(sizeof(*j
));
7640 j
->type
= REDIS_IOJOB_PREPARE_SWAP
;
7642 j
->key
= dupStringObject(key
);
7646 j
->thread
= (pthread_t
) -1;
7647 key
->storage
= REDIS_VM_SWAPPING
;
7655 /* ================================= Debugging ============================== */
7657 static void debugCommand(redisClient
*c
) {
7658 if (!strcasecmp(c
->argv
[1]->ptr
,"segfault")) {
7660 } else if (!strcasecmp(c
->argv
[1]->ptr
,"reload")) {
7661 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
7662 addReply(c
,shared
.err
);
7666 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
7667 addReply(c
,shared
.err
);
7670 redisLog(REDIS_WARNING
,"DB reloaded by DEBUG RELOAD");
7671 addReply(c
,shared
.ok
);
7672 } else if (!strcasecmp(c
->argv
[1]->ptr
,"loadaof")) {
7674 if (loadAppendOnlyFile(server
.appendfilename
) != REDIS_OK
) {
7675 addReply(c
,shared
.err
);
7678 redisLog(REDIS_WARNING
,"Append Only File loaded by DEBUG LOADAOF");
7679 addReply(c
,shared
.ok
);
7680 } else if (!strcasecmp(c
->argv
[1]->ptr
,"object") && c
->argc
== 3) {
7681 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
7685 addReply(c
,shared
.nokeyerr
);
7688 key
= dictGetEntryKey(de
);
7689 val
= dictGetEntryVal(de
);
7690 if (server
.vm_enabled
&& (key
->storage
== REDIS_VM_MEMORY
||
7691 key
->storage
== REDIS_VM_SWAPPING
)) {
7692 addReplySds(c
,sdscatprintf(sdsempty(),
7693 "+Key at:%p refcount:%d, value at:%p refcount:%d "
7694 "encoding:%d serializedlength:%lld\r\n",
7695 (void*)key
, key
->refcount
, (void*)val
, val
->refcount
,
7696 val
->encoding
, rdbSavedObjectLen(val
,NULL
)));
7698 addReplySds(c
,sdscatprintf(sdsempty(),
7699 "+Key at:%p refcount:%d, value swapped at: page %llu "
7700 "using %llu pages\r\n",
7701 (void*)key
, key
->refcount
, (unsigned long long) key
->vm
.page
,
7702 (unsigned long long) key
->vm
.usedpages
));
7704 } else if (!strcasecmp(c
->argv
[1]->ptr
,"swapout") && c
->argc
== 3) {
7705 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
7708 if (!server
.vm_enabled
) {
7709 addReplySds(c
,sdsnew("-ERR Virtual Memory is disabled\r\n"));
7713 addReply(c
,shared
.nokeyerr
);
7716 key
= dictGetEntryKey(de
);
7717 val
= dictGetEntryVal(de
);
7718 /* If the key is shared we want to create a copy */
7719 if (key
->refcount
> 1) {
7720 robj
*newkey
= dupStringObject(key
);
7722 key
= dictGetEntryKey(de
) = newkey
;
7725 if (key
->storage
!= REDIS_VM_MEMORY
) {
7726 addReplySds(c
,sdsnew("-ERR This key is not in memory\r\n"));
7727 } else if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
7728 dictGetEntryVal(de
) = NULL
;
7729 addReply(c
,shared
.ok
);
7731 addReply(c
,shared
.err
);
7734 addReplySds(c
,sdsnew(
7735 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPOUT <key>|RELOAD]\r\n"));
7739 static void _redisAssert(char *estr
, char *file
, int line
) {
7740 redisLog(REDIS_WARNING
,"=== ASSERTION FAILED ===");
7741 redisLog(REDIS_WARNING
,"==> %s:%d '%s' is not true\n",file
,line
,estr
);
7742 #ifdef HAVE_BACKTRACE
7743 redisLog(REDIS_WARNING
,"(forcing SIGSEGV in order to print the stack trace)");
7748 /* =================================== Main! ================================ */
7751 int linuxOvercommitMemoryValue(void) {
7752 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
7756 if (fgets(buf
,64,fp
) == NULL
) {
7765 void linuxOvercommitMemoryWarning(void) {
7766 if (linuxOvercommitMemoryValue() == 0) {
7767 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.");
7770 #endif /* __linux__ */
7772 static void daemonize(void) {
7776 if (fork() != 0) exit(0); /* parent exits */
7777 setsid(); /* create a new session */
7779 /* Every output goes to /dev/null. If Redis is daemonized but
7780 * the 'logfile' is set to 'stdout' in the configuration file
7781 * it will not log at all. */
7782 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
7783 dup2(fd
, STDIN_FILENO
);
7784 dup2(fd
, STDOUT_FILENO
);
7785 dup2(fd
, STDERR_FILENO
);
7786 if (fd
> STDERR_FILENO
) close(fd
);
7788 /* Try to write the pid file */
7789 fp
= fopen(server
.pidfile
,"w");
7791 fprintf(fp
,"%d\n",getpid());
7796 int main(int argc
, char **argv
) {
7799 resetServerSaveParams();
7800 loadServerConfig(argv
[1]);
7801 } else if (argc
> 2) {
7802 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
7805 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'");
7807 if (server
.daemonize
) daemonize();
7809 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
7811 linuxOvercommitMemoryWarning();
7813 if (server
.appendonly
) {
7814 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
7815 redisLog(REDIS_NOTICE
,"DB loaded from append only file");
7817 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
7818 redisLog(REDIS_NOTICE
,"DB loaded from disk");
7820 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
7822 aeDeleteEventLoop(server
.el
);
7826 /* ============================= Backtrace support ========================= */
7828 #ifdef HAVE_BACKTRACE
7829 static char *findFuncName(void *pointer
, unsigned long *offset
);
7831 static void *getMcontextEip(ucontext_t
*uc
) {
7832 #if defined(__FreeBSD__)
7833 return (void*) uc
->uc_mcontext
.mc_eip
;
7834 #elif defined(__dietlibc__)
7835 return (void*) uc
->uc_mcontext
.eip
;
7836 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
7838 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
7840 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
7842 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
7843 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
7844 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
7846 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
7848 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
7849 return (void*) uc
->uc_mcontext
.gregs
[REG_EIP
]; /* Linux 32/64 bit */
7850 #elif defined(__ia64__) /* Linux IA64 */
7851 return (void*) uc
->uc_mcontext
.sc_ip
;
7857 static void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
7859 char **messages
= NULL
;
7860 int i
, trace_size
= 0;
7861 unsigned long offset
=0;
7862 ucontext_t
*uc
= (ucontext_t
*) secret
;
7864 REDIS_NOTUSED(info
);
7866 redisLog(REDIS_WARNING
,
7867 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
7868 infostring
= genRedisInfoString();
7869 redisLog(REDIS_WARNING
, "%s",infostring
);
7870 /* It's not safe to sdsfree() the returned string under memory
7871 * corruption conditions. Let it leak as we are going to abort */
7873 trace_size
= backtrace(trace
, 100);
7874 /* overwrite sigaction with caller's address */
7875 if (getMcontextEip(uc
) != NULL
) {
7876 trace
[1] = getMcontextEip(uc
);
7878 messages
= backtrace_symbols(trace
, trace_size
);
7880 for (i
=1; i
<trace_size
; ++i
) {
7881 char *fn
= findFuncName(trace
[i
], &offset
), *p
;
7883 p
= strchr(messages
[i
],'+');
7884 if (!fn
|| (p
&& ((unsigned long)strtol(p
+1,NULL
,10)) < offset
)) {
7885 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
7887 redisLog(REDIS_WARNING
,"%d redis-server %p %s + %d", i
, trace
[i
], fn
, (unsigned int)offset
);
7890 /* free(messages); Don't call free() with possibly corrupted memory. */
7894 static void setupSigSegvAction(void) {
7895 struct sigaction act
;
7897 sigemptyset (&act
.sa_mask
);
7898 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
7899 * is used. Otherwise, sa_handler is used */
7900 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
7901 act
.sa_sigaction
= segvHandler
;
7902 sigaction (SIGSEGV
, &act
, NULL
);
7903 sigaction (SIGBUS
, &act
, NULL
);
7904 sigaction (SIGFPE
, &act
, NULL
);
7905 sigaction (SIGILL
, &act
, NULL
);
7906 sigaction (SIGBUS
, &act
, NULL
);
7910 #include "staticsymbols.h"
7911 /* This function try to convert a pointer into a function name. It's used in
7912 * oreder to provide a backtrace under segmentation fault that's able to
7913 * display functions declared as static (otherwise the backtrace is useless). */
7914 static char *findFuncName(void *pointer
, unsigned long *offset
){
7916 unsigned long off
, minoff
= 0;
7918 /* Try to match against the Symbol with the smallest offset */
7919 for (i
=0; symsTable
[i
].pointer
; i
++) {
7920 unsigned long lp
= (unsigned long) pointer
;
7922 if (lp
!= (unsigned long)-1 && lp
>= symsTable
[i
].pointer
) {
7923 off
=lp
-symsTable
[i
].pointer
;
7924 if (ret
< 0 || off
< minoff
) {
7930 if (ret
== -1) return NULL
;
7932 return symsTable
[ret
].name
;
7934 #else /* HAVE_BACKTRACE */
7935 static void setupSigSegvAction(void) {
7937 #endif /* HAVE_BACKTRACE */