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
169 #define REDIS_CLOSE 1 /* This client connection should be closed ASAP */
170 #define REDIS_SLAVE 2 /* This client is a slave server */
171 #define REDIS_MASTER 4 /* This client is a master server */
172 #define REDIS_MONITOR 8 /* This client is a slave monitor, see MONITOR */
173 #define REDIS_MULTI 16 /* This client is in a MULTI context */
174 #define REDIS_BLOCKED 32 /* The client is waiting in a blocking operation */
175 #define REDIS_IO_WAIT 64 /* The client is waiting for Virtual Memory I/O */
177 /* Slave replication state - slave side */
178 #define REDIS_REPL_NONE 0 /* No active replication */
179 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
180 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
182 /* Slave replication state - from the point of view of master
183 * Note that in SEND_BULK and ONLINE state the slave receives new updates
184 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
185 * to start the next background saving in order to send updates to it. */
186 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
187 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
188 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
189 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
191 /* List related stuff */
195 /* Sort operations */
196 #define REDIS_SORT_GET 0
197 #define REDIS_SORT_ASC 1
198 #define REDIS_SORT_DESC 2
199 #define REDIS_SORTKEY_MAX 1024
202 #define REDIS_DEBUG 0
203 #define REDIS_VERBOSE 1
204 #define REDIS_NOTICE 2
205 #define REDIS_WARNING 3
207 /* Anti-warning macro... */
208 #define REDIS_NOTUSED(V) ((void) V)
210 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
211 #define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
213 /* Append only defines */
214 #define APPENDFSYNC_NO 0
215 #define APPENDFSYNC_ALWAYS 1
216 #define APPENDFSYNC_EVERYSEC 2
218 /* We can print the stacktrace, so our assert is defined this way: */
219 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e),exit(1)))
220 static void _redisAssert(char *estr
);
222 /*================================= Data types ============================== */
224 /* A redis object, that is a type able to hold a string / list / set */
226 /* The VM object structure */
227 struct redisObjectVM
{
228 off_t page
; /* the page at witch the object is stored on disk */
229 off_t usedpages
; /* number of pages used on disk */
230 time_t atime
; /* Last access time */
233 /* The actual Redis Object */
234 typedef struct redisObject
{
237 unsigned char encoding
;
238 unsigned char storage
; /* If this object is a key, where is the value?
239 * REDIS_VM_MEMORY, REDIS_VM_SWAPPED, ... */
240 unsigned char vtype
; /* If this object is a key, and value is swapped out,
241 * this is the type of the swapped out object. */
243 /* VM fields, this are only allocated if VM is active, otherwise the
244 * object allocation function will just allocate
245 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
246 * Redis without VM active will not have any overhead. */
247 struct redisObjectVM vm
;
250 /* Macro used to initalize a Redis object allocated on the stack.
251 * Note that this macro is taken near the structure definition to make sure
252 * we'll update it when the structure is changed, to avoid bugs like
253 * bug #85 introduced exactly in this way. */
254 #define initStaticStringObject(_var,_ptr) do { \
256 _var.type = REDIS_STRING; \
257 _var.encoding = REDIS_ENCODING_RAW; \
259 if (server.vm_enabled) _var.storage = REDIS_VM_MEMORY; \
262 typedef struct redisDb
{
263 dict
*dict
; /* The keyspace for this DB */
264 dict
*expires
; /* Timeout of keys with a timeout set */
265 dict
*blockingkeys
; /* Keys with clients waiting for data (BLPOP) */
269 /* Client MULTI/EXEC state */
270 typedef struct multiCmd
{
273 struct redisCommand
*cmd
;
276 typedef struct multiState
{
277 multiCmd
*commands
; /* Array of MULTI commands */
278 int count
; /* Total number of MULTI commands */
281 /* With multiplexing we need to take per-clinet state.
282 * Clients are taken in a liked list. */
283 typedef struct redisClient
{
288 robj
**argv
, **mbargv
;
290 int bulklen
; /* bulk read len. -1 if not in bulk read mode */
291 int multibulk
; /* multi bulk command format active */
294 time_t lastinteraction
; /* time of the last interaction, used for timeout */
295 int flags
; /* REDIS_CLOSE | REDIS_SLAVE | REDIS_MONITOR */
297 int slaveseldb
; /* slave selected db, if this client is a slave */
298 int authenticated
; /* when requirepass is non-NULL */
299 int replstate
; /* replication state if this is a slave */
300 int repldbfd
; /* replication DB file descriptor */
301 long repldboff
; /* replication DB file offset */
302 off_t repldbsize
; /* replication DB file size */
303 multiState mstate
; /* MULTI/EXEC state */
304 robj
**blockingkeys
; /* The key we waiting to terminate a blocking
305 * operation such as BLPOP. Otherwise NULL. */
306 int blockingkeysnum
; /* Number of blocking keys */
307 time_t blockingto
; /* Blocking operation timeout. If UNIX current time
308 * is >= blockingto then the operation timed out. */
309 list
*io_keys
; /* Keys this client is waiting to be loaded from the
310 * swap file in order to continue. */
318 /* Global server state structure */
323 dict
*sharingpool
; /* Poll used for object sharing */
324 unsigned int sharingpoolsize
;
325 long long dirty
; /* changes to DB from the last save */
327 list
*slaves
, *monitors
;
328 char neterr
[ANET_ERR_LEN
];
330 int cronloops
; /* number of times the cron function run */
331 list
*objfreelist
; /* A list of freed objects to avoid malloc() */
332 time_t lastsave
; /* Unix time of last save succeeede */
333 size_t usedmemory
; /* Used memory in megabytes */
334 /* Fields used only for stats */
335 time_t stat_starttime
; /* server start time */
336 long long stat_numcommands
; /* number of processed commands */
337 long long stat_numconnections
; /* number of connections received */
350 pid_t bgsavechildpid
;
351 pid_t bgrewritechildpid
;
352 sds bgrewritebuf
; /* buffer taken by parent during oppend only rewrite */
353 struct saveparam
*saveparams
;
358 char *appendfilename
;
362 /* Replication related */
367 redisClient
*master
; /* client that is master for this slave */
369 unsigned int maxclients
;
370 unsigned long long maxmemory
;
371 unsigned int blockedclients
;
372 /* Sort parameters - qsort_r() is only available under BSD so we
373 * have to take this state global, in order to pass it to sortCompare() */
377 /* Virtual memory configuration */
381 unsigned long long vm_max_memory
;
382 /* Virtual memory state */
385 off_t vm_next_page
; /* Next probably empty page */
386 off_t vm_near_pages
; /* Number of pages allocated sequentially */
387 unsigned char *vm_bitmap
; /* Bitmap of free/used pages */
388 time_t unixtime
; /* Unix time sampled every second. */
389 /* Virtual memory I/O threads stuff */
390 /* An I/O thread process an element taken from the io_jobs queue and
391 * put the result of the operation in the io_done list. While the
392 * job is being processed, it's put on io_processing queue. */
393 list
*io_newjobs
; /* List of VM I/O jobs yet to be processed */
394 list
*io_processing
; /* List of VM I/O jobs being processed */
395 list
*io_processed
; /* List of VM I/O jobs already processed */
396 list
*io_clients
; /* All the clients waiting for SWAP I/O operations */
397 pthread_mutex_t io_mutex
; /* lock to access io_jobs/io_done/io_thread_job */
398 int io_active_threads
; /* Number of running I/O threads */
399 int vm_max_threads
; /* Max number of I/O threads running at the same time */
400 /* Our main thread is blocked on the event loop, locking for sockets ready
401 * to be read or written, so when a threaded I/O operation is ready to be
402 * processed by the main thread, the I/O thread will use a unix pipe to
403 * awake the main thread. The followings are the two pipe FDs. */
404 int io_ready_pipe_read
;
405 int io_ready_pipe_write
;
406 /* Virtual memory stats */
407 unsigned long long vm_stats_used_pages
;
408 unsigned long long vm_stats_swapped_objects
;
409 unsigned long long vm_stats_swapouts
;
410 unsigned long long vm_stats_swapins
;
413 typedef void redisCommandProc(redisClient
*c
);
414 struct redisCommand
{
416 redisCommandProc
*proc
;
421 struct redisFunctionSym
{
423 unsigned long pointer
;
426 typedef struct _redisSortObject
{
434 typedef struct _redisSortOperation
{
437 } redisSortOperation
;
439 /* ZSETs use a specialized version of Skiplists */
441 typedef struct zskiplistNode
{
442 struct zskiplistNode
**forward
;
443 struct zskiplistNode
*backward
;
448 typedef struct zskiplist
{
449 struct zskiplistNode
*header
, *tail
;
450 unsigned long length
;
454 typedef struct zset
{
459 /* Our shared "common" objects */
461 struct sharedObjectsStruct
{
462 robj
*crlf
, *ok
, *err
, *emptybulk
, *czero
, *cone
, *pong
, *space
,
463 *colon
, *nullbulk
, *nullmultibulk
, *queued
,
464 *emptymultibulk
, *wrongtypeerr
, *nokeyerr
, *syntaxerr
, *sameobjecterr
,
465 *outofrangeerr
, *plus
,
466 *select0
, *select1
, *select2
, *select3
, *select4
,
467 *select5
, *select6
, *select7
, *select8
, *select9
;
470 /* Global vars that are actally used as constants. The following double
471 * values are used for double on-disk serialization, and are initialized
472 * at runtime to avoid strange compiler optimizations. */
474 static double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
;
476 /* VM threaded I/O request message */
477 #define REDIS_IOJOB_LOAD 0
478 #define REDIS_IOJOB_SWAP 1
479 typedef struct iojon
{
480 int type
; /* Request type, REDIS_IOJOB_* */
481 int dbid
; /* Redis database ID */
482 robj
*key
; /* This I/O request is about swapping this key */
483 robj
*val
; /* the value to swap for REDIS_IOREQ_SWAP, otherwise this
484 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
485 off_t page
; /* Swap page where to read/write the object */
486 int canceled
; /* True if this command was canceled by blocking side of VM */
487 pthread_t thread
; /* ID of the thread processing this entry */
490 /*================================ Prototypes =============================== */
492 static void freeStringObject(robj
*o
);
493 static void freeListObject(robj
*o
);
494 static void freeSetObject(robj
*o
);
495 static void decrRefCount(void *o
);
496 static robj
*createObject(int type
, void *ptr
);
497 static void freeClient(redisClient
*c
);
498 static int rdbLoad(char *filename
);
499 static void addReply(redisClient
*c
, robj
*obj
);
500 static void addReplySds(redisClient
*c
, sds s
);
501 static void incrRefCount(robj
*o
);
502 static int rdbSaveBackground(char *filename
);
503 static robj
*createStringObject(char *ptr
, size_t len
);
504 static robj
*dupStringObject(robj
*o
);
505 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
506 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
507 static int syncWithMaster(void);
508 static robj
*tryObjectSharing(robj
*o
);
509 static int tryObjectEncoding(robj
*o
);
510 static robj
*getDecodedObject(robj
*o
);
511 static int removeExpire(redisDb
*db
, robj
*key
);
512 static int expireIfNeeded(redisDb
*db
, robj
*key
);
513 static int deleteIfVolatile(redisDb
*db
, robj
*key
);
514 static int deleteIfSwapped(redisDb
*db
, robj
*key
);
515 static int deleteKey(redisDb
*db
, robj
*key
);
516 static time_t getExpire(redisDb
*db
, robj
*key
);
517 static int setExpire(redisDb
*db
, robj
*key
, time_t when
);
518 static void updateSlavesWaitingBgsave(int bgsaveerr
);
519 static void freeMemoryIfNeeded(void);
520 static int processCommand(redisClient
*c
);
521 static void setupSigSegvAction(void);
522 static void rdbRemoveTempFile(pid_t childpid
);
523 static void aofRemoveTempFile(pid_t childpid
);
524 static size_t stringObjectLen(robj
*o
);
525 static void processInputBuffer(redisClient
*c
);
526 static zskiplist
*zslCreate(void);
527 static void zslFree(zskiplist
*zsl
);
528 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
);
529 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
530 static void initClientMultiState(redisClient
*c
);
531 static void freeClientMultiState(redisClient
*c
);
532 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
);
533 static void unblockClient(redisClient
*c
);
534 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
);
535 static void vmInit(void);
536 static void vmMarkPagesFree(off_t page
, off_t count
);
537 static robj
*vmLoadObject(robj
*key
);
538 static robj
*vmPreviewObject(robj
*key
);
539 static int vmSwapOneObjectBlocking(void);
540 static int vmSwapOneObjectThreaded(void);
541 static int vmCanSwapOut(void);
542 static void freeOneObjectFromFreelist(void);
543 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
544 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
545 static void vmCancelThreadedIOJob(robj
*o
);
547 static void authCommand(redisClient
*c
);
548 static void pingCommand(redisClient
*c
);
549 static void echoCommand(redisClient
*c
);
550 static void setCommand(redisClient
*c
);
551 static void setnxCommand(redisClient
*c
);
552 static void getCommand(redisClient
*c
);
553 static void delCommand(redisClient
*c
);
554 static void existsCommand(redisClient
*c
);
555 static void incrCommand(redisClient
*c
);
556 static void decrCommand(redisClient
*c
);
557 static void incrbyCommand(redisClient
*c
);
558 static void decrbyCommand(redisClient
*c
);
559 static void selectCommand(redisClient
*c
);
560 static void randomkeyCommand(redisClient
*c
);
561 static void keysCommand(redisClient
*c
);
562 static void dbsizeCommand(redisClient
*c
);
563 static void lastsaveCommand(redisClient
*c
);
564 static void saveCommand(redisClient
*c
);
565 static void bgsaveCommand(redisClient
*c
);
566 static void bgrewriteaofCommand(redisClient
*c
);
567 static void shutdownCommand(redisClient
*c
);
568 static void moveCommand(redisClient
*c
);
569 static void renameCommand(redisClient
*c
);
570 static void renamenxCommand(redisClient
*c
);
571 static void lpushCommand(redisClient
*c
);
572 static void rpushCommand(redisClient
*c
);
573 static void lpopCommand(redisClient
*c
);
574 static void rpopCommand(redisClient
*c
);
575 static void llenCommand(redisClient
*c
);
576 static void lindexCommand(redisClient
*c
);
577 static void lrangeCommand(redisClient
*c
);
578 static void ltrimCommand(redisClient
*c
);
579 static void typeCommand(redisClient
*c
);
580 static void lsetCommand(redisClient
*c
);
581 static void saddCommand(redisClient
*c
);
582 static void sremCommand(redisClient
*c
);
583 static void smoveCommand(redisClient
*c
);
584 static void sismemberCommand(redisClient
*c
);
585 static void scardCommand(redisClient
*c
);
586 static void spopCommand(redisClient
*c
);
587 static void srandmemberCommand(redisClient
*c
);
588 static void sinterCommand(redisClient
*c
);
589 static void sinterstoreCommand(redisClient
*c
);
590 static void sunionCommand(redisClient
*c
);
591 static void sunionstoreCommand(redisClient
*c
);
592 static void sdiffCommand(redisClient
*c
);
593 static void sdiffstoreCommand(redisClient
*c
);
594 static void syncCommand(redisClient
*c
);
595 static void flushdbCommand(redisClient
*c
);
596 static void flushallCommand(redisClient
*c
);
597 static void sortCommand(redisClient
*c
);
598 static void lremCommand(redisClient
*c
);
599 static void rpoplpushcommand(redisClient
*c
);
600 static void infoCommand(redisClient
*c
);
601 static void mgetCommand(redisClient
*c
);
602 static void monitorCommand(redisClient
*c
);
603 static void expireCommand(redisClient
*c
);
604 static void expireatCommand(redisClient
*c
);
605 static void getsetCommand(redisClient
*c
);
606 static void ttlCommand(redisClient
*c
);
607 static void slaveofCommand(redisClient
*c
);
608 static void debugCommand(redisClient
*c
);
609 static void msetCommand(redisClient
*c
);
610 static void msetnxCommand(redisClient
*c
);
611 static void zaddCommand(redisClient
*c
);
612 static void zincrbyCommand(redisClient
*c
);
613 static void zrangeCommand(redisClient
*c
);
614 static void zrangebyscoreCommand(redisClient
*c
);
615 static void zrevrangeCommand(redisClient
*c
);
616 static void zcardCommand(redisClient
*c
);
617 static void zremCommand(redisClient
*c
);
618 static void zscoreCommand(redisClient
*c
);
619 static void zremrangebyscoreCommand(redisClient
*c
);
620 static void multiCommand(redisClient
*c
);
621 static void execCommand(redisClient
*c
);
622 static void blpopCommand(redisClient
*c
);
623 static void brpopCommand(redisClient
*c
);
625 /*================================= Globals ================================= */
628 static struct redisServer server
; /* server global state */
629 static struct redisCommand cmdTable
[] = {
630 {"get",getCommand
,2,REDIS_CMD_INLINE
},
631 {"set",setCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
632 {"setnx",setnxCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
633 {"del",delCommand
,-2,REDIS_CMD_INLINE
},
634 {"exists",existsCommand
,2,REDIS_CMD_INLINE
},
635 {"incr",incrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
636 {"decr",decrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
637 {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
},
638 {"rpush",rpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
639 {"lpush",lpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
640 {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
},
641 {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
},
642 {"brpop",brpopCommand
,-3,REDIS_CMD_INLINE
},
643 {"blpop",blpopCommand
,-3,REDIS_CMD_INLINE
},
644 {"llen",llenCommand
,2,REDIS_CMD_INLINE
},
645 {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
},
646 {"lset",lsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
647 {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
},
648 {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
},
649 {"lrem",lremCommand
,4,REDIS_CMD_BULK
},
650 {"rpoplpush",rpoplpushcommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
651 {"sadd",saddCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
652 {"srem",sremCommand
,3,REDIS_CMD_BULK
},
653 {"smove",smoveCommand
,4,REDIS_CMD_BULK
},
654 {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
},
655 {"scard",scardCommand
,2,REDIS_CMD_INLINE
},
656 {"spop",spopCommand
,2,REDIS_CMD_INLINE
},
657 {"srandmember",srandmemberCommand
,2,REDIS_CMD_INLINE
},
658 {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
659 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
660 {"sunion",sunionCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
661 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
662 {"sdiff",sdiffCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
663 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
664 {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
},
665 {"zadd",zaddCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
666 {"zincrby",zincrbyCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
667 {"zrem",zremCommand
,3,REDIS_CMD_BULK
},
668 {"zremrangebyscore",zremrangebyscoreCommand
,4,REDIS_CMD_INLINE
},
669 {"zrange",zrangeCommand
,-4,REDIS_CMD_INLINE
},
670 {"zrangebyscore",zrangebyscoreCommand
,-4,REDIS_CMD_INLINE
},
671 {"zrevrange",zrevrangeCommand
,-4,REDIS_CMD_INLINE
},
672 {"zcard",zcardCommand
,2,REDIS_CMD_INLINE
},
673 {"zscore",zscoreCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
674 {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
675 {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
676 {"getset",getsetCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
677 {"mset",msetCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
678 {"msetnx",msetnxCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
679 {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
},
680 {"select",selectCommand
,2,REDIS_CMD_INLINE
},
681 {"move",moveCommand
,3,REDIS_CMD_INLINE
},
682 {"rename",renameCommand
,3,REDIS_CMD_INLINE
},
683 {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
},
684 {"expire",expireCommand
,3,REDIS_CMD_INLINE
},
685 {"expireat",expireatCommand
,3,REDIS_CMD_INLINE
},
686 {"keys",keysCommand
,2,REDIS_CMD_INLINE
},
687 {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
},
688 {"auth",authCommand
,2,REDIS_CMD_INLINE
},
689 {"ping",pingCommand
,1,REDIS_CMD_INLINE
},
690 {"echo",echoCommand
,2,REDIS_CMD_BULK
},
691 {"save",saveCommand
,1,REDIS_CMD_INLINE
},
692 {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
},
693 {"bgrewriteaof",bgrewriteaofCommand
,1,REDIS_CMD_INLINE
},
694 {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
},
695 {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
},
696 {"type",typeCommand
,2,REDIS_CMD_INLINE
},
697 {"multi",multiCommand
,1,REDIS_CMD_INLINE
},
698 {"exec",execCommand
,1,REDIS_CMD_INLINE
},
699 {"sync",syncCommand
,1,REDIS_CMD_INLINE
},
700 {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
},
701 {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
},
702 {"sort",sortCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
703 {"info",infoCommand
,1,REDIS_CMD_INLINE
},
704 {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
},
705 {"ttl",ttlCommand
,2,REDIS_CMD_INLINE
},
706 {"slaveof",slaveofCommand
,3,REDIS_CMD_INLINE
},
707 {"debug",debugCommand
,-2,REDIS_CMD_INLINE
},
711 /*============================ Utility functions ============================ */
713 /* Glob-style pattern matching. */
714 int stringmatchlen(const char *pattern
, int patternLen
,
715 const char *string
, int stringLen
, int nocase
)
720 while (pattern
[1] == '*') {
725 return 1; /* match */
727 if (stringmatchlen(pattern
+1, patternLen
-1,
728 string
, stringLen
, nocase
))
729 return 1; /* match */
733 return 0; /* no match */
737 return 0; /* no match */
747 not = pattern
[0] == '^';
754 if (pattern
[0] == '\\') {
757 if (pattern
[0] == string
[0])
759 } else if (pattern
[0] == ']') {
761 } else if (patternLen
== 0) {
765 } else if (pattern
[1] == '-' && patternLen
>= 3) {
766 int start
= pattern
[0];
767 int end
= pattern
[2];
775 start
= tolower(start
);
781 if (c
>= start
&& c
<= end
)
785 if (pattern
[0] == string
[0])
788 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
798 return 0; /* no match */
804 if (patternLen
>= 2) {
811 if (pattern
[0] != string
[0])
812 return 0; /* no match */
814 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
815 return 0; /* no match */
823 if (stringLen
== 0) {
824 while(*pattern
== '*') {
831 if (patternLen
== 0 && stringLen
== 0)
836 static void redisLog(int level
, const char *fmt
, ...) {
840 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
844 if (level
>= server
.verbosity
) {
850 strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
));
851 fprintf(fp
,"%s %c ",buf
,c
[level
]);
852 vfprintf(fp
, fmt
, ap
);
858 if (server
.logfile
) fclose(fp
);
861 /*====================== Hash table type implementation ==================== */
863 /* This is an hash table type that uses the SDS dynamic strings libary as
864 * keys and radis objects as values (objects can hold SDS strings,
867 static void dictVanillaFree(void *privdata
, void *val
)
869 DICT_NOTUSED(privdata
);
873 static void dictListDestructor(void *privdata
, void *val
)
875 DICT_NOTUSED(privdata
);
876 listRelease((list
*)val
);
879 static int sdsDictKeyCompare(void *privdata
, const void *key1
,
883 DICT_NOTUSED(privdata
);
885 l1
= sdslen((sds
)key1
);
886 l2
= sdslen((sds
)key2
);
887 if (l1
!= l2
) return 0;
888 return memcmp(key1
, key2
, l1
) == 0;
891 static void dictRedisObjectDestructor(void *privdata
, void *val
)
893 DICT_NOTUSED(privdata
);
895 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
899 static int dictObjKeyCompare(void *privdata
, const void *key1
,
902 const robj
*o1
= key1
, *o2
= key2
;
903 return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
906 static unsigned int dictObjHash(const void *key
) {
908 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
911 static int dictEncObjKeyCompare(void *privdata
, const void *key1
,
914 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
917 o1
= getDecodedObject(o1
);
918 o2
= getDecodedObject(o2
);
919 cmp
= sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
925 static unsigned int dictEncObjHash(const void *key
) {
926 robj
*o
= (robj
*) key
;
928 o
= getDecodedObject(o
);
929 unsigned int hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
934 static dictType setDictType
= {
935 dictEncObjHash
, /* hash function */
938 dictEncObjKeyCompare
, /* key compare */
939 dictRedisObjectDestructor
, /* key destructor */
940 NULL
/* val destructor */
943 static dictType zsetDictType
= {
944 dictEncObjHash
, /* hash function */
947 dictEncObjKeyCompare
, /* key compare */
948 dictRedisObjectDestructor
, /* key destructor */
949 dictVanillaFree
/* val destructor of malloc(sizeof(double)) */
952 static dictType hashDictType
= {
953 dictObjHash
, /* hash function */
956 dictObjKeyCompare
, /* key compare */
957 dictRedisObjectDestructor
, /* key destructor */
958 dictRedisObjectDestructor
/* val destructor */
961 /* Keylist hash table type has unencoded redis objects as keys and
962 * lists as values. It's used for blocking operations (BLPOP) */
963 static dictType keylistDictType
= {
964 dictObjHash
, /* hash function */
967 dictObjKeyCompare
, /* key compare */
968 dictRedisObjectDestructor
, /* key destructor */
969 dictListDestructor
/* val destructor */
972 /* ========================= Random utility functions ======================= */
974 /* Redis generally does not try to recover from out of memory conditions
975 * when allocating objects or strings, it is not clear if it will be possible
976 * to report this condition to the client since the networking layer itself
977 * is based on heap allocation for send buffers, so we simply abort.
978 * At least the code will be simpler to read... */
979 static void oom(const char *msg
) {
980 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
985 /* ====================== Redis server networking stuff ===================== */
986 static void closeTimedoutClients(void) {
989 time_t now
= time(NULL
);
991 listRewind(server
.clients
);
992 while ((ln
= listYield(server
.clients
)) != NULL
) {
993 c
= listNodeValue(ln
);
994 if (server
.maxidletime
&&
995 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
996 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
997 (now
- c
->lastinteraction
> server
.maxidletime
))
999 redisLog(REDIS_VERBOSE
,"Closing idle client");
1001 } else if (c
->flags
& REDIS_BLOCKED
) {
1002 if (c
->blockingto
!= 0 && c
->blockingto
< now
) {
1003 addReply(c
,shared
.nullmultibulk
);
1010 static int htNeedsResize(dict
*dict
) {
1011 long long size
, used
;
1013 size
= dictSlots(dict
);
1014 used
= dictSize(dict
);
1015 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
1016 (used
*100/size
< REDIS_HT_MINFILL
));
1019 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
1020 * we resize the hash table to save memory */
1021 static void tryResizeHashTables(void) {
1024 for (j
= 0; j
< server
.dbnum
; j
++) {
1025 if (htNeedsResize(server
.db
[j
].dict
)) {
1026 redisLog(REDIS_VERBOSE
,"The hash table %d is too sparse, resize it...",j
);
1027 dictResize(server
.db
[j
].dict
);
1028 redisLog(REDIS_VERBOSE
,"Hash table %d resized.",j
);
1030 if (htNeedsResize(server
.db
[j
].expires
))
1031 dictResize(server
.db
[j
].expires
);
1035 /* A background saving child (BGSAVE) terminated its work. Handle this. */
1036 void backgroundSaveDoneHandler(int statloc
) {
1037 int exitcode
= WEXITSTATUS(statloc
);
1038 int bysignal
= WIFSIGNALED(statloc
);
1040 if (!bysignal
&& exitcode
== 0) {
1041 redisLog(REDIS_NOTICE
,
1042 "Background saving terminated with success");
1044 server
.lastsave
= time(NULL
);
1045 } else if (!bysignal
&& exitcode
!= 0) {
1046 redisLog(REDIS_WARNING
, "Background saving error");
1048 redisLog(REDIS_WARNING
,
1049 "Background saving terminated by signal");
1050 rdbRemoveTempFile(server
.bgsavechildpid
);
1052 server
.bgsavechildpid
= -1;
1053 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1054 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1055 updateSlavesWaitingBgsave(exitcode
== 0 ? REDIS_OK
: REDIS_ERR
);
1058 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1060 void backgroundRewriteDoneHandler(int statloc
) {
1061 int exitcode
= WEXITSTATUS(statloc
);
1062 int bysignal
= WIFSIGNALED(statloc
);
1064 if (!bysignal
&& exitcode
== 0) {
1068 redisLog(REDIS_NOTICE
,
1069 "Background append only file rewriting terminated with success");
1070 /* Now it's time to flush the differences accumulated by the parent */
1071 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) server
.bgrewritechildpid
);
1072 fd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
1074 redisLog(REDIS_WARNING
, "Not able to open the temp append only file produced by the child: %s", strerror(errno
));
1077 /* Flush our data... */
1078 if (write(fd
,server
.bgrewritebuf
,sdslen(server
.bgrewritebuf
)) !=
1079 (signed) sdslen(server
.bgrewritebuf
)) {
1080 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
));
1084 redisLog(REDIS_NOTICE
,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server
.bgrewritebuf
));
1085 /* Now our work is to rename the temp file into the stable file. And
1086 * switch the file descriptor used by the server for append only. */
1087 if (rename(tmpfile
,server
.appendfilename
) == -1) {
1088 redisLog(REDIS_WARNING
,"Can't rename the temp append only file into the stable one: %s", strerror(errno
));
1092 /* Mission completed... almost */
1093 redisLog(REDIS_NOTICE
,"Append only file successfully rewritten.");
1094 if (server
.appendfd
!= -1) {
1095 /* If append only is actually enabled... */
1096 close(server
.appendfd
);
1097 server
.appendfd
= fd
;
1099 server
.appendseldb
= -1; /* Make sure it will issue SELECT */
1100 redisLog(REDIS_NOTICE
,"The new append only file was selected for future appends.");
1102 /* If append only is disabled we just generate a dump in this
1103 * format. Why not? */
1106 } else if (!bysignal
&& exitcode
!= 0) {
1107 redisLog(REDIS_WARNING
, "Background append only file rewriting error");
1109 redisLog(REDIS_WARNING
,
1110 "Background append only file rewriting terminated by signal");
1113 sdsfree(server
.bgrewritebuf
);
1114 server
.bgrewritebuf
= sdsempty();
1115 aofRemoveTempFile(server
.bgrewritechildpid
);
1116 server
.bgrewritechildpid
= -1;
1119 static int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
1120 int j
, loops
= server
.cronloops
++;
1121 REDIS_NOTUSED(eventLoop
);
1123 REDIS_NOTUSED(clientData
);
1125 /* We take a cached value of the unix time in the global state because
1126 * with virtual memory and aging there is to store the current time
1127 * in objects at every object access, and accuracy is not needed.
1128 * To access a global var is faster than calling time(NULL) */
1129 server
.unixtime
= time(NULL
);
1131 /* Update the global state with the amount of used memory */
1132 server
.usedmemory
= zmalloc_used_memory();
1134 /* Show some info about non-empty databases */
1135 for (j
= 0; j
< server
.dbnum
; j
++) {
1136 long long size
, used
, vkeys
;
1138 size
= dictSlots(server
.db
[j
].dict
);
1139 used
= dictSize(server
.db
[j
].dict
);
1140 vkeys
= dictSize(server
.db
[j
].expires
);
1141 if (!(loops
% 5) && (used
|| vkeys
)) {
1142 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
1143 /* dictPrintStats(server.dict); */
1147 /* We don't want to resize the hash tables while a bacground saving
1148 * is in progress: the saving child is created using fork() that is
1149 * implemented with a copy-on-write semantic in most modern systems, so
1150 * if we resize the HT while there is the saving child at work actually
1151 * a lot of memory movements in the parent will cause a lot of pages
1153 if (server
.bgsavechildpid
== -1) tryResizeHashTables();
1155 /* Show information about connected clients */
1157 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use, %d shared objects",
1158 listLength(server
.clients
)-listLength(server
.slaves
),
1159 listLength(server
.slaves
),
1161 dictSize(server
.sharingpool
));
1164 /* Close connections of timedout clients */
1165 if ((server
.maxidletime
&& !(loops
% 10)) || server
.blockedclients
)
1166 closeTimedoutClients();
1168 /* Check if a background saving or AOF rewrite in progress terminated */
1169 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
1173 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
1174 if (pid
== server
.bgsavechildpid
) {
1175 backgroundSaveDoneHandler(statloc
);
1177 backgroundRewriteDoneHandler(statloc
);
1181 /* If there is not a background saving in progress check if
1182 * we have to save now */
1183 time_t now
= time(NULL
);
1184 for (j
= 0; j
< server
.saveparamslen
; j
++) {
1185 struct saveparam
*sp
= server
.saveparams
+j
;
1187 if (server
.dirty
>= sp
->changes
&&
1188 now
-server
.lastsave
> sp
->seconds
) {
1189 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
1190 sp
->changes
, sp
->seconds
);
1191 rdbSaveBackground(server
.dbfilename
);
1197 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1198 * will use few CPU cycles if there are few expiring keys, otherwise
1199 * it will get more aggressive to avoid that too much memory is used by
1200 * keys that can be removed from the keyspace. */
1201 for (j
= 0; j
< server
.dbnum
; j
++) {
1203 redisDb
*db
= server
.db
+j
;
1205 /* Continue to expire if at the end of the cycle more than 25%
1206 * of the keys were expired. */
1208 long num
= dictSize(db
->expires
);
1209 time_t now
= time(NULL
);
1212 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
1213 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
1218 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
1219 t
= (time_t) dictGetEntryVal(de
);
1221 deleteKey(db
,dictGetEntryKey(de
));
1225 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
1228 /* Swap a few keys on disk if we are over the memory limit and VM
1229 * is enbled. Try to free objects from the free list first. */
1230 if (vmCanSwapOut()) {
1231 while (server
.vm_enabled
&& zmalloc_used_memory() >
1232 server
.vm_max_memory
)
1234 if (listLength(server
.objfreelist
)) {
1235 freeOneObjectFromFreelist();
1237 if (vmSwapOneObjectThreaded() == REDIS_ERR
) {
1238 if ((loops
% 30) == 0 && zmalloc_used_memory() >
1239 (server
.vm_max_memory
+server
.vm_max_memory
/10)) {
1240 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
1243 /* Note that we freed just one object, because anyway when
1244 * the I/O thread in charge to swap this object out will
1245 * do its work, the handler of completed jobs will try to swap
1246 * more objects if we are out of memory. */
1252 /* Check if we should connect to a MASTER */
1253 if (server
.replstate
== REDIS_REPL_CONNECT
) {
1254 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
1255 if (syncWithMaster() == REDIS_OK
) {
1256 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
1262 static void createSharedObjects(void) {
1263 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
1264 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
1265 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
1266 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
1267 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
1268 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
1269 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
1270 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
1271 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
1272 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
1273 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
1274 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
1275 "-ERR Operation against a key holding the wrong kind of value\r\n"));
1276 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
1277 "-ERR no such key\r\n"));
1278 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
1279 "-ERR syntax error\r\n"));
1280 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
1281 "-ERR source and destination objects are the same\r\n"));
1282 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
1283 "-ERR index out of range\r\n"));
1284 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
1285 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
1286 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
1287 shared
.select0
= createStringObject("select 0\r\n",10);
1288 shared
.select1
= createStringObject("select 1\r\n",10);
1289 shared
.select2
= createStringObject("select 2\r\n",10);
1290 shared
.select3
= createStringObject("select 3\r\n",10);
1291 shared
.select4
= createStringObject("select 4\r\n",10);
1292 shared
.select5
= createStringObject("select 5\r\n",10);
1293 shared
.select6
= createStringObject("select 6\r\n",10);
1294 shared
.select7
= createStringObject("select 7\r\n",10);
1295 shared
.select8
= createStringObject("select 8\r\n",10);
1296 shared
.select9
= createStringObject("select 9\r\n",10);
1299 static void appendServerSaveParams(time_t seconds
, int changes
) {
1300 server
.saveparams
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1));
1301 server
.saveparams
[server
.saveparamslen
].seconds
= seconds
;
1302 server
.saveparams
[server
.saveparamslen
].changes
= changes
;
1303 server
.saveparamslen
++;
1306 static void resetServerSaveParams() {
1307 zfree(server
.saveparams
);
1308 server
.saveparams
= NULL
;
1309 server
.saveparamslen
= 0;
1312 static void initServerConfig() {
1313 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
1314 server
.port
= REDIS_SERVERPORT
;
1315 server
.verbosity
= REDIS_VERBOSE
;
1316 server
.maxidletime
= REDIS_MAXIDLETIME
;
1317 server
.saveparams
= NULL
;
1318 server
.logfile
= NULL
; /* NULL = log on standard output */
1319 server
.bindaddr
= NULL
;
1320 server
.glueoutputbuf
= 1;
1321 server
.daemonize
= 0;
1322 server
.appendonly
= 0;
1323 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1324 server
.lastfsync
= time(NULL
);
1325 server
.appendfd
= -1;
1326 server
.appendseldb
= -1; /* Make sure the first time will not match */
1327 server
.pidfile
= "/var/run/redis.pid";
1328 server
.dbfilename
= "dump.rdb";
1329 server
.appendfilename
= "appendonly.aof";
1330 server
.requirepass
= NULL
;
1331 server
.shareobjects
= 0;
1332 server
.rdbcompression
= 1;
1333 server
.sharingpoolsize
= 1024;
1334 server
.maxclients
= 0;
1335 server
.blockedclients
= 0;
1336 server
.maxmemory
= 0;
1337 server
.vm_enabled
= 0;
1338 server
.vm_page_size
= 256; /* 256 bytes per page */
1339 server
.vm_pages
= 1024*1024*100; /* 104 millions of pages */
1340 server
.vm_max_memory
= 1024LL*1024*1024*1; /* 1 GB of RAM */
1341 server
.vm_max_threads
= 4;
1343 resetServerSaveParams();
1345 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1346 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1347 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1348 /* Replication related */
1350 server
.masterauth
= NULL
;
1351 server
.masterhost
= NULL
;
1352 server
.masterport
= 6379;
1353 server
.master
= NULL
;
1354 server
.replstate
= REDIS_REPL_NONE
;
1356 /* Double constants initialization */
1358 R_PosInf
= 1.0/R_Zero
;
1359 R_NegInf
= -1.0/R_Zero
;
1360 R_Nan
= R_Zero
/R_Zero
;
1363 static void initServer() {
1366 signal(SIGHUP
, SIG_IGN
);
1367 signal(SIGPIPE
, SIG_IGN
);
1368 setupSigSegvAction();
1370 server
.clients
= listCreate();
1371 server
.slaves
= listCreate();
1372 server
.monitors
= listCreate();
1373 server
.objfreelist
= listCreate();
1374 createSharedObjects();
1375 server
.el
= aeCreateEventLoop();
1376 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
1377 server
.sharingpool
= dictCreate(&setDictType
,NULL
);
1378 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
1379 if (server
.fd
== -1) {
1380 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
1383 for (j
= 0; j
< server
.dbnum
; j
++) {
1384 server
.db
[j
].dict
= dictCreate(&hashDictType
,NULL
);
1385 server
.db
[j
].expires
= dictCreate(&setDictType
,NULL
);
1386 server
.db
[j
].blockingkeys
= dictCreate(&keylistDictType
,NULL
);
1387 server
.db
[j
].id
= j
;
1389 server
.cronloops
= 0;
1390 server
.bgsavechildpid
= -1;
1391 server
.bgrewritechildpid
= -1;
1392 server
.bgrewritebuf
= sdsempty();
1393 server
.lastsave
= time(NULL
);
1395 server
.usedmemory
= 0;
1396 server
.stat_numcommands
= 0;
1397 server
.stat_numconnections
= 0;
1398 server
.stat_starttime
= time(NULL
);
1399 server
.unixtime
= time(NULL
);
1400 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
1401 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
1402 acceptHandler
, NULL
) == AE_ERR
) oom("creating file event");
1403 if (server
.vm_enabled
) {
1404 /* Listen for events in the threaded I/O pipe */
1405 if (aeCreateFileEvent(server
.el
, server
.io_ready_pipe_read
, AE_READABLE
,
1406 vmThreadedIOCompletedJob
, NULL
) == AE_ERR
)
1407 oom("creating file event");
1410 if (server
.appendonly
) {
1411 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
1412 if (server
.appendfd
== -1) {
1413 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
1419 if (server
.vm_enabled
) vmInit();
1422 /* Empty the whole database */
1423 static long long emptyDb() {
1425 long long removed
= 0;
1427 for (j
= 0; j
< server
.dbnum
; j
++) {
1428 removed
+= dictSize(server
.db
[j
].dict
);
1429 dictEmpty(server
.db
[j
].dict
);
1430 dictEmpty(server
.db
[j
].expires
);
1435 static int yesnotoi(char *s
) {
1436 if (!strcasecmp(s
,"yes")) return 1;
1437 else if (!strcasecmp(s
,"no")) return 0;
1441 /* I agree, this is a very rudimental way to load a configuration...
1442 will improve later if the config gets more complex */
1443 static void loadServerConfig(char *filename
) {
1445 char buf
[REDIS_CONFIGLINE_MAX
+1], *err
= NULL
;
1449 if (filename
[0] == '-' && filename
[1] == '\0')
1452 if ((fp
= fopen(filename
,"r")) == NULL
) {
1453 redisLog(REDIS_WARNING
,"Fatal error, can't open config file");
1458 while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) {
1464 line
= sdstrim(line
," \t\r\n");
1466 /* Skip comments and blank lines*/
1467 if (line
[0] == '#' || line
[0] == '\0') {
1472 /* Split into arguments */
1473 argv
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
);
1474 sdstolower(argv
[0]);
1476 /* Execute config directives */
1477 if (!strcasecmp(argv
[0],"timeout") && argc
== 2) {
1478 server
.maxidletime
= atoi(argv
[1]);
1479 if (server
.maxidletime
< 0) {
1480 err
= "Invalid timeout value"; goto loaderr
;
1482 } else if (!strcasecmp(argv
[0],"port") && argc
== 2) {
1483 server
.port
= atoi(argv
[1]);
1484 if (server
.port
< 1 || server
.port
> 65535) {
1485 err
= "Invalid port"; goto loaderr
;
1487 } else if (!strcasecmp(argv
[0],"bind") && argc
== 2) {
1488 server
.bindaddr
= zstrdup(argv
[1]);
1489 } else if (!strcasecmp(argv
[0],"save") && argc
== 3) {
1490 int seconds
= atoi(argv
[1]);
1491 int changes
= atoi(argv
[2]);
1492 if (seconds
< 1 || changes
< 0) {
1493 err
= "Invalid save parameters"; goto loaderr
;
1495 appendServerSaveParams(seconds
,changes
);
1496 } else if (!strcasecmp(argv
[0],"dir") && argc
== 2) {
1497 if (chdir(argv
[1]) == -1) {
1498 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s",
1499 argv
[1], strerror(errno
));
1502 } else if (!strcasecmp(argv
[0],"loglevel") && argc
== 2) {
1503 if (!strcasecmp(argv
[1],"debug")) server
.verbosity
= REDIS_DEBUG
;
1504 else if (!strcasecmp(argv
[1],"verbose")) server
.verbosity
= REDIS_VERBOSE
;
1505 else if (!strcasecmp(argv
[1],"notice")) server
.verbosity
= REDIS_NOTICE
;
1506 else if (!strcasecmp(argv
[1],"warning")) server
.verbosity
= REDIS_WARNING
;
1508 err
= "Invalid log level. Must be one of debug, notice, warning";
1511 } else if (!strcasecmp(argv
[0],"logfile") && argc
== 2) {
1514 server
.logfile
= zstrdup(argv
[1]);
1515 if (!strcasecmp(server
.logfile
,"stdout")) {
1516 zfree(server
.logfile
);
1517 server
.logfile
= NULL
;
1519 if (server
.logfile
) {
1520 /* Test if we are able to open the file. The server will not
1521 * be able to abort just for this problem later... */
1522 logfp
= fopen(server
.logfile
,"a");
1523 if (logfp
== NULL
) {
1524 err
= sdscatprintf(sdsempty(),
1525 "Can't open the log file: %s", strerror(errno
));
1530 } else if (!strcasecmp(argv
[0],"databases") && argc
== 2) {
1531 server
.dbnum
= atoi(argv
[1]);
1532 if (server
.dbnum
< 1) {
1533 err
= "Invalid number of databases"; goto loaderr
;
1535 } else if (!strcasecmp(argv
[0],"maxclients") && argc
== 2) {
1536 server
.maxclients
= atoi(argv
[1]);
1537 } else if (!strcasecmp(argv
[0],"maxmemory") && argc
== 2) {
1538 server
.maxmemory
= strtoll(argv
[1], NULL
, 10);
1539 } else if (!strcasecmp(argv
[0],"slaveof") && argc
== 3) {
1540 server
.masterhost
= sdsnew(argv
[1]);
1541 server
.masterport
= atoi(argv
[2]);
1542 server
.replstate
= REDIS_REPL_CONNECT
;
1543 } else if (!strcasecmp(argv
[0],"masterauth") && argc
== 2) {
1544 server
.masterauth
= zstrdup(argv
[1]);
1545 } else if (!strcasecmp(argv
[0],"glueoutputbuf") && argc
== 2) {
1546 if ((server
.glueoutputbuf
= yesnotoi(argv
[1])) == -1) {
1547 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1549 } else if (!strcasecmp(argv
[0],"shareobjects") && argc
== 2) {
1550 if ((server
.shareobjects
= yesnotoi(argv
[1])) == -1) {
1551 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1553 } else if (!strcasecmp(argv
[0],"rdbcompression") && argc
== 2) {
1554 if ((server
.rdbcompression
= yesnotoi(argv
[1])) == -1) {
1555 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1557 } else if (!strcasecmp(argv
[0],"shareobjectspoolsize") && argc
== 2) {
1558 server
.sharingpoolsize
= atoi(argv
[1]);
1559 if (server
.sharingpoolsize
< 1) {
1560 err
= "invalid object sharing pool size"; goto loaderr
;
1562 } else if (!strcasecmp(argv
[0],"daemonize") && argc
== 2) {
1563 if ((server
.daemonize
= yesnotoi(argv
[1])) == -1) {
1564 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1566 } else if (!strcasecmp(argv
[0],"appendonly") && argc
== 2) {
1567 if ((server
.appendonly
= yesnotoi(argv
[1])) == -1) {
1568 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1570 } else if (!strcasecmp(argv
[0],"appendfsync") && argc
== 2) {
1571 if (!strcasecmp(argv
[1],"no")) {
1572 server
.appendfsync
= APPENDFSYNC_NO
;
1573 } else if (!strcasecmp(argv
[1],"always")) {
1574 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1575 } else if (!strcasecmp(argv
[1],"everysec")) {
1576 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
1578 err
= "argument must be 'no', 'always' or 'everysec'";
1581 } else if (!strcasecmp(argv
[0],"requirepass") && argc
== 2) {
1582 server
.requirepass
= zstrdup(argv
[1]);
1583 } else if (!strcasecmp(argv
[0],"pidfile") && argc
== 2) {
1584 server
.pidfile
= zstrdup(argv
[1]);
1585 } else if (!strcasecmp(argv
[0],"dbfilename") && argc
== 2) {
1586 server
.dbfilename
= zstrdup(argv
[1]);
1587 } else if (!strcasecmp(argv
[0],"vm-enabled") && argc
== 2) {
1588 if ((server
.vm_enabled
= yesnotoi(argv
[1])) == -1) {
1589 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1591 } else if (!strcasecmp(argv
[0],"vm-max-memory") && argc
== 2) {
1592 server
.vm_max_memory
= strtoll(argv
[1], NULL
, 10);
1593 } else if (!strcasecmp(argv
[0],"vm-page-size") && argc
== 2) {
1594 server
.vm_page_size
= strtoll(argv
[1], NULL
, 10);
1595 } else if (!strcasecmp(argv
[0],"vm-pages") && argc
== 2) {
1596 server
.vm_pages
= strtoll(argv
[1], NULL
, 10);
1597 } else if (!strcasecmp(argv
[0],"vm-max-threads") && argc
== 2) {
1598 server
.vm_max_threads
= strtoll(argv
[1], NULL
, 10);
1600 err
= "Bad directive or wrong number of arguments"; goto loaderr
;
1602 for (j
= 0; j
< argc
; j
++)
1607 if (fp
!= stdin
) fclose(fp
);
1611 fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n");
1612 fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
);
1613 fprintf(stderr
, ">>> '%s'\n", line
);
1614 fprintf(stderr
, "%s\n", err
);
1618 static void freeClientArgv(redisClient
*c
) {
1621 for (j
= 0; j
< c
->argc
; j
++)
1622 decrRefCount(c
->argv
[j
]);
1623 for (j
= 0; j
< c
->mbargc
; j
++)
1624 decrRefCount(c
->mbargv
[j
]);
1629 static void freeClient(redisClient
*c
) {
1632 /* Note that if the client we are freeing is blocked into a blocking
1633 * call, we have to set querybuf to NULL *before* to call unblockClient()
1634 * to avoid processInputBuffer() will get called. Also it is important
1635 * to remove the file events after this, because this call adds
1636 * the READABLE event. */
1637 sdsfree(c
->querybuf
);
1639 if (c
->flags
& REDIS_BLOCKED
)
1642 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
1643 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1644 listRelease(c
->reply
);
1645 listRelease(c
->io_keys
);
1648 /* Remove from the list of clients */
1649 ln
= listSearchKey(server
.clients
,c
);
1650 redisAssert(ln
!= NULL
);
1651 listDelNode(server
.clients
,ln
);
1652 /* Remove from the list of clients waiting for VM operations */
1653 if (server
.vm_enabled
&& listLength(c
->io_keys
)) {
1654 ln
= listSearchKey(server
.io_clients
,c
);
1655 if (ln
) listDelNode(server
.io_clients
,ln
);
1656 listRelease(c
->io_keys
);
1659 if (c
->flags
& REDIS_SLAVE
) {
1660 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
1662 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
1663 ln
= listSearchKey(l
,c
);
1664 redisAssert(ln
!= NULL
);
1667 if (c
->flags
& REDIS_MASTER
) {
1668 server
.master
= NULL
;
1669 server
.replstate
= REDIS_REPL_CONNECT
;
1673 freeClientMultiState(c
);
1677 #define GLUEREPLY_UP_TO (1024)
1678 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
1680 char buf
[GLUEREPLY_UP_TO
];
1684 listRewind(c
->reply
);
1685 while((ln
= listYield(c
->reply
))) {
1689 objlen
= sdslen(o
->ptr
);
1690 if (copylen
+ objlen
<= GLUEREPLY_UP_TO
) {
1691 memcpy(buf
+copylen
,o
->ptr
,objlen
);
1693 listDelNode(c
->reply
,ln
);
1695 if (copylen
== 0) return;
1699 /* Now the output buffer is empty, add the new single element */
1700 o
= createObject(REDIS_STRING
,sdsnewlen(buf
,copylen
));
1701 listAddNodeHead(c
->reply
,o
);
1704 static void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1705 redisClient
*c
= privdata
;
1706 int nwritten
= 0, totwritten
= 0, objlen
;
1709 REDIS_NOTUSED(mask
);
1711 /* Use writev() if we have enough buffers to send */
1712 if (!server
.glueoutputbuf
&&
1713 listLength(c
->reply
) > REDIS_WRITEV_THRESHOLD
&&
1714 !(c
->flags
& REDIS_MASTER
))
1716 sendReplyToClientWritev(el
, fd
, privdata
, mask
);
1720 while(listLength(c
->reply
)) {
1721 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
1722 glueReplyBuffersIfNeeded(c
);
1724 o
= listNodeValue(listFirst(c
->reply
));
1725 objlen
= sdslen(o
->ptr
);
1728 listDelNode(c
->reply
,listFirst(c
->reply
));
1732 if (c
->flags
& REDIS_MASTER
) {
1733 /* Don't reply to a master */
1734 nwritten
= objlen
- c
->sentlen
;
1736 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen
- c
->sentlen
);
1737 if (nwritten
<= 0) break;
1739 c
->sentlen
+= nwritten
;
1740 totwritten
+= nwritten
;
1741 /* If we fully sent the object on head go to the next one */
1742 if (c
->sentlen
== objlen
) {
1743 listDelNode(c
->reply
,listFirst(c
->reply
));
1746 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
1747 * bytes, in a single threaded server it's a good idea to serve
1748 * other clients as well, even if a very large request comes from
1749 * super fast link that is always able to accept data (in real world
1750 * scenario think about 'KEYS *' against the loopback interfae) */
1751 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
) break;
1753 if (nwritten
== -1) {
1754 if (errno
== EAGAIN
) {
1757 redisLog(REDIS_VERBOSE
,
1758 "Error writing to client: %s", strerror(errno
));
1763 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
1764 if (listLength(c
->reply
) == 0) {
1766 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1770 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
)
1772 redisClient
*c
= privdata
;
1773 int nwritten
= 0, totwritten
= 0, objlen
, willwrite
;
1775 struct iovec iov
[REDIS_WRITEV_IOVEC_COUNT
];
1776 int offset
, ion
= 0;
1778 REDIS_NOTUSED(mask
);
1781 while (listLength(c
->reply
)) {
1782 offset
= c
->sentlen
;
1786 /* fill-in the iov[] array */
1787 for(node
= listFirst(c
->reply
); node
; node
= listNextNode(node
)) {
1788 o
= listNodeValue(node
);
1789 objlen
= sdslen(o
->ptr
);
1791 if (totwritten
+ objlen
- offset
> REDIS_MAX_WRITE_PER_EVENT
)
1794 if(ion
== REDIS_WRITEV_IOVEC_COUNT
)
1795 break; /* no more iovecs */
1797 iov
[ion
].iov_base
= ((char*)o
->ptr
) + offset
;
1798 iov
[ion
].iov_len
= objlen
- offset
;
1799 willwrite
+= objlen
- offset
;
1800 offset
= 0; /* just for the first item */
1807 /* write all collected blocks at once */
1808 if((nwritten
= writev(fd
, iov
, ion
)) < 0) {
1809 if (errno
!= EAGAIN
) {
1810 redisLog(REDIS_VERBOSE
,
1811 "Error writing to client: %s", strerror(errno
));
1818 totwritten
+= nwritten
;
1819 offset
= c
->sentlen
;
1821 /* remove written robjs from c->reply */
1822 while (nwritten
&& listLength(c
->reply
)) {
1823 o
= listNodeValue(listFirst(c
->reply
));
1824 objlen
= sdslen(o
->ptr
);
1826 if(nwritten
>= objlen
- offset
) {
1827 listDelNode(c
->reply
, listFirst(c
->reply
));
1828 nwritten
-= objlen
- offset
;
1832 c
->sentlen
+= nwritten
;
1840 c
->lastinteraction
= time(NULL
);
1842 if (listLength(c
->reply
) == 0) {
1844 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1848 static struct redisCommand
*lookupCommand(char *name
) {
1850 while(cmdTable
[j
].name
!= NULL
) {
1851 if (!strcasecmp(name
,cmdTable
[j
].name
)) return &cmdTable
[j
];
1857 /* resetClient prepare the client to process the next command */
1858 static void resetClient(redisClient
*c
) {
1864 /* Call() is the core of Redis execution of a command */
1865 static void call(redisClient
*c
, struct redisCommand
*cmd
) {
1868 dirty
= server
.dirty
;
1870 if (server
.appendonly
&& server
.dirty
-dirty
)
1871 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1872 if (server
.dirty
-dirty
&& listLength(server
.slaves
))
1873 replicationFeedSlaves(server
.slaves
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1874 if (listLength(server
.monitors
))
1875 replicationFeedSlaves(server
.monitors
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1876 server
.stat_numcommands
++;
1879 /* If this function gets called we already read a whole
1880 * command, argments are in the client argv/argc fields.
1881 * processCommand() execute the command or prepare the
1882 * server for a bulk read from the client.
1884 * If 1 is returned the client is still alive and valid and
1885 * and other operations can be performed by the caller. Otherwise
1886 * if 0 is returned the client was destroied (i.e. after QUIT). */
1887 static int processCommand(redisClient
*c
) {
1888 struct redisCommand
*cmd
;
1890 /* Free some memory if needed (maxmemory setting) */
1891 if (server
.maxmemory
) freeMemoryIfNeeded();
1893 /* Handle the multi bulk command type. This is an alternative protocol
1894 * supported by Redis in order to receive commands that are composed of
1895 * multiple binary-safe "bulk" arguments. The latency of processing is
1896 * a bit higher but this allows things like multi-sets, so if this
1897 * protocol is used only for MSET and similar commands this is a big win. */
1898 if (c
->multibulk
== 0 && c
->argc
== 1 && ((char*)(c
->argv
[0]->ptr
))[0] == '*') {
1899 c
->multibulk
= atoi(((char*)c
->argv
[0]->ptr
)+1);
1900 if (c
->multibulk
<= 0) {
1904 decrRefCount(c
->argv
[c
->argc
-1]);
1908 } else if (c
->multibulk
) {
1909 if (c
->bulklen
== -1) {
1910 if (((char*)c
->argv
[0]->ptr
)[0] != '$') {
1911 addReplySds(c
,sdsnew("-ERR multi bulk protocol error\r\n"));
1915 int bulklen
= atoi(((char*)c
->argv
[0]->ptr
)+1);
1916 decrRefCount(c
->argv
[0]);
1917 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
1919 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
1924 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
1928 c
->mbargv
= zrealloc(c
->mbargv
,(sizeof(robj
*))*(c
->mbargc
+1));
1929 c
->mbargv
[c
->mbargc
] = c
->argv
[0];
1933 if (c
->multibulk
== 0) {
1937 /* Here we need to swap the multi-bulk argc/argv with the
1938 * normal argc/argv of the client structure. */
1940 c
->argv
= c
->mbargv
;
1941 c
->mbargv
= auxargv
;
1944 c
->argc
= c
->mbargc
;
1945 c
->mbargc
= auxargc
;
1947 /* We need to set bulklen to something different than -1
1948 * in order for the code below to process the command without
1949 * to try to read the last argument of a bulk command as
1950 * a special argument. */
1952 /* continue below and process the command */
1959 /* -- end of multi bulk commands processing -- */
1961 /* The QUIT command is handled as a special case. Normal command
1962 * procs are unable to close the client connection safely */
1963 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
1967 cmd
= lookupCommand(c
->argv
[0]->ptr
);
1970 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
1971 (char*)c
->argv
[0]->ptr
));
1974 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
1975 (c
->argc
< -cmd
->arity
)) {
1977 sdscatprintf(sdsempty(),
1978 "-ERR wrong number of arguments for '%s' command\r\n",
1982 } else if (server
.maxmemory
&& cmd
->flags
& REDIS_CMD_DENYOOM
&& zmalloc_used_memory() > server
.maxmemory
) {
1983 addReplySds(c
,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
1986 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
1987 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
1989 decrRefCount(c
->argv
[c
->argc
-1]);
1990 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
1992 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
1997 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
1998 /* It is possible that the bulk read is already in the
1999 * buffer. Check this condition and handle it accordingly.
2000 * This is just a fast path, alternative to call processInputBuffer().
2001 * It's a good idea since the code is small and this condition
2002 * happens most of the times. */
2003 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
2004 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2006 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2011 /* Let's try to share objects on the command arguments vector */
2012 if (server
.shareobjects
) {
2014 for(j
= 1; j
< c
->argc
; j
++)
2015 c
->argv
[j
] = tryObjectSharing(c
->argv
[j
]);
2017 /* Let's try to encode the bulk object to save space. */
2018 if (cmd
->flags
& REDIS_CMD_BULK
)
2019 tryObjectEncoding(c
->argv
[c
->argc
-1]);
2021 /* Check if the user is authenticated */
2022 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
2023 addReplySds(c
,sdsnew("-ERR operation not permitted\r\n"));
2028 /* Exec the command */
2029 if (c
->flags
& REDIS_MULTI
&& cmd
->proc
!= execCommand
) {
2030 queueMultiCommand(c
,cmd
);
2031 addReply(c
,shared
.queued
);
2036 /* Prepare the client for the next command */
2037 if (c
->flags
& REDIS_CLOSE
) {
2045 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
2049 /* (args*2)+1 is enough room for args, spaces, newlines */
2050 robj
*static_outv
[REDIS_STATIC_ARGS
*2+1];
2052 if (argc
<= REDIS_STATIC_ARGS
) {
2055 outv
= zmalloc(sizeof(robj
*)*(argc
*2+1));
2058 for (j
= 0; j
< argc
; j
++) {
2059 if (j
!= 0) outv
[outc
++] = shared
.space
;
2060 if ((cmd
->flags
& REDIS_CMD_BULK
) && j
== argc
-1) {
2063 lenobj
= createObject(REDIS_STRING
,
2064 sdscatprintf(sdsempty(),"%lu\r\n",
2065 (unsigned long) stringObjectLen(argv
[j
])));
2066 lenobj
->refcount
= 0;
2067 outv
[outc
++] = lenobj
;
2069 outv
[outc
++] = argv
[j
];
2071 outv
[outc
++] = shared
.crlf
;
2073 /* Increment all the refcounts at start and decrement at end in order to
2074 * be sure to free objects if there is no slave in a replication state
2075 * able to be feed with commands */
2076 for (j
= 0; j
< outc
; j
++) incrRefCount(outv
[j
]);
2078 while((ln
= listYield(slaves
))) {
2079 redisClient
*slave
= ln
->value
;
2081 /* Don't feed slaves that are still waiting for BGSAVE to start */
2082 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) continue;
2084 /* Feed all the other slaves, MONITORs and so on */
2085 if (slave
->slaveseldb
!= dictid
) {
2089 case 0: selectcmd
= shared
.select0
; break;
2090 case 1: selectcmd
= shared
.select1
; break;
2091 case 2: selectcmd
= shared
.select2
; break;
2092 case 3: selectcmd
= shared
.select3
; break;
2093 case 4: selectcmd
= shared
.select4
; break;
2094 case 5: selectcmd
= shared
.select5
; break;
2095 case 6: selectcmd
= shared
.select6
; break;
2096 case 7: selectcmd
= shared
.select7
; break;
2097 case 8: selectcmd
= shared
.select8
; break;
2098 case 9: selectcmd
= shared
.select9
; break;
2100 selectcmd
= createObject(REDIS_STRING
,
2101 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
2102 selectcmd
->refcount
= 0;
2105 addReply(slave
,selectcmd
);
2106 slave
->slaveseldb
= dictid
;
2108 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
2110 for (j
= 0; j
< outc
; j
++) decrRefCount(outv
[j
]);
2111 if (outv
!= static_outv
) zfree(outv
);
2114 static void processInputBuffer(redisClient
*c
) {
2116 /* Before to process the input buffer, make sure the client is not
2117 * waitig for a blocking operation such as BLPOP. Note that the first
2118 * iteration the client is never blocked, otherwise the processInputBuffer
2119 * would not be called at all, but after the execution of the first commands
2120 * in the input buffer the client may be blocked, and the "goto again"
2121 * will try to reiterate. The following line will make it return asap. */
2122 if (c
->flags
& REDIS_BLOCKED
|| c
->flags
& REDIS_IO_WAIT
) return;
2123 if (c
->bulklen
== -1) {
2124 /* Read the first line of the query */
2125 char *p
= strchr(c
->querybuf
,'\n');
2132 query
= c
->querybuf
;
2133 c
->querybuf
= sdsempty();
2134 querylen
= 1+(p
-(query
));
2135 if (sdslen(query
) > querylen
) {
2136 /* leave data after the first line of the query in the buffer */
2137 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
2139 *p
= '\0'; /* remove "\n" */
2140 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
2141 sdsupdatelen(query
);
2143 /* Now we can split the query in arguments */
2144 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
2147 if (c
->argv
) zfree(c
->argv
);
2148 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
2150 for (j
= 0; j
< argc
; j
++) {
2151 if (sdslen(argv
[j
])) {
2152 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
2160 /* Execute the command. If the client is still valid
2161 * after processCommand() return and there is something
2162 * on the query buffer try to process the next command. */
2163 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2165 /* Nothing to process, argc == 0. Just process the query
2166 * buffer if it's not empty or return to the caller */
2167 if (sdslen(c
->querybuf
)) goto again
;
2170 } else if (sdslen(c
->querybuf
) >= REDIS_REQUEST_MAX_SIZE
) {
2171 redisLog(REDIS_VERBOSE
, "Client protocol error");
2176 /* Bulk read handling. Note that if we are at this point
2177 the client already sent a command terminated with a newline,
2178 we are reading the bulk data that is actually the last
2179 argument of the command. */
2180 int qbl
= sdslen(c
->querybuf
);
2182 if (c
->bulklen
<= qbl
) {
2183 /* Copy everything but the final CRLF as final argument */
2184 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2186 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2187 /* Process the command. If the client is still valid after
2188 * the processing and there is more data in the buffer
2189 * try to parse it. */
2190 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2196 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2197 redisClient
*c
= (redisClient
*) privdata
;
2198 char buf
[REDIS_IOBUF_LEN
];
2201 REDIS_NOTUSED(mask
);
2203 nread
= read(fd
, buf
, REDIS_IOBUF_LEN
);
2205 if (errno
== EAGAIN
) {
2208 redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
));
2212 } else if (nread
== 0) {
2213 redisLog(REDIS_VERBOSE
, "Client closed connection");
2218 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
2219 c
->lastinteraction
= time(NULL
);
2223 processInputBuffer(c
);
2226 static int selectDb(redisClient
*c
, int id
) {
2227 if (id
< 0 || id
>= server
.dbnum
)
2229 c
->db
= &server
.db
[id
];
2233 static void *dupClientReplyValue(void *o
) {
2234 incrRefCount((robj
*)o
);
2238 static redisClient
*createClient(int fd
) {
2239 redisClient
*c
= zmalloc(sizeof(*c
));
2241 anetNonBlock(NULL
,fd
);
2242 anetTcpNoDelay(NULL
,fd
);
2243 if (!c
) return NULL
;
2246 c
->querybuf
= sdsempty();
2255 c
->lastinteraction
= time(NULL
);
2256 c
->authenticated
= 0;
2257 c
->replstate
= REDIS_REPL_NONE
;
2258 c
->reply
= listCreate();
2259 listSetFreeMethod(c
->reply
,decrRefCount
);
2260 listSetDupMethod(c
->reply
,dupClientReplyValue
);
2261 c
->blockingkeys
= NULL
;
2262 c
->blockingkeysnum
= 0;
2263 c
->io_keys
= listCreate();
2264 listSetFreeMethod(c
->io_keys
,decrRefCount
);
2265 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
2266 readQueryFromClient
, c
) == AE_ERR
) {
2270 listAddNodeTail(server
.clients
,c
);
2271 initClientMultiState(c
);
2275 static void addReply(redisClient
*c
, robj
*obj
) {
2276 if (listLength(c
->reply
) == 0 &&
2277 (c
->replstate
== REDIS_REPL_NONE
||
2278 c
->replstate
== REDIS_REPL_ONLINE
) &&
2279 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
2280 sendReplyToClient
, c
) == AE_ERR
) return;
2282 if (server
.vm_enabled
&& obj
->storage
!= REDIS_VM_MEMORY
) {
2283 obj
= dupStringObject(obj
);
2284 obj
->refcount
= 0; /* getDecodedObject() will increment the refcount */
2286 listAddNodeTail(c
->reply
,getDecodedObject(obj
));
2289 static void addReplySds(redisClient
*c
, sds s
) {
2290 robj
*o
= createObject(REDIS_STRING
,s
);
2295 static void addReplyDouble(redisClient
*c
, double d
) {
2298 snprintf(buf
,sizeof(buf
),"%.17g",d
);
2299 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
2300 (unsigned long) strlen(buf
),buf
));
2303 static void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
2306 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
2307 len
= sdslen(obj
->ptr
);
2309 long n
= (long)obj
->ptr
;
2311 /* Compute how many bytes will take this integer as a radix 10 string */
2317 while((n
= n
/10) != 0) {
2321 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",(unsigned long)len
));
2324 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2329 REDIS_NOTUSED(mask
);
2330 REDIS_NOTUSED(privdata
);
2332 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
2333 if (cfd
== AE_ERR
) {
2334 redisLog(REDIS_VERBOSE
,"Accepting client connection: %s", server
.neterr
);
2337 redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
);
2338 if ((c
= createClient(cfd
)) == NULL
) {
2339 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
2340 close(cfd
); /* May be already closed, just ingore errors */
2343 /* If maxclient directive is set and this is one client more... close the
2344 * connection. Note that we create the client instead to check before
2345 * for this condition, since now the socket is already set in nonblocking
2346 * mode and we can send an error for free using the Kernel I/O */
2347 if (server
.maxclients
&& listLength(server
.clients
) > server
.maxclients
) {
2348 char *err
= "-ERR max number of clients reached\r\n";
2350 /* That's a best effort error message, don't check write errors */
2351 if (write(c
->fd
,err
,strlen(err
)) == -1) {
2352 /* Nothing to do, Just to avoid the warning... */
2357 server
.stat_numconnections
++;
2360 /* ======================= Redis objects implementation ===================== */
2362 static robj
*createObject(int type
, void *ptr
) {
2365 if (listLength(server
.objfreelist
)) {
2366 listNode
*head
= listFirst(server
.objfreelist
);
2367 o
= listNodeValue(head
);
2368 listDelNode(server
.objfreelist
,head
);
2370 if (server
.vm_enabled
) {
2371 o
= zmalloc(sizeof(*o
));
2373 o
= zmalloc(sizeof(*o
)-sizeof(struct redisObjectVM
));
2377 o
->encoding
= REDIS_ENCODING_RAW
;
2380 if (server
.vm_enabled
) {
2381 o
->vm
.atime
= server
.unixtime
;
2382 o
->storage
= REDIS_VM_MEMORY
;
2387 static robj
*createStringObject(char *ptr
, size_t len
) {
2388 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
2391 static robj
*dupStringObject(robj
*o
) {
2392 return createStringObject(o
->ptr
,sdslen(o
->ptr
));
2395 static robj
*createListObject(void) {
2396 list
*l
= listCreate();
2398 listSetFreeMethod(l
,decrRefCount
);
2399 return createObject(REDIS_LIST
,l
);
2402 static robj
*createSetObject(void) {
2403 dict
*d
= dictCreate(&setDictType
,NULL
);
2404 return createObject(REDIS_SET
,d
);
2407 static robj
*createZsetObject(void) {
2408 zset
*zs
= zmalloc(sizeof(*zs
));
2410 zs
->dict
= dictCreate(&zsetDictType
,NULL
);
2411 zs
->zsl
= zslCreate();
2412 return createObject(REDIS_ZSET
,zs
);
2415 static void freeStringObject(robj
*o
) {
2416 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2421 static void freeListObject(robj
*o
) {
2422 listRelease((list
*) o
->ptr
);
2425 static void freeSetObject(robj
*o
) {
2426 dictRelease((dict
*) o
->ptr
);
2429 static void freeZsetObject(robj
*o
) {
2432 dictRelease(zs
->dict
);
2437 static void freeHashObject(robj
*o
) {
2438 dictRelease((dict
*) o
->ptr
);
2441 static void incrRefCount(robj
*o
) {
2442 redisAssert(!server
.vm_enabled
|| o
->storage
== REDIS_VM_MEMORY
);
2446 static void decrRefCount(void *obj
) {
2449 /* Object is swapped out, or in the process of being loaded. */
2450 if (server
.vm_enabled
&&
2451 (o
->storage
== REDIS_VM_SWAPPED
|| o
->storage
== REDIS_VM_LOADING
))
2453 if (o
->storage
== REDIS_VM_SWAPPED
|| o
->storage
== REDIS_VM_LOADING
) {
2454 redisAssert(o
->refcount
== 1);
2456 if (o
->storage
== REDIS_VM_LOADING
) vmCancelThreadedIOJob(obj
);
2457 redisAssert(o
->type
== REDIS_STRING
);
2458 freeStringObject(o
);
2459 vmMarkPagesFree(o
->vm
.page
,o
->vm
.usedpages
);
2460 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2461 !listAddNodeHead(server
.objfreelist
,o
))
2463 server
.vm_stats_swapped_objects
--;
2466 /* Object is in memory, or in the process of being swapped out. */
2467 if (--(o
->refcount
) == 0) {
2468 if (server
.vm_enabled
&& o
->storage
== REDIS_VM_SWAPPING
)
2469 vmCancelThreadedIOJob(obj
);
2471 case REDIS_STRING
: freeStringObject(o
); break;
2472 case REDIS_LIST
: freeListObject(o
); break;
2473 case REDIS_SET
: freeSetObject(o
); break;
2474 case REDIS_ZSET
: freeZsetObject(o
); break;
2475 case REDIS_HASH
: freeHashObject(o
); break;
2476 default: redisAssert(0 != 0); break;
2478 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2479 !listAddNodeHead(server
.objfreelist
,o
))
2484 static robj
*lookupKey(redisDb
*db
, robj
*key
) {
2485 dictEntry
*de
= dictFind(db
->dict
,key
);
2487 robj
*key
= dictGetEntryKey(de
);
2488 robj
*val
= dictGetEntryVal(de
);
2490 if (server
.vm_enabled
) {
2491 if (key
->storage
== REDIS_VM_MEMORY
||
2492 key
->storage
== REDIS_VM_SWAPPING
)
2494 /* If we were swapping the object out, stop it, this key
2496 if (key
->storage
== REDIS_VM_SWAPPING
)
2497 vmCancelThreadedIOJob(key
);
2498 /* Update the access time of the key for the aging algorithm. */
2499 key
->vm
.atime
= server
.unixtime
;
2501 /* Our value was swapped on disk. Bring it at home. */
2502 redisAssert(val
== NULL
);
2503 val
= vmLoadObject(key
);
2504 dictGetEntryVal(de
) = val
;
2513 static robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
2514 expireIfNeeded(db
,key
);
2515 return lookupKey(db
,key
);
2518 static robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
2519 deleteIfVolatile(db
,key
);
2520 return lookupKey(db
,key
);
2523 static int deleteKey(redisDb
*db
, robj
*key
) {
2526 /* We need to protect key from destruction: after the first dictDelete()
2527 * it may happen that 'key' is no longer valid if we don't increment
2528 * it's count. This may happen when we get the object reference directly
2529 * from the hash table with dictRandomKey() or dict iterators */
2531 if (dictSize(db
->expires
)) dictDelete(db
->expires
,key
);
2532 retval
= dictDelete(db
->dict
,key
);
2535 return retval
== DICT_OK
;
2538 /* Try to share an object against the shared objects pool */
2539 static robj
*tryObjectSharing(robj
*o
) {
2540 struct dictEntry
*de
;
2543 if (o
== NULL
|| server
.shareobjects
== 0) return o
;
2545 redisAssert(o
->type
== REDIS_STRING
);
2546 de
= dictFind(server
.sharingpool
,o
);
2548 robj
*shared
= dictGetEntryKey(de
);
2550 c
= ((unsigned long) dictGetEntryVal(de
))+1;
2551 dictGetEntryVal(de
) = (void*) c
;
2552 incrRefCount(shared
);
2556 /* Here we are using a stream algorihtm: Every time an object is
2557 * shared we increment its count, everytime there is a miss we
2558 * recrement the counter of a random object. If this object reaches
2559 * zero we remove the object and put the current object instead. */
2560 if (dictSize(server
.sharingpool
) >=
2561 server
.sharingpoolsize
) {
2562 de
= dictGetRandomKey(server
.sharingpool
);
2563 redisAssert(de
!= NULL
);
2564 c
= ((unsigned long) dictGetEntryVal(de
))-1;
2565 dictGetEntryVal(de
) = (void*) c
;
2567 dictDelete(server
.sharingpool
,de
->key
);
2570 c
= 0; /* If the pool is empty we want to add this object */
2575 retval
= dictAdd(server
.sharingpool
,o
,(void*)1);
2576 redisAssert(retval
== DICT_OK
);
2583 /* Check if the nul-terminated string 's' can be represented by a long
2584 * (that is, is a number that fits into long without any other space or
2585 * character before or after the digits).
2587 * If so, the function returns REDIS_OK and *longval is set to the value
2588 * of the number. Otherwise REDIS_ERR is returned */
2589 static int isStringRepresentableAsLong(sds s
, long *longval
) {
2590 char buf
[32], *endptr
;
2594 value
= strtol(s
, &endptr
, 10);
2595 if (endptr
[0] != '\0') return REDIS_ERR
;
2596 slen
= snprintf(buf
,32,"%ld",value
);
2598 /* If the number converted back into a string is not identical
2599 * then it's not possible to encode the string as integer */
2600 if (sdslen(s
) != (unsigned)slen
|| memcmp(buf
,s
,slen
)) return REDIS_ERR
;
2601 if (longval
) *longval
= value
;
2605 /* Try to encode a string object in order to save space */
2606 static int tryObjectEncoding(robj
*o
) {
2610 if (o
->encoding
!= REDIS_ENCODING_RAW
)
2611 return REDIS_ERR
; /* Already encoded */
2613 /* It's not save to encode shared objects: shared objects can be shared
2614 * everywhere in the "object space" of Redis. Encoded objects can only
2615 * appear as "values" (and not, for instance, as keys) */
2616 if (o
->refcount
> 1) return REDIS_ERR
;
2618 /* Currently we try to encode only strings */
2619 redisAssert(o
->type
== REDIS_STRING
);
2621 /* Check if we can represent this string as a long integer */
2622 if (isStringRepresentableAsLong(s
,&value
) == REDIS_ERR
) return REDIS_ERR
;
2624 /* Ok, this object can be encoded */
2625 o
->encoding
= REDIS_ENCODING_INT
;
2627 o
->ptr
= (void*) value
;
2631 /* Get a decoded version of an encoded object (returned as a new object).
2632 * If the object is already raw-encoded just increment the ref count. */
2633 static robj
*getDecodedObject(robj
*o
) {
2636 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2640 if (o
->type
== REDIS_STRING
&& o
->encoding
== REDIS_ENCODING_INT
) {
2643 snprintf(buf
,32,"%ld",(long)o
->ptr
);
2644 dec
= createStringObject(buf
,strlen(buf
));
2647 redisAssert(1 != 1);
2651 /* Compare two string objects via strcmp() or alike.
2652 * Note that the objects may be integer-encoded. In such a case we
2653 * use snprintf() to get a string representation of the numbers on the stack
2654 * and compare the strings, it's much faster than calling getDecodedObject().
2656 * Important note: if objects are not integer encoded, but binary-safe strings,
2657 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
2659 static int compareStringObjects(robj
*a
, robj
*b
) {
2660 redisAssert(a
->type
== REDIS_STRING
&& b
->type
== REDIS_STRING
);
2661 char bufa
[128], bufb
[128], *astr
, *bstr
;
2664 if (a
== b
) return 0;
2665 if (a
->encoding
!= REDIS_ENCODING_RAW
) {
2666 snprintf(bufa
,sizeof(bufa
),"%ld",(long) a
->ptr
);
2672 if (b
->encoding
!= REDIS_ENCODING_RAW
) {
2673 snprintf(bufb
,sizeof(bufb
),"%ld",(long) b
->ptr
);
2679 return bothsds
? sdscmp(astr
,bstr
) : strcmp(astr
,bstr
);
2682 static size_t stringObjectLen(robj
*o
) {
2683 redisAssert(o
->type
== REDIS_STRING
);
2684 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2685 return sdslen(o
->ptr
);
2689 return snprintf(buf
,32,"%ld",(long)o
->ptr
);
2693 /*============================ RDB saving/loading =========================== */
2695 static int rdbSaveType(FILE *fp
, unsigned char type
) {
2696 if (fwrite(&type
,1,1,fp
) == 0) return -1;
2700 static int rdbSaveTime(FILE *fp
, time_t t
) {
2701 int32_t t32
= (int32_t) t
;
2702 if (fwrite(&t32
,4,1,fp
) == 0) return -1;
2706 /* check rdbLoadLen() comments for more info */
2707 static int rdbSaveLen(FILE *fp
, uint32_t len
) {
2708 unsigned char buf
[2];
2711 /* Save a 6 bit len */
2712 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
2713 if (fwrite(buf
,1,1,fp
) == 0) return -1;
2714 } else if (len
< (1<<14)) {
2715 /* Save a 14 bit len */
2716 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
2718 if (fwrite(buf
,2,1,fp
) == 0) return -1;
2720 /* Save a 32 bit len */
2721 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
2722 if (fwrite(buf
,1,1,fp
) == 0) return -1;
2724 if (fwrite(&len
,4,1,fp
) == 0) return -1;
2729 /* String objects in the form "2391" "-100" without any space and with a
2730 * range of values that can fit in an 8, 16 or 32 bit signed value can be
2731 * encoded as integers to save space */
2732 static int rdbTryIntegerEncoding(sds s
, unsigned char *enc
) {
2734 char *endptr
, buf
[32];
2736 /* Check if it's possible to encode this value as a number */
2737 value
= strtoll(s
, &endptr
, 10);
2738 if (endptr
[0] != '\0') return 0;
2739 snprintf(buf
,32,"%lld",value
);
2741 /* If the number converted back into a string is not identical
2742 * then it's not possible to encode the string as integer */
2743 if (strlen(buf
) != sdslen(s
) || memcmp(buf
,s
,sdslen(s
))) return 0;
2745 /* Finally check if it fits in our ranges */
2746 if (value
>= -(1<<7) && value
<= (1<<7)-1) {
2747 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT8
;
2748 enc
[1] = value
&0xFF;
2750 } else if (value
>= -(1<<15) && value
<= (1<<15)-1) {
2751 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
;
2752 enc
[1] = value
&0xFF;
2753 enc
[2] = (value
>>8)&0xFF;
2755 } else if (value
>= -((long long)1<<31) && value
<= ((long long)1<<31)-1) {
2756 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT32
;
2757 enc
[1] = value
&0xFF;
2758 enc
[2] = (value
>>8)&0xFF;
2759 enc
[3] = (value
>>16)&0xFF;
2760 enc
[4] = (value
>>24)&0xFF;
2767 static int rdbSaveLzfStringObject(FILE *fp
, robj
*obj
) {
2768 unsigned int comprlen
, outlen
;
2772 /* We require at least four bytes compression for this to be worth it */
2773 outlen
= sdslen(obj
->ptr
)-4;
2774 if (outlen
<= 0) return 0;
2775 if ((out
= zmalloc(outlen
+1)) == NULL
) return 0;
2776 comprlen
= lzf_compress(obj
->ptr
, sdslen(obj
->ptr
), out
, outlen
);
2777 if (comprlen
== 0) {
2781 /* Data compressed! Let's save it on disk */
2782 byte
= (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_LZF
;
2783 if (fwrite(&byte
,1,1,fp
) == 0) goto writeerr
;
2784 if (rdbSaveLen(fp
,comprlen
) == -1) goto writeerr
;
2785 if (rdbSaveLen(fp
,sdslen(obj
->ptr
)) == -1) goto writeerr
;
2786 if (fwrite(out
,comprlen
,1,fp
) == 0) goto writeerr
;
2795 /* Save a string objet as [len][data] on disk. If the object is a string
2796 * representation of an integer value we try to safe it in a special form */
2797 static int rdbSaveStringObjectRaw(FILE *fp
, robj
*obj
) {
2801 len
= sdslen(obj
->ptr
);
2803 /* Try integer encoding */
2805 unsigned char buf
[5];
2806 if ((enclen
= rdbTryIntegerEncoding(obj
->ptr
,buf
)) > 0) {
2807 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
2812 /* Try LZF compression - under 20 bytes it's unable to compress even
2813 * aaaaaaaaaaaaaaaaaa so skip it */
2814 if (server
.rdbcompression
&& len
> 20) {
2817 retval
= rdbSaveLzfStringObject(fp
,obj
);
2818 if (retval
== -1) return -1;
2819 if (retval
> 0) return 0;
2820 /* retval == 0 means data can't be compressed, save the old way */
2823 /* Store verbatim */
2824 if (rdbSaveLen(fp
,len
) == -1) return -1;
2825 if (len
&& fwrite(obj
->ptr
,len
,1,fp
) == 0) return -1;
2829 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
2830 static int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
2833 if (obj
->storage
== REDIS_VM_MEMORY
&&
2834 obj
->encoding
!= REDIS_ENCODING_RAW
)
2836 obj
= getDecodedObject(obj
);
2837 retval
= rdbSaveStringObjectRaw(fp
,obj
);
2840 /* This is a fast path when we are sure the object is not encoded.
2841 * Note that's any *faster* actually as we needed to add the conditional
2842 * but because this may happen in a background process we don't want
2843 * to touch the object fields with incr/decrRefCount in order to
2844 * preveny copy on write of pages.
2846 * Also incrRefCount() will have a failing assert() if we try to call
2847 * it against an object with storage != REDIS_VM_MEMORY. */
2848 retval
= rdbSaveStringObjectRaw(fp
,obj
);
2853 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
2854 * 8 bit integer specifing the length of the representation.
2855 * This 8 bit integer has special values in order to specify the following
2861 static int rdbSaveDoubleValue(FILE *fp
, double val
) {
2862 unsigned char buf
[128];
2868 } else if (!isfinite(val
)) {
2870 buf
[0] = (val
< 0) ? 255 : 254;
2872 snprintf((char*)buf
+1,sizeof(buf
)-1,"%.17g",val
);
2873 buf
[0] = strlen((char*)buf
+1);
2876 if (fwrite(buf
,len
,1,fp
) == 0) return -1;
2880 /* Save a Redis object. */
2881 static int rdbSaveObject(FILE *fp
, robj
*o
) {
2882 if (o
->type
== REDIS_STRING
) {
2883 /* Save a string value */
2884 if (rdbSaveStringObject(fp
,o
) == -1) return -1;
2885 } else if (o
->type
== REDIS_LIST
) {
2886 /* Save a list value */
2887 list
*list
= o
->ptr
;
2891 if (rdbSaveLen(fp
,listLength(list
)) == -1) return -1;
2892 while((ln
= listYield(list
))) {
2893 robj
*eleobj
= listNodeValue(ln
);
2895 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2897 } else if (o
->type
== REDIS_SET
) {
2898 /* Save a set value */
2900 dictIterator
*di
= dictGetIterator(set
);
2903 if (rdbSaveLen(fp
,dictSize(set
)) == -1) return -1;
2904 while((de
= dictNext(di
)) != NULL
) {
2905 robj
*eleobj
= dictGetEntryKey(de
);
2907 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2909 dictReleaseIterator(di
);
2910 } else if (o
->type
== REDIS_ZSET
) {
2911 /* Save a set value */
2913 dictIterator
*di
= dictGetIterator(zs
->dict
);
2916 if (rdbSaveLen(fp
,dictSize(zs
->dict
)) == -1) return -1;
2917 while((de
= dictNext(di
)) != NULL
) {
2918 robj
*eleobj
= dictGetEntryKey(de
);
2919 double *score
= dictGetEntryVal(de
);
2921 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2922 if (rdbSaveDoubleValue(fp
,*score
) == -1) return -1;
2924 dictReleaseIterator(di
);
2926 redisAssert(0 != 0);
2931 /* Return the length the object will have on disk if saved with
2932 * the rdbSaveObject() function. Currently we use a trick to get
2933 * this length with very little changes to the code. In the future
2934 * we could switch to a faster solution. */
2935 static off_t
rdbSavedObjectLen(robj
*o
) {
2936 static FILE *fp
= NULL
;
2938 if (fp
== NULL
) fp
= fopen("/dev/null","w");
2942 assert(rdbSaveObject(fp
,o
) != 1);
2946 /* Return the number of pages required to save this object in the swap file */
2947 static off_t
rdbSavedObjectPages(robj
*o
) {
2948 off_t bytes
= rdbSavedObjectLen(o
);
2950 return (bytes
+(server
.vm_page_size
-1))/server
.vm_page_size
;
2953 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
2954 static int rdbSave(char *filename
) {
2955 dictIterator
*di
= NULL
;
2960 time_t now
= time(NULL
);
2962 snprintf(tmpfile
,256,"temp-%d.rdb", (int) getpid());
2963 fp
= fopen(tmpfile
,"w");
2965 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
2968 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
2969 for (j
= 0; j
< server
.dbnum
; j
++) {
2970 redisDb
*db
= server
.db
+j
;
2972 if (dictSize(d
) == 0) continue;
2973 di
= dictGetIterator(d
);
2979 /* Write the SELECT DB opcode */
2980 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
2981 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
2983 /* Iterate this DB writing every entry */
2984 while((de
= dictNext(di
)) != NULL
) {
2985 robj
*key
= dictGetEntryKey(de
);
2986 robj
*o
= dictGetEntryVal(de
);
2987 time_t expiretime
= getExpire(db
,key
);
2989 /* Save the expire time */
2990 if (expiretime
!= -1) {
2991 /* If this key is already expired skip it */
2992 if (expiretime
< now
) continue;
2993 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
;
2994 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
;
2996 /* Save the key and associated value. This requires special
2997 * handling if the value is swapped out. */
2998 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
2999 key
->storage
== REDIS_VM_SWAPPING
) {
3000 /* Save type, key, value */
3001 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
3002 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3003 if (rdbSaveObject(fp
,o
) == -1) goto werr
;
3005 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
3007 /* Get a preview of the object in memory */
3008 po
= vmPreviewObject(key
);
3009 /* Also duplicate the key object, to pass around a standard
3011 newkey
= dupStringObject(key
);
3012 /* Save type, key, value */
3013 if (rdbSaveType(fp
,key
->vtype
) == -1) goto werr
;
3014 if (rdbSaveStringObject(fp
,newkey
) == -1) goto werr
;
3015 if (rdbSaveObject(fp
,po
) == -1) goto werr
;
3016 /* Remove the loaded object from memory */
3018 decrRefCount(newkey
);
3021 dictReleaseIterator(di
);
3024 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
3026 /* Make sure data will not remain on the OS's output buffers */
3031 /* Use RENAME to make sure the DB file is changed atomically only
3032 * if the generate DB file is ok. */
3033 if (rename(tmpfile
,filename
) == -1) {
3034 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destination: %s", strerror(errno
));
3038 redisLog(REDIS_NOTICE
,"DB saved on disk");
3040 server
.lastsave
= time(NULL
);
3046 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
3047 if (di
) dictReleaseIterator(di
);
3051 static int rdbSaveBackground(char *filename
) {
3054 if (server
.bgsavechildpid
!= -1) return REDIS_ERR
;
3055 if ((childpid
= fork()) == 0) {
3058 if (rdbSave(filename
) == REDIS_OK
) {
3065 if (childpid
== -1) {
3066 redisLog(REDIS_WARNING
,"Can't save in background: fork: %s",
3070 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
3071 server
.bgsavechildpid
= childpid
;
3074 return REDIS_OK
; /* unreached */
3077 static void rdbRemoveTempFile(pid_t childpid
) {
3080 snprintf(tmpfile
,256,"temp-%d.rdb", (int) childpid
);
3084 static int rdbLoadType(FILE *fp
) {
3086 if (fread(&type
,1,1,fp
) == 0) return -1;
3090 static time_t rdbLoadTime(FILE *fp
) {
3092 if (fread(&t32
,4,1,fp
) == 0) return -1;
3093 return (time_t) t32
;
3096 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
3097 * of this file for a description of how this are stored on disk.
3099 * isencoded is set to 1 if the readed length is not actually a length but
3100 * an "encoding type", check the above comments for more info */
3101 static uint32_t rdbLoadLen(FILE *fp
, int *isencoded
) {
3102 unsigned char buf
[2];
3106 if (isencoded
) *isencoded
= 0;
3107 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3108 type
= (buf
[0]&0xC0)>>6;
3109 if (type
== REDIS_RDB_6BITLEN
) {
3110 /* Read a 6 bit len */
3112 } else if (type
== REDIS_RDB_ENCVAL
) {
3113 /* Read a 6 bit len encoding type */
3114 if (isencoded
) *isencoded
= 1;
3116 } else if (type
== REDIS_RDB_14BITLEN
) {
3117 /* Read a 14 bit len */
3118 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3119 return ((buf
[0]&0x3F)<<8)|buf
[1];
3121 /* Read a 32 bit len */
3122 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
3127 static robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
) {
3128 unsigned char enc
[4];
3131 if (enctype
== REDIS_RDB_ENC_INT8
) {
3132 if (fread(enc
,1,1,fp
) == 0) return NULL
;
3133 val
= (signed char)enc
[0];
3134 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
3136 if (fread(enc
,2,1,fp
) == 0) return NULL
;
3137 v
= enc
[0]|(enc
[1]<<8);
3139 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
3141 if (fread(enc
,4,1,fp
) == 0) return NULL
;
3142 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
3145 val
= 0; /* anti-warning */
3148 return createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",val
));
3151 static robj
*rdbLoadLzfStringObject(FILE*fp
) {
3152 unsigned int len
, clen
;
3153 unsigned char *c
= NULL
;
3156 if ((clen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3157 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3158 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
3159 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
3160 if (fread(c
,clen
,1,fp
) == 0) goto err
;
3161 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
3163 return createObject(REDIS_STRING
,val
);
3170 static robj
*rdbLoadStringObject(FILE*fp
) {
3175 len
= rdbLoadLen(fp
,&isencoded
);
3178 case REDIS_RDB_ENC_INT8
:
3179 case REDIS_RDB_ENC_INT16
:
3180 case REDIS_RDB_ENC_INT32
:
3181 return tryObjectSharing(rdbLoadIntegerObject(fp
,len
));
3182 case REDIS_RDB_ENC_LZF
:
3183 return tryObjectSharing(rdbLoadLzfStringObject(fp
));
3189 if (len
== REDIS_RDB_LENERR
) return NULL
;
3190 val
= sdsnewlen(NULL
,len
);
3191 if (len
&& fread(val
,len
,1,fp
) == 0) {
3195 return tryObjectSharing(createObject(REDIS_STRING
,val
));
3198 /* For information about double serialization check rdbSaveDoubleValue() */
3199 static int rdbLoadDoubleValue(FILE *fp
, double *val
) {
3203 if (fread(&len
,1,1,fp
) == 0) return -1;
3205 case 255: *val
= R_NegInf
; return 0;
3206 case 254: *val
= R_PosInf
; return 0;
3207 case 253: *val
= R_Nan
; return 0;
3209 if (fread(buf
,len
,1,fp
) == 0) return -1;
3211 sscanf(buf
, "%lg", val
);
3216 /* Load a Redis object of the specified type from the specified file.
3217 * On success a newly allocated object is returned, otherwise NULL. */
3218 static robj
*rdbLoadObject(int type
, FILE *fp
) {
3221 if (type
== REDIS_STRING
) {
3222 /* Read string value */
3223 if ((o
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3224 tryObjectEncoding(o
);
3225 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
3226 /* Read list/set value */
3229 if ((listlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3230 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
3231 /* Load every single element of the list/set */
3235 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3236 tryObjectEncoding(ele
);
3237 if (type
== REDIS_LIST
) {
3238 listAddNodeTail((list
*)o
->ptr
,ele
);
3240 dictAdd((dict
*)o
->ptr
,ele
,NULL
);
3243 } else if (type
== REDIS_ZSET
) {
3244 /* Read list/set value */
3248 if ((zsetlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3249 o
= createZsetObject();
3251 /* Load every single element of the list/set */
3254 double *score
= zmalloc(sizeof(double));
3256 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3257 tryObjectEncoding(ele
);
3258 if (rdbLoadDoubleValue(fp
,score
) == -1) return NULL
;
3259 dictAdd(zs
->dict
,ele
,score
);
3260 zslInsert(zs
->zsl
,*score
,ele
);
3261 incrRefCount(ele
); /* added to skiplist */
3264 redisAssert(0 != 0);
3269 static int rdbLoad(char *filename
) {
3271 robj
*keyobj
= NULL
;
3273 int type
, retval
, rdbver
;
3274 dict
*d
= server
.db
[0].dict
;
3275 redisDb
*db
= server
.db
+0;
3277 time_t expiretime
= -1, now
= time(NULL
);
3278 long long loadedkeys
= 0;
3280 fp
= fopen(filename
,"r");
3281 if (!fp
) return REDIS_ERR
;
3282 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
3284 if (memcmp(buf
,"REDIS",5) != 0) {
3286 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
3289 rdbver
= atoi(buf
+5);
3292 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
3299 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3300 if (type
== REDIS_EXPIRETIME
) {
3301 if ((expiretime
= rdbLoadTime(fp
)) == -1) goto eoferr
;
3302 /* We read the time so we need to read the object type again */
3303 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3305 if (type
== REDIS_EOF
) break;
3306 /* Handle SELECT DB opcode as a special case */
3307 if (type
== REDIS_SELECTDB
) {
3308 if ((dbid
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
)
3310 if (dbid
>= (unsigned)server
.dbnum
) {
3311 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
3314 db
= server
.db
+dbid
;
3319 if ((keyobj
= rdbLoadStringObject(fp
)) == NULL
) goto eoferr
;
3321 if ((o
= rdbLoadObject(type
,fp
)) == NULL
) goto eoferr
;
3322 /* Add the new object in the hash table */
3323 retval
= dictAdd(d
,keyobj
,o
);
3324 if (retval
== DICT_ERR
) {
3325 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj
->ptr
);
3328 /* Set the expire time if needed */
3329 if (expiretime
!= -1) {
3330 setExpire(db
,keyobj
,expiretime
);
3331 /* Delete this key if already expired */
3332 if (expiretime
< now
) deleteKey(db
,keyobj
);
3336 /* Handle swapping while loading big datasets when VM is on */
3338 if (server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
3339 while (zmalloc_used_memory() > server
.vm_max_memory
) {
3340 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
3347 eoferr
: /* unexpected end of file is handled here with a fatal exit */
3348 if (keyobj
) decrRefCount(keyobj
);
3349 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
3351 return REDIS_ERR
; /* Just to avoid warning */
3354 /*================================== Commands =============================== */
3356 static void authCommand(redisClient
*c
) {
3357 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
3358 c
->authenticated
= 1;
3359 addReply(c
,shared
.ok
);
3361 c
->authenticated
= 0;
3362 addReplySds(c
,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
3366 static void pingCommand(redisClient
*c
) {
3367 addReply(c
,shared
.pong
);
3370 static void echoCommand(redisClient
*c
) {
3371 addReplyBulkLen(c
,c
->argv
[1]);
3372 addReply(c
,c
->argv
[1]);
3373 addReply(c
,shared
.crlf
);
3376 /*=================================== Strings =============================== */
3378 static void setGenericCommand(redisClient
*c
, int nx
) {
3381 if (nx
) deleteIfVolatile(c
->db
,c
->argv
[1]);
3382 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3383 if (retval
== DICT_ERR
) {
3385 /* If the key is about a swapped value, we want a new key object
3386 * to overwrite the old. So we delete the old key in the database.
3387 * This will also make sure that swap pages about the old object
3388 * will be marked as free. */
3389 if (deleteIfSwapped(c
->db
,c
->argv
[1]))
3390 incrRefCount(c
->argv
[1]);
3391 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3392 incrRefCount(c
->argv
[2]);
3394 addReply(c
,shared
.czero
);
3398 incrRefCount(c
->argv
[1]);
3399 incrRefCount(c
->argv
[2]);
3402 removeExpire(c
->db
,c
->argv
[1]);
3403 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3406 static void setCommand(redisClient
*c
) {
3407 setGenericCommand(c
,0);
3410 static void setnxCommand(redisClient
*c
) {
3411 setGenericCommand(c
,1);
3414 static int getGenericCommand(redisClient
*c
) {
3415 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3418 addReply(c
,shared
.nullbulk
);
3421 if (o
->type
!= REDIS_STRING
) {
3422 addReply(c
,shared
.wrongtypeerr
);
3425 addReplyBulkLen(c
,o
);
3427 addReply(c
,shared
.crlf
);
3433 static void getCommand(redisClient
*c
) {
3434 getGenericCommand(c
);
3437 static void getsetCommand(redisClient
*c
) {
3438 if (getGenericCommand(c
) == REDIS_ERR
) return;
3439 if (dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]) == DICT_ERR
) {
3440 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3442 incrRefCount(c
->argv
[1]);
3444 incrRefCount(c
->argv
[2]);
3446 removeExpire(c
->db
,c
->argv
[1]);
3449 static void mgetCommand(redisClient
*c
) {
3452 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
3453 for (j
= 1; j
< c
->argc
; j
++) {
3454 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[j
]);
3456 addReply(c
,shared
.nullbulk
);
3458 if (o
->type
!= REDIS_STRING
) {
3459 addReply(c
,shared
.nullbulk
);
3461 addReplyBulkLen(c
,o
);
3463 addReply(c
,shared
.crlf
);
3469 static void msetGenericCommand(redisClient
*c
, int nx
) {
3470 int j
, busykeys
= 0;
3472 if ((c
->argc
% 2) == 0) {
3473 addReplySds(c
,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
3476 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
3477 * set nothing at all if at least one already key exists. */
3479 for (j
= 1; j
< c
->argc
; j
+= 2) {
3480 if (lookupKeyWrite(c
->db
,c
->argv
[j
]) != NULL
) {
3486 addReply(c
, shared
.czero
);
3490 for (j
= 1; j
< c
->argc
; j
+= 2) {
3493 tryObjectEncoding(c
->argv
[j
+1]);
3494 retval
= dictAdd(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3495 if (retval
== DICT_ERR
) {
3496 dictReplace(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3497 incrRefCount(c
->argv
[j
+1]);
3499 incrRefCount(c
->argv
[j
]);
3500 incrRefCount(c
->argv
[j
+1]);
3502 removeExpire(c
->db
,c
->argv
[j
]);
3504 server
.dirty
+= (c
->argc
-1)/2;
3505 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3508 static void msetCommand(redisClient
*c
) {
3509 msetGenericCommand(c
,0);
3512 static void msetnxCommand(redisClient
*c
) {
3513 msetGenericCommand(c
,1);
3516 static void incrDecrCommand(redisClient
*c
, long long incr
) {
3521 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3525 if (o
->type
!= REDIS_STRING
) {
3530 if (o
->encoding
== REDIS_ENCODING_RAW
)
3531 value
= strtoll(o
->ptr
, &eptr
, 10);
3532 else if (o
->encoding
== REDIS_ENCODING_INT
)
3533 value
= (long)o
->ptr
;
3535 redisAssert(1 != 1);
3540 o
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
));
3541 tryObjectEncoding(o
);
3542 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],o
);
3543 if (retval
== DICT_ERR
) {
3544 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
3545 removeExpire(c
->db
,c
->argv
[1]);
3547 incrRefCount(c
->argv
[1]);
3550 addReply(c
,shared
.colon
);
3552 addReply(c
,shared
.crlf
);
3555 static void incrCommand(redisClient
*c
) {
3556 incrDecrCommand(c
,1);
3559 static void decrCommand(redisClient
*c
) {
3560 incrDecrCommand(c
,-1);
3563 static void incrbyCommand(redisClient
*c
) {
3564 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3565 incrDecrCommand(c
,incr
);
3568 static void decrbyCommand(redisClient
*c
) {
3569 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3570 incrDecrCommand(c
,-incr
);
3573 /* ========================= Type agnostic commands ========================= */
3575 static void delCommand(redisClient
*c
) {
3578 for (j
= 1; j
< c
->argc
; j
++) {
3579 if (deleteKey(c
->db
,c
->argv
[j
])) {
3586 addReply(c
,shared
.czero
);
3589 addReply(c
,shared
.cone
);
3592 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",deleted
));
3597 static void existsCommand(redisClient
*c
) {
3598 addReply(c
,lookupKeyRead(c
->db
,c
->argv
[1]) ? shared
.cone
: shared
.czero
);
3601 static void selectCommand(redisClient
*c
) {
3602 int id
= atoi(c
->argv
[1]->ptr
);
3604 if (selectDb(c
,id
) == REDIS_ERR
) {
3605 addReplySds(c
,sdsnew("-ERR invalid DB index\r\n"));
3607 addReply(c
,shared
.ok
);
3611 static void randomkeyCommand(redisClient
*c
) {
3615 de
= dictGetRandomKey(c
->db
->dict
);
3616 if (!de
|| expireIfNeeded(c
->db
,dictGetEntryKey(de
)) == 0) break;
3619 addReply(c
,shared
.plus
);
3620 addReply(c
,shared
.crlf
);
3622 addReply(c
,shared
.plus
);
3623 addReply(c
,dictGetEntryKey(de
));
3624 addReply(c
,shared
.crlf
);
3628 static void keysCommand(redisClient
*c
) {
3631 sds pattern
= c
->argv
[1]->ptr
;
3632 int plen
= sdslen(pattern
);
3633 unsigned long numkeys
= 0, keyslen
= 0;
3634 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
3636 di
= dictGetIterator(c
->db
->dict
);
3638 decrRefCount(lenobj
);
3639 while((de
= dictNext(di
)) != NULL
) {
3640 robj
*keyobj
= dictGetEntryKey(de
);
3642 sds key
= keyobj
->ptr
;
3643 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
3644 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
3645 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
3647 addReply(c
,shared
.space
);
3650 keyslen
+= sdslen(key
);
3654 dictReleaseIterator(di
);
3655 lenobj
->ptr
= sdscatprintf(sdsempty(),"$%lu\r\n",keyslen
+(numkeys
? (numkeys
-1) : 0));
3656 addReply(c
,shared
.crlf
);
3659 static void dbsizeCommand(redisClient
*c
) {
3661 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c
->db
->dict
)));
3664 static void lastsaveCommand(redisClient
*c
) {
3666 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
3669 static void typeCommand(redisClient
*c
) {
3673 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3678 case REDIS_STRING
: type
= "+string"; break;
3679 case REDIS_LIST
: type
= "+list"; break;
3680 case REDIS_SET
: type
= "+set"; break;
3681 case REDIS_ZSET
: type
= "+zset"; break;
3682 default: type
= "unknown"; break;
3685 addReplySds(c
,sdsnew(type
));
3686 addReply(c
,shared
.crlf
);
3689 static void saveCommand(redisClient
*c
) {
3690 if (server
.bgsavechildpid
!= -1) {
3691 addReplySds(c
,sdsnew("-ERR background save in progress\r\n"));
3694 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
3695 addReply(c
,shared
.ok
);
3697 addReply(c
,shared
.err
);
3701 static void bgsaveCommand(redisClient
*c
) {
3702 if (server
.bgsavechildpid
!= -1) {
3703 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
3706 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
3707 char *status
= "+Background saving started\r\n";
3708 addReplySds(c
,sdsnew(status
));
3710 addReply(c
,shared
.err
);
3714 static void shutdownCommand(redisClient
*c
) {
3715 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
3716 /* Kill the saving child if there is a background saving in progress.
3717 We want to avoid race conditions, for instance our saving child may
3718 overwrite the synchronous saving did by SHUTDOWN. */
3719 if (server
.bgsavechildpid
!= -1) {
3720 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
3721 kill(server
.bgsavechildpid
,SIGKILL
);
3722 rdbRemoveTempFile(server
.bgsavechildpid
);
3724 if (server
.appendonly
) {
3725 /* Append only file: fsync() the AOF and exit */
3726 fsync(server
.appendfd
);
3729 /* Snapshotting. Perform a SYNC SAVE and exit */
3730 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
3731 if (server
.daemonize
)
3732 unlink(server
.pidfile
);
3733 redisLog(REDIS_WARNING
,"%zu bytes used at exit",zmalloc_used_memory());
3734 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
3737 /* Ooops.. error saving! The best we can do is to continue operating.
3738 * Note that if there was a background saving process, in the next
3739 * cron() Redis will be notified that the background saving aborted,
3740 * handling special stuff like slaves pending for synchronization... */
3741 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
3742 addReplySds(c
,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
3747 static void renameGenericCommand(redisClient
*c
, int nx
) {
3750 /* To use the same key as src and dst is probably an error */
3751 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
3752 addReply(c
,shared
.sameobjecterr
);
3756 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3758 addReply(c
,shared
.nokeyerr
);
3762 deleteIfVolatile(c
->db
,c
->argv
[2]);
3763 if (dictAdd(c
->db
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
3766 addReply(c
,shared
.czero
);
3769 dictReplace(c
->db
->dict
,c
->argv
[2],o
);
3771 incrRefCount(c
->argv
[2]);
3773 deleteKey(c
->db
,c
->argv
[1]);
3775 addReply(c
,nx
? shared
.cone
: shared
.ok
);
3778 static void renameCommand(redisClient
*c
) {
3779 renameGenericCommand(c
,0);
3782 static void renamenxCommand(redisClient
*c
) {
3783 renameGenericCommand(c
,1);
3786 static void moveCommand(redisClient
*c
) {
3791 /* Obtain source and target DB pointers */
3794 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
3795 addReply(c
,shared
.outofrangeerr
);
3799 selectDb(c
,srcid
); /* Back to the source DB */
3801 /* If the user is moving using as target the same
3802 * DB as the source DB it is probably an error. */
3804 addReply(c
,shared
.sameobjecterr
);
3808 /* Check if the element exists and get a reference */
3809 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3811 addReply(c
,shared
.czero
);
3815 /* Try to add the element to the target DB */
3816 deleteIfVolatile(dst
,c
->argv
[1]);
3817 if (dictAdd(dst
->dict
,c
->argv
[1],o
) == DICT_ERR
) {
3818 addReply(c
,shared
.czero
);
3821 incrRefCount(c
->argv
[1]);
3824 /* OK! key moved, free the entry in the source DB */
3825 deleteKey(src
,c
->argv
[1]);
3827 addReply(c
,shared
.cone
);
3830 /* =================================== Lists ================================ */
3831 static void pushGenericCommand(redisClient
*c
, int where
) {
3835 lobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3837 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
3838 addReply(c
,shared
.ok
);
3841 lobj
= createListObject();
3843 if (where
== REDIS_HEAD
) {
3844 listAddNodeHead(list
,c
->argv
[2]);
3846 listAddNodeTail(list
,c
->argv
[2]);
3848 dictAdd(c
->db
->dict
,c
->argv
[1],lobj
);
3849 incrRefCount(c
->argv
[1]);
3850 incrRefCount(c
->argv
[2]);
3852 if (lobj
->type
!= REDIS_LIST
) {
3853 addReply(c
,shared
.wrongtypeerr
);
3856 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
3857 addReply(c
,shared
.ok
);
3861 if (where
== REDIS_HEAD
) {
3862 listAddNodeHead(list
,c
->argv
[2]);
3864 listAddNodeTail(list
,c
->argv
[2]);
3866 incrRefCount(c
->argv
[2]);
3869 addReply(c
,shared
.ok
);
3872 static void lpushCommand(redisClient
*c
) {
3873 pushGenericCommand(c
,REDIS_HEAD
);
3876 static void rpushCommand(redisClient
*c
) {
3877 pushGenericCommand(c
,REDIS_TAIL
);
3880 static void llenCommand(redisClient
*c
) {
3884 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3886 addReply(c
,shared
.czero
);
3889 if (o
->type
!= REDIS_LIST
) {
3890 addReply(c
,shared
.wrongtypeerr
);
3893 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(l
)));
3898 static void lindexCommand(redisClient
*c
) {
3900 int index
= atoi(c
->argv
[2]->ptr
);
3902 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3904 addReply(c
,shared
.nullbulk
);
3906 if (o
->type
!= REDIS_LIST
) {
3907 addReply(c
,shared
.wrongtypeerr
);
3909 list
*list
= o
->ptr
;
3912 ln
= listIndex(list
, index
);
3914 addReply(c
,shared
.nullbulk
);
3916 robj
*ele
= listNodeValue(ln
);
3917 addReplyBulkLen(c
,ele
);
3919 addReply(c
,shared
.crlf
);
3925 static void lsetCommand(redisClient
*c
) {
3927 int index
= atoi(c
->argv
[2]->ptr
);
3929 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3931 addReply(c
,shared
.nokeyerr
);
3933 if (o
->type
!= REDIS_LIST
) {
3934 addReply(c
,shared
.wrongtypeerr
);
3936 list
*list
= o
->ptr
;
3939 ln
= listIndex(list
, index
);
3941 addReply(c
,shared
.outofrangeerr
);
3943 robj
*ele
= listNodeValue(ln
);
3946 listNodeValue(ln
) = c
->argv
[3];
3947 incrRefCount(c
->argv
[3]);
3948 addReply(c
,shared
.ok
);
3955 static void popGenericCommand(redisClient
*c
, int where
) {
3958 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3960 addReply(c
,shared
.nullbulk
);
3962 if (o
->type
!= REDIS_LIST
) {
3963 addReply(c
,shared
.wrongtypeerr
);
3965 list
*list
= o
->ptr
;
3968 if (where
== REDIS_HEAD
)
3969 ln
= listFirst(list
);
3971 ln
= listLast(list
);
3974 addReply(c
,shared
.nullbulk
);
3976 robj
*ele
= listNodeValue(ln
);
3977 addReplyBulkLen(c
,ele
);
3979 addReply(c
,shared
.crlf
);
3980 listDelNode(list
,ln
);
3987 static void lpopCommand(redisClient
*c
) {
3988 popGenericCommand(c
,REDIS_HEAD
);
3991 static void rpopCommand(redisClient
*c
) {
3992 popGenericCommand(c
,REDIS_TAIL
);
3995 static void lrangeCommand(redisClient
*c
) {
3997 int start
= atoi(c
->argv
[2]->ptr
);
3998 int end
= atoi(c
->argv
[3]->ptr
);
4000 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4002 addReply(c
,shared
.nullmultibulk
);
4004 if (o
->type
!= REDIS_LIST
) {
4005 addReply(c
,shared
.wrongtypeerr
);
4007 list
*list
= o
->ptr
;
4009 int llen
= listLength(list
);
4013 /* convert negative indexes */
4014 if (start
< 0) start
= llen
+start
;
4015 if (end
< 0) end
= llen
+end
;
4016 if (start
< 0) start
= 0;
4017 if (end
< 0) end
= 0;
4019 /* indexes sanity checks */
4020 if (start
> end
|| start
>= llen
) {
4021 /* Out of range start or start > end result in empty list */
4022 addReply(c
,shared
.emptymultibulk
);
4025 if (end
>= llen
) end
= llen
-1;
4026 rangelen
= (end
-start
)+1;
4028 /* Return the result in form of a multi-bulk reply */
4029 ln
= listIndex(list
, start
);
4030 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
4031 for (j
= 0; j
< rangelen
; j
++) {
4032 ele
= listNodeValue(ln
);
4033 addReplyBulkLen(c
,ele
);
4035 addReply(c
,shared
.crlf
);
4042 static void ltrimCommand(redisClient
*c
) {
4044 int start
= atoi(c
->argv
[2]->ptr
);
4045 int end
= atoi(c
->argv
[3]->ptr
);
4047 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4049 addReply(c
,shared
.ok
);
4051 if (o
->type
!= REDIS_LIST
) {
4052 addReply(c
,shared
.wrongtypeerr
);
4054 list
*list
= o
->ptr
;
4056 int llen
= listLength(list
);
4057 int j
, ltrim
, rtrim
;
4059 /* convert negative indexes */
4060 if (start
< 0) start
= llen
+start
;
4061 if (end
< 0) end
= llen
+end
;
4062 if (start
< 0) start
= 0;
4063 if (end
< 0) end
= 0;
4065 /* indexes sanity checks */
4066 if (start
> end
|| start
>= llen
) {
4067 /* Out of range start or start > end result in empty list */
4071 if (end
>= llen
) end
= llen
-1;
4076 /* Remove list elements to perform the trim */
4077 for (j
= 0; j
< ltrim
; j
++) {
4078 ln
= listFirst(list
);
4079 listDelNode(list
,ln
);
4081 for (j
= 0; j
< rtrim
; j
++) {
4082 ln
= listLast(list
);
4083 listDelNode(list
,ln
);
4086 addReply(c
,shared
.ok
);
4091 static void lremCommand(redisClient
*c
) {
4094 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4096 addReply(c
,shared
.czero
);
4098 if (o
->type
!= REDIS_LIST
) {
4099 addReply(c
,shared
.wrongtypeerr
);
4101 list
*list
= o
->ptr
;
4102 listNode
*ln
, *next
;
4103 int toremove
= atoi(c
->argv
[2]->ptr
);
4108 toremove
= -toremove
;
4111 ln
= fromtail
? list
->tail
: list
->head
;
4113 robj
*ele
= listNodeValue(ln
);
4115 next
= fromtail
? ln
->prev
: ln
->next
;
4116 if (compareStringObjects(ele
,c
->argv
[3]) == 0) {
4117 listDelNode(list
,ln
);
4120 if (toremove
&& removed
== toremove
) break;
4124 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
4129 /* This is the semantic of this command:
4130 * RPOPLPUSH srclist dstlist:
4131 * IF LLEN(srclist) > 0
4132 * element = RPOP srclist
4133 * LPUSH dstlist element
4140 * The idea is to be able to get an element from a list in a reliable way
4141 * since the element is not just returned but pushed against another list
4142 * as well. This command was originally proposed by Ezra Zygmuntowicz.
4144 static void rpoplpushcommand(redisClient
*c
) {
4147 sobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4149 addReply(c
,shared
.nullbulk
);
4151 if (sobj
->type
!= REDIS_LIST
) {
4152 addReply(c
,shared
.wrongtypeerr
);
4154 list
*srclist
= sobj
->ptr
;
4155 listNode
*ln
= listLast(srclist
);
4158 addReply(c
,shared
.nullbulk
);
4160 robj
*dobj
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4161 robj
*ele
= listNodeValue(ln
);
4164 if (dobj
&& dobj
->type
!= REDIS_LIST
) {
4165 addReply(c
,shared
.wrongtypeerr
);
4169 /* Add the element to the target list (unless it's directly
4170 * passed to some BLPOP-ing client */
4171 if (!handleClientsWaitingListPush(c
,c
->argv
[2],ele
)) {
4173 /* Create the list if the key does not exist */
4174 dobj
= createListObject();
4175 dictAdd(c
->db
->dict
,c
->argv
[2],dobj
);
4176 incrRefCount(c
->argv
[2]);
4178 dstlist
= dobj
->ptr
;
4179 listAddNodeHead(dstlist
,ele
);
4183 /* Send the element to the client as reply as well */
4184 addReplyBulkLen(c
,ele
);
4186 addReply(c
,shared
.crlf
);
4188 /* Finally remove the element from the source list */
4189 listDelNode(srclist
,ln
);
4197 /* ==================================== Sets ================================ */
4199 static void saddCommand(redisClient
*c
) {
4202 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4204 set
= createSetObject();
4205 dictAdd(c
->db
->dict
,c
->argv
[1],set
);
4206 incrRefCount(c
->argv
[1]);
4208 if (set
->type
!= REDIS_SET
) {
4209 addReply(c
,shared
.wrongtypeerr
);
4213 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
4214 incrRefCount(c
->argv
[2]);
4216 addReply(c
,shared
.cone
);
4218 addReply(c
,shared
.czero
);
4222 static void sremCommand(redisClient
*c
) {
4225 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4227 addReply(c
,shared
.czero
);
4229 if (set
->type
!= REDIS_SET
) {
4230 addReply(c
,shared
.wrongtypeerr
);
4233 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
4235 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4236 addReply(c
,shared
.cone
);
4238 addReply(c
,shared
.czero
);
4243 static void smoveCommand(redisClient
*c
) {
4244 robj
*srcset
, *dstset
;
4246 srcset
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4247 dstset
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4249 /* If the source key does not exist return 0, if it's of the wrong type
4251 if (srcset
== NULL
|| srcset
->type
!= REDIS_SET
) {
4252 addReply(c
, srcset
? shared
.wrongtypeerr
: shared
.czero
);
4255 /* Error if the destination key is not a set as well */
4256 if (dstset
&& dstset
->type
!= REDIS_SET
) {
4257 addReply(c
,shared
.wrongtypeerr
);
4260 /* Remove the element from the source set */
4261 if (dictDelete(srcset
->ptr
,c
->argv
[3]) == DICT_ERR
) {
4262 /* Key not found in the src set! return zero */
4263 addReply(c
,shared
.czero
);
4267 /* Add the element to the destination set */
4269 dstset
= createSetObject();
4270 dictAdd(c
->db
->dict
,c
->argv
[2],dstset
);
4271 incrRefCount(c
->argv
[2]);
4273 if (dictAdd(dstset
->ptr
,c
->argv
[3],NULL
) == DICT_OK
)
4274 incrRefCount(c
->argv
[3]);
4275 addReply(c
,shared
.cone
);
4278 static void sismemberCommand(redisClient
*c
) {
4281 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
4283 addReply(c
,shared
.czero
);
4285 if (set
->type
!= REDIS_SET
) {
4286 addReply(c
,shared
.wrongtypeerr
);
4289 if (dictFind(set
->ptr
,c
->argv
[2]))
4290 addReply(c
,shared
.cone
);
4292 addReply(c
,shared
.czero
);
4296 static void scardCommand(redisClient
*c
) {
4300 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4302 addReply(c
,shared
.czero
);
4305 if (o
->type
!= REDIS_SET
) {
4306 addReply(c
,shared
.wrongtypeerr
);
4309 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4315 static void spopCommand(redisClient
*c
) {
4319 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4321 addReply(c
,shared
.nullbulk
);
4323 if (set
->type
!= REDIS_SET
) {
4324 addReply(c
,shared
.wrongtypeerr
);
4327 de
= dictGetRandomKey(set
->ptr
);
4329 addReply(c
,shared
.nullbulk
);
4331 robj
*ele
= dictGetEntryKey(de
);
4333 addReplyBulkLen(c
,ele
);
4335 addReply(c
,shared
.crlf
);
4336 dictDelete(set
->ptr
,ele
);
4337 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4343 static void srandmemberCommand(redisClient
*c
) {
4347 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
4349 addReply(c
,shared
.nullbulk
);
4351 if (set
->type
!= REDIS_SET
) {
4352 addReply(c
,shared
.wrongtypeerr
);
4355 de
= dictGetRandomKey(set
->ptr
);
4357 addReply(c
,shared
.nullbulk
);
4359 robj
*ele
= dictGetEntryKey(de
);
4361 addReplyBulkLen(c
,ele
);
4363 addReply(c
,shared
.crlf
);
4368 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
4369 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
4371 return dictSize(*d1
)-dictSize(*d2
);
4374 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, unsigned long setsnum
, robj
*dstkey
) {
4375 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4378 robj
*lenobj
= NULL
, *dstset
= NULL
;
4379 unsigned long j
, cardinality
= 0;
4381 for (j
= 0; j
< setsnum
; j
++) {
4385 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4386 lookupKeyRead(c
->db
,setskeys
[j
]);
4390 if (deleteKey(c
->db
,dstkey
))
4392 addReply(c
,shared
.czero
);
4394 addReply(c
,shared
.nullmultibulk
);
4398 if (setobj
->type
!= REDIS_SET
) {
4400 addReply(c
,shared
.wrongtypeerr
);
4403 dv
[j
] = setobj
->ptr
;
4405 /* Sort sets from the smallest to largest, this will improve our
4406 * algorithm's performace */
4407 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
4409 /* The first thing we should output is the total number of elements...
4410 * since this is a multi-bulk write, but at this stage we don't know
4411 * the intersection set size, so we use a trick, append an empty object
4412 * to the output list and save the pointer to later modify it with the
4415 lenobj
= createObject(REDIS_STRING
,NULL
);
4417 decrRefCount(lenobj
);
4419 /* If we have a target key where to store the resulting set
4420 * create this key with an empty set inside */
4421 dstset
= createSetObject();
4424 /* Iterate all the elements of the first (smallest) set, and test
4425 * the element against all the other sets, if at least one set does
4426 * not include the element it is discarded */
4427 di
= dictGetIterator(dv
[0]);
4429 while((de
= dictNext(di
)) != NULL
) {
4432 for (j
= 1; j
< setsnum
; j
++)
4433 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
4435 continue; /* at least one set does not contain the member */
4436 ele
= dictGetEntryKey(de
);
4438 addReplyBulkLen(c
,ele
);
4440 addReply(c
,shared
.crlf
);
4443 dictAdd(dstset
->ptr
,ele
,NULL
);
4447 dictReleaseIterator(di
);
4450 /* Store the resulting set into the target */
4451 deleteKey(c
->db
,dstkey
);
4452 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4453 incrRefCount(dstkey
);
4457 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",cardinality
);
4459 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4460 dictSize((dict
*)dstset
->ptr
)));
4466 static void sinterCommand(redisClient
*c
) {
4467 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
4470 static void sinterstoreCommand(redisClient
*c
) {
4471 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
4474 #define REDIS_OP_UNION 0
4475 #define REDIS_OP_DIFF 1
4477 static void sunionDiffGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
, int op
) {
4478 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4481 robj
*dstset
= NULL
;
4482 int j
, cardinality
= 0;
4484 for (j
= 0; j
< setsnum
; j
++) {
4488 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4489 lookupKeyRead(c
->db
,setskeys
[j
]);
4494 if (setobj
->type
!= REDIS_SET
) {
4496 addReply(c
,shared
.wrongtypeerr
);
4499 dv
[j
] = setobj
->ptr
;
4502 /* We need a temp set object to store our union. If the dstkey
4503 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
4504 * this set object will be the resulting object to set into the target key*/
4505 dstset
= createSetObject();
4507 /* Iterate all the elements of all the sets, add every element a single
4508 * time to the result set */
4509 for (j
= 0; j
< setsnum
; j
++) {
4510 if (op
== REDIS_OP_DIFF
&& j
== 0 && !dv
[j
]) break; /* result set is empty */
4511 if (!dv
[j
]) continue; /* non existing keys are like empty sets */
4513 di
= dictGetIterator(dv
[j
]);
4515 while((de
= dictNext(di
)) != NULL
) {
4518 /* dictAdd will not add the same element multiple times */
4519 ele
= dictGetEntryKey(de
);
4520 if (op
== REDIS_OP_UNION
|| j
== 0) {
4521 if (dictAdd(dstset
->ptr
,ele
,NULL
) == DICT_OK
) {
4525 } else if (op
== REDIS_OP_DIFF
) {
4526 if (dictDelete(dstset
->ptr
,ele
) == DICT_OK
) {
4531 dictReleaseIterator(di
);
4533 if (op
== REDIS_OP_DIFF
&& cardinality
== 0) break; /* result set is empty */
4536 /* Output the content of the resulting set, if not in STORE mode */
4538 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",cardinality
));
4539 di
= dictGetIterator(dstset
->ptr
);
4540 while((de
= dictNext(di
)) != NULL
) {
4543 ele
= dictGetEntryKey(de
);
4544 addReplyBulkLen(c
,ele
);
4546 addReply(c
,shared
.crlf
);
4548 dictReleaseIterator(di
);
4550 /* If we have a target key where to store the resulting set
4551 * create this key with the result set inside */
4552 deleteKey(c
->db
,dstkey
);
4553 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4554 incrRefCount(dstkey
);
4559 decrRefCount(dstset
);
4561 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4562 dictSize((dict
*)dstset
->ptr
)));
4568 static void sunionCommand(redisClient
*c
) {
4569 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_UNION
);
4572 static void sunionstoreCommand(redisClient
*c
) {
4573 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_UNION
);
4576 static void sdiffCommand(redisClient
*c
) {
4577 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_DIFF
);
4580 static void sdiffstoreCommand(redisClient
*c
) {
4581 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_DIFF
);
4584 /* ==================================== ZSets =============================== */
4586 /* ZSETs are ordered sets using two data structures to hold the same elements
4587 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
4590 * The elements are added to an hash table mapping Redis objects to scores.
4591 * At the same time the elements are added to a skip list mapping scores
4592 * to Redis objects (so objects are sorted by scores in this "view"). */
4594 /* This skiplist implementation is almost a C translation of the original
4595 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
4596 * Alternative to Balanced Trees", modified in three ways:
4597 * a) this implementation allows for repeated values.
4598 * b) the comparison is not just by key (our 'score') but by satellite data.
4599 * c) there is a back pointer, so it's a doubly linked list with the back
4600 * pointers being only at "level 1". This allows to traverse the list
4601 * from tail to head, useful for ZREVRANGE. */
4603 static zskiplistNode
*zslCreateNode(int level
, double score
, robj
*obj
) {
4604 zskiplistNode
*zn
= zmalloc(sizeof(*zn
));
4606 zn
->forward
= zmalloc(sizeof(zskiplistNode
*) * level
);
4612 static zskiplist
*zslCreate(void) {
4616 zsl
= zmalloc(sizeof(*zsl
));
4619 zsl
->header
= zslCreateNode(ZSKIPLIST_MAXLEVEL
,0,NULL
);
4620 for (j
= 0; j
< ZSKIPLIST_MAXLEVEL
; j
++)
4621 zsl
->header
->forward
[j
] = NULL
;
4622 zsl
->header
->backward
= NULL
;
4627 static void zslFreeNode(zskiplistNode
*node
) {
4628 decrRefCount(node
->obj
);
4629 zfree(node
->forward
);
4633 static void zslFree(zskiplist
*zsl
) {
4634 zskiplistNode
*node
= zsl
->header
->forward
[0], *next
;
4636 zfree(zsl
->header
->forward
);
4639 next
= node
->forward
[0];
4646 static int zslRandomLevel(void) {
4648 while ((random()&0xFFFF) < (ZSKIPLIST_P
* 0xFFFF))
4653 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
) {
4654 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4658 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4659 while (x
->forward
[i
] &&
4660 (x
->forward
[i
]->score
< score
||
4661 (x
->forward
[i
]->score
== score
&&
4662 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
4666 /* we assume the key is not already inside, since we allow duplicated
4667 * scores, and the re-insertion of score and redis object should never
4668 * happpen since the caller of zslInsert() should test in the hash table
4669 * if the element is already inside or not. */
4670 level
= zslRandomLevel();
4671 if (level
> zsl
->level
) {
4672 for (i
= zsl
->level
; i
< level
; i
++)
4673 update
[i
] = zsl
->header
;
4676 x
= zslCreateNode(level
,score
,obj
);
4677 for (i
= 0; i
< level
; i
++) {
4678 x
->forward
[i
] = update
[i
]->forward
[i
];
4679 update
[i
]->forward
[i
] = x
;
4681 x
->backward
= (update
[0] == zsl
->header
) ? NULL
: update
[0];
4683 x
->forward
[0]->backward
= x
;
4689 /* Delete an element with matching score/object from the skiplist. */
4690 static int zslDelete(zskiplist
*zsl
, double score
, robj
*obj
) {
4691 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4695 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4696 while (x
->forward
[i
] &&
4697 (x
->forward
[i
]->score
< score
||
4698 (x
->forward
[i
]->score
== score
&&
4699 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
4703 /* We may have multiple elements with the same score, what we need
4704 * is to find the element with both the right score and object. */
4706 if (x
&& score
== x
->score
&& compareStringObjects(x
->obj
,obj
) == 0) {
4707 for (i
= 0; i
< zsl
->level
; i
++) {
4708 if (update
[i
]->forward
[i
] != x
) break;
4709 update
[i
]->forward
[i
] = x
->forward
[i
];
4711 if (x
->forward
[0]) {
4712 x
->forward
[0]->backward
= (x
->backward
== zsl
->header
) ?
4715 zsl
->tail
= x
->backward
;
4718 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
4723 return 0; /* not found */
4725 return 0; /* not found */
4728 /* Delete all the elements with score between min and max from the skiplist.
4729 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
4730 * Note that this function takes the reference to the hash table view of the
4731 * sorted set, in order to remove the elements from the hash table too. */
4732 static unsigned long zslDeleteRange(zskiplist
*zsl
, double min
, double max
, dict
*dict
) {
4733 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4734 unsigned long removed
= 0;
4738 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4739 while (x
->forward
[i
] && x
->forward
[i
]->score
< min
)
4743 /* We may have multiple elements with the same score, what we need
4744 * is to find the element with both the right score and object. */
4746 while (x
&& x
->score
<= max
) {
4747 zskiplistNode
*next
;
4749 for (i
= 0; i
< zsl
->level
; i
++) {
4750 if (update
[i
]->forward
[i
] != x
) break;
4751 update
[i
]->forward
[i
] = x
->forward
[i
];
4753 if (x
->forward
[0]) {
4754 x
->forward
[0]->backward
= (x
->backward
== zsl
->header
) ?
4757 zsl
->tail
= x
->backward
;
4759 next
= x
->forward
[0];
4760 dictDelete(dict
,x
->obj
);
4762 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
4768 return removed
; /* not found */
4771 /* Find the first node having a score equal or greater than the specified one.
4772 * Returns NULL if there is no match. */
4773 static zskiplistNode
*zslFirstWithScore(zskiplist
*zsl
, double score
) {
4778 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4779 while (x
->forward
[i
] && x
->forward
[i
]->score
< score
)
4782 /* We may have multiple elements with the same score, what we need
4783 * is to find the element with both the right score and object. */
4784 return x
->forward
[0];
4787 /* The actual Z-commands implementations */
4789 /* This generic command implements both ZADD and ZINCRBY.
4790 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
4791 * the increment if the operation is a ZINCRBY (doincrement == 1). */
4792 static void zaddGenericCommand(redisClient
*c
, robj
*key
, robj
*ele
, double scoreval
, int doincrement
) {
4797 zsetobj
= lookupKeyWrite(c
->db
,key
);
4798 if (zsetobj
== NULL
) {
4799 zsetobj
= createZsetObject();
4800 dictAdd(c
->db
->dict
,key
,zsetobj
);
4803 if (zsetobj
->type
!= REDIS_ZSET
) {
4804 addReply(c
,shared
.wrongtypeerr
);
4810 /* Ok now since we implement both ZADD and ZINCRBY here the code
4811 * needs to handle the two different conditions. It's all about setting
4812 * '*score', that is, the new score to set, to the right value. */
4813 score
= zmalloc(sizeof(double));
4817 /* Read the old score. If the element was not present starts from 0 */
4818 de
= dictFind(zs
->dict
,ele
);
4820 double *oldscore
= dictGetEntryVal(de
);
4821 *score
= *oldscore
+ scoreval
;
4829 /* What follows is a simple remove and re-insert operation that is common
4830 * to both ZADD and ZINCRBY... */
4831 if (dictAdd(zs
->dict
,ele
,score
) == DICT_OK
) {
4832 /* case 1: New element */
4833 incrRefCount(ele
); /* added to hash */
4834 zslInsert(zs
->zsl
,*score
,ele
);
4835 incrRefCount(ele
); /* added to skiplist */
4838 addReplyDouble(c
,*score
);
4840 addReply(c
,shared
.cone
);
4845 /* case 2: Score update operation */
4846 de
= dictFind(zs
->dict
,ele
);
4847 redisAssert(de
!= NULL
);
4848 oldscore
= dictGetEntryVal(de
);
4849 if (*score
!= *oldscore
) {
4852 /* Remove and insert the element in the skip list with new score */
4853 deleted
= zslDelete(zs
->zsl
,*oldscore
,ele
);
4854 redisAssert(deleted
!= 0);
4855 zslInsert(zs
->zsl
,*score
,ele
);
4857 /* Update the score in the hash table */
4858 dictReplace(zs
->dict
,ele
,score
);
4864 addReplyDouble(c
,*score
);
4866 addReply(c
,shared
.czero
);
4870 static void zaddCommand(redisClient
*c
) {
4873 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
4874 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,0);
4877 static void zincrbyCommand(redisClient
*c
) {
4880 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
4881 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,1);
4884 static void zremCommand(redisClient
*c
) {
4888 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4889 if (zsetobj
== NULL
) {
4890 addReply(c
,shared
.czero
);
4896 if (zsetobj
->type
!= REDIS_ZSET
) {
4897 addReply(c
,shared
.wrongtypeerr
);
4901 de
= dictFind(zs
->dict
,c
->argv
[2]);
4903 addReply(c
,shared
.czero
);
4906 /* Delete from the skiplist */
4907 oldscore
= dictGetEntryVal(de
);
4908 deleted
= zslDelete(zs
->zsl
,*oldscore
,c
->argv
[2]);
4909 redisAssert(deleted
!= 0);
4911 /* Delete from the hash table */
4912 dictDelete(zs
->dict
,c
->argv
[2]);
4913 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
4915 addReply(c
,shared
.cone
);
4919 static void zremrangebyscoreCommand(redisClient
*c
) {
4920 double min
= strtod(c
->argv
[2]->ptr
,NULL
);
4921 double max
= strtod(c
->argv
[3]->ptr
,NULL
);
4925 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4926 if (zsetobj
== NULL
) {
4927 addReply(c
,shared
.czero
);
4931 if (zsetobj
->type
!= REDIS_ZSET
) {
4932 addReply(c
,shared
.wrongtypeerr
);
4936 deleted
= zslDeleteRange(zs
->zsl
,min
,max
,zs
->dict
);
4937 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
4938 server
.dirty
+= deleted
;
4939 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",deleted
));
4943 static void zrangeGenericCommand(redisClient
*c
, int reverse
) {
4945 int start
= atoi(c
->argv
[2]->ptr
);
4946 int end
= atoi(c
->argv
[3]->ptr
);
4949 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
4951 } else if (c
->argc
>= 5) {
4952 addReply(c
,shared
.syntaxerr
);
4956 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4958 addReply(c
,shared
.nullmultibulk
);
4960 if (o
->type
!= REDIS_ZSET
) {
4961 addReply(c
,shared
.wrongtypeerr
);
4963 zset
*zsetobj
= o
->ptr
;
4964 zskiplist
*zsl
= zsetobj
->zsl
;
4967 int llen
= zsl
->length
;
4971 /* convert negative indexes */
4972 if (start
< 0) start
= llen
+start
;
4973 if (end
< 0) end
= llen
+end
;
4974 if (start
< 0) start
= 0;
4975 if (end
< 0) end
= 0;
4977 /* indexes sanity checks */
4978 if (start
> end
|| start
>= llen
) {
4979 /* Out of range start or start > end result in empty list */
4980 addReply(c
,shared
.emptymultibulk
);
4983 if (end
>= llen
) end
= llen
-1;
4984 rangelen
= (end
-start
)+1;
4986 /* Return the result in form of a multi-bulk reply */
4992 ln
= zsl
->header
->forward
[0];
4994 ln
= ln
->forward
[0];
4997 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",
4998 withscores
? (rangelen
*2) : rangelen
));
4999 for (j
= 0; j
< rangelen
; j
++) {
5001 addReplyBulkLen(c
,ele
);
5003 addReply(c
,shared
.crlf
);
5005 addReplyDouble(c
,ln
->score
);
5006 ln
= reverse
? ln
->backward
: ln
->forward
[0];
5012 static void zrangeCommand(redisClient
*c
) {
5013 zrangeGenericCommand(c
,0);
5016 static void zrevrangeCommand(redisClient
*c
) {
5017 zrangeGenericCommand(c
,1);
5020 static void zrangebyscoreCommand(redisClient
*c
) {
5022 double min
= strtod(c
->argv
[2]->ptr
,NULL
);
5023 double max
= strtod(c
->argv
[3]->ptr
,NULL
);
5024 int offset
= 0, limit
= -1;
5026 if (c
->argc
!= 4 && c
->argc
!= 7) {
5028 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
5030 } else if (c
->argc
== 7 && strcasecmp(c
->argv
[4]->ptr
,"limit")) {
5031 addReply(c
,shared
.syntaxerr
);
5033 } else if (c
->argc
== 7) {
5034 offset
= atoi(c
->argv
[5]->ptr
);
5035 limit
= atoi(c
->argv
[6]->ptr
);
5036 if (offset
< 0) offset
= 0;
5039 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5041 addReply(c
,shared
.nullmultibulk
);
5043 if (o
->type
!= REDIS_ZSET
) {
5044 addReply(c
,shared
.wrongtypeerr
);
5046 zset
*zsetobj
= o
->ptr
;
5047 zskiplist
*zsl
= zsetobj
->zsl
;
5050 unsigned int rangelen
= 0;
5052 /* Get the first node with the score >= min */
5053 ln
= zslFirstWithScore(zsl
,min
);
5055 /* No element matching the speciifed interval */
5056 addReply(c
,shared
.emptymultibulk
);
5060 /* We don't know in advance how many matching elements there
5061 * are in the list, so we push this object that will represent
5062 * the multi-bulk length in the output buffer, and will "fix"
5064 lenobj
= createObject(REDIS_STRING
,NULL
);
5066 decrRefCount(lenobj
);
5068 while(ln
&& ln
->score
<= max
) {
5071 ln
= ln
->forward
[0];
5074 if (limit
== 0) break;
5076 addReplyBulkLen(c
,ele
);
5078 addReply(c
,shared
.crlf
);
5079 ln
= ln
->forward
[0];
5081 if (limit
> 0) limit
--;
5083 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%d\r\n",rangelen
);
5088 static void zcardCommand(redisClient
*c
) {
5092 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5094 addReply(c
,shared
.czero
);
5097 if (o
->type
!= REDIS_ZSET
) {
5098 addReply(c
,shared
.wrongtypeerr
);
5101 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",zs
->zsl
->length
));
5106 static void zscoreCommand(redisClient
*c
) {
5110 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5112 addReply(c
,shared
.nullbulk
);
5115 if (o
->type
!= REDIS_ZSET
) {
5116 addReply(c
,shared
.wrongtypeerr
);
5121 de
= dictFind(zs
->dict
,c
->argv
[2]);
5123 addReply(c
,shared
.nullbulk
);
5125 double *score
= dictGetEntryVal(de
);
5127 addReplyDouble(c
,*score
);
5133 /* ========================= Non type-specific commands ==================== */
5135 static void flushdbCommand(redisClient
*c
) {
5136 server
.dirty
+= dictSize(c
->db
->dict
);
5137 dictEmpty(c
->db
->dict
);
5138 dictEmpty(c
->db
->expires
);
5139 addReply(c
,shared
.ok
);
5142 static void flushallCommand(redisClient
*c
) {
5143 server
.dirty
+= emptyDb();
5144 addReply(c
,shared
.ok
);
5145 rdbSave(server
.dbfilename
);
5149 static redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
5150 redisSortOperation
*so
= zmalloc(sizeof(*so
));
5152 so
->pattern
= pattern
;
5156 /* Return the value associated to the key with a name obtained
5157 * substituting the first occurence of '*' in 'pattern' with 'subst' */
5158 static robj
*lookupKeyByPattern(redisDb
*db
, robj
*pattern
, robj
*subst
) {
5162 int prefixlen
, sublen
, postfixlen
;
5163 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
5167 char buf
[REDIS_SORTKEY_MAX
+1];
5170 /* If the pattern is "#" return the substitution object itself in order
5171 * to implement the "SORT ... GET #" feature. */
5172 spat
= pattern
->ptr
;
5173 if (spat
[0] == '#' && spat
[1] == '\0') {
5177 /* The substitution object may be specially encoded. If so we create
5178 * a decoded object on the fly. Otherwise getDecodedObject will just
5179 * increment the ref count, that we'll decrement later. */
5180 subst
= getDecodedObject(subst
);
5183 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
5184 p
= strchr(spat
,'*');
5186 decrRefCount(subst
);
5191 sublen
= sdslen(ssub
);
5192 postfixlen
= sdslen(spat
)-(prefixlen
+1);
5193 memcpy(keyname
.buf
,spat
,prefixlen
);
5194 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
5195 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
5196 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
5197 keyname
.len
= prefixlen
+sublen
+postfixlen
;
5199 initStaticStringObject(keyobj
,((char*)&keyname
)+(sizeof(long)*2))
5200 decrRefCount(subst
);
5202 /* printf("lookup '%s' => %p\n", keyname.buf,de); */
5203 return lookupKeyRead(db
,&keyobj
);
5206 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
5207 * the additional parameter is not standard but a BSD-specific we have to
5208 * pass sorting parameters via the global 'server' structure */
5209 static int sortCompare(const void *s1
, const void *s2
) {
5210 const redisSortObject
*so1
= s1
, *so2
= s2
;
5213 if (!server
.sort_alpha
) {
5214 /* Numeric sorting. Here it's trivial as we precomputed scores */
5215 if (so1
->u
.score
> so2
->u
.score
) {
5217 } else if (so1
->u
.score
< so2
->u
.score
) {
5223 /* Alphanumeric sorting */
5224 if (server
.sort_bypattern
) {
5225 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
5226 /* At least one compare object is NULL */
5227 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
5229 else if (so1
->u
.cmpobj
== NULL
)
5234 /* We have both the objects, use strcoll */
5235 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
5238 /* Compare elements directly */
5241 dec1
= getDecodedObject(so1
->obj
);
5242 dec2
= getDecodedObject(so2
->obj
);
5243 cmp
= strcoll(dec1
->ptr
,dec2
->ptr
);
5248 return server
.sort_desc
? -cmp
: cmp
;
5251 /* The SORT command is the most complex command in Redis. Warning: this code
5252 * is optimized for speed and a bit less for readability */
5253 static void sortCommand(redisClient
*c
) {
5256 int desc
= 0, alpha
= 0;
5257 int limit_start
= 0, limit_count
= -1, start
, end
;
5258 int j
, dontsort
= 0, vectorlen
;
5259 int getop
= 0; /* GET operation counter */
5260 robj
*sortval
, *sortby
= NULL
, *storekey
= NULL
;
5261 redisSortObject
*vector
; /* Resulting vector to sort */
5263 /* Lookup the key to sort. It must be of the right types */
5264 sortval
= lookupKeyRead(c
->db
,c
->argv
[1]);
5265 if (sortval
== NULL
) {
5266 addReply(c
,shared
.nullmultibulk
);
5269 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
&&
5270 sortval
->type
!= REDIS_ZSET
)
5272 addReply(c
,shared
.wrongtypeerr
);
5276 /* Create a list of operations to perform for every sorted element.
5277 * Operations can be GET/DEL/INCR/DECR */
5278 operations
= listCreate();
5279 listSetFreeMethod(operations
,zfree
);
5282 /* Now we need to protect sortval incrementing its count, in the future
5283 * SORT may have options able to overwrite/delete keys during the sorting
5284 * and the sorted key itself may get destroied */
5285 incrRefCount(sortval
);
5287 /* The SORT command has an SQL-alike syntax, parse it */
5288 while(j
< c
->argc
) {
5289 int leftargs
= c
->argc
-j
-1;
5290 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
5292 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
5294 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
5296 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
5297 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
5298 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
5300 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"store") && leftargs
>= 1) {
5301 storekey
= c
->argv
[j
+1];
5303 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
5304 sortby
= c
->argv
[j
+1];
5305 /* If the BY pattern does not contain '*', i.e. it is constant,
5306 * we don't need to sort nor to lookup the weight keys. */
5307 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
5309 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
5310 listAddNodeTail(operations
,createSortOperation(
5311 REDIS_SORT_GET
,c
->argv
[j
+1]));
5315 decrRefCount(sortval
);
5316 listRelease(operations
);
5317 addReply(c
,shared
.syntaxerr
);
5323 /* Load the sorting vector with all the objects to sort */
5324 switch(sortval
->type
) {
5325 case REDIS_LIST
: vectorlen
= listLength((list
*)sortval
->ptr
); break;
5326 case REDIS_SET
: vectorlen
= dictSize((dict
*)sortval
->ptr
); break;
5327 case REDIS_ZSET
: vectorlen
= dictSize(((zset
*)sortval
->ptr
)->dict
); break;
5328 default: vectorlen
= 0; redisAssert(0); /* Avoid GCC warning */
5330 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
5333 if (sortval
->type
== REDIS_LIST
) {
5334 list
*list
= sortval
->ptr
;
5338 while((ln
= listYield(list
))) {
5339 robj
*ele
= ln
->value
;
5340 vector
[j
].obj
= ele
;
5341 vector
[j
].u
.score
= 0;
5342 vector
[j
].u
.cmpobj
= NULL
;
5350 if (sortval
->type
== REDIS_SET
) {
5353 zset
*zs
= sortval
->ptr
;
5357 di
= dictGetIterator(set
);
5358 while((setele
= dictNext(di
)) != NULL
) {
5359 vector
[j
].obj
= dictGetEntryKey(setele
);
5360 vector
[j
].u
.score
= 0;
5361 vector
[j
].u
.cmpobj
= NULL
;
5364 dictReleaseIterator(di
);
5366 redisAssert(j
== vectorlen
);
5368 /* Now it's time to load the right scores in the sorting vector */
5369 if (dontsort
== 0) {
5370 for (j
= 0; j
< vectorlen
; j
++) {
5374 byval
= lookupKeyByPattern(c
->db
,sortby
,vector
[j
].obj
);
5375 if (!byval
|| byval
->type
!= REDIS_STRING
) continue;
5377 vector
[j
].u
.cmpobj
= getDecodedObject(byval
);
5379 if (byval
->encoding
== REDIS_ENCODING_RAW
) {
5380 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
5382 /* Don't need to decode the object if it's
5383 * integer-encoded (the only encoding supported) so
5384 * far. We can just cast it */
5385 if (byval
->encoding
== REDIS_ENCODING_INT
) {
5386 vector
[j
].u
.score
= (long)byval
->ptr
;
5388 redisAssert(1 != 1);
5393 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_RAW
)
5394 vector
[j
].u
.score
= strtod(vector
[j
].obj
->ptr
,NULL
);
5396 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_INT
)
5397 vector
[j
].u
.score
= (long) vector
[j
].obj
->ptr
;
5399 redisAssert(1 != 1);
5406 /* We are ready to sort the vector... perform a bit of sanity check
5407 * on the LIMIT option too. We'll use a partial version of quicksort. */
5408 start
= (limit_start
< 0) ? 0 : limit_start
;
5409 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
5410 if (start
>= vectorlen
) {
5411 start
= vectorlen
-1;
5414 if (end
>= vectorlen
) end
= vectorlen
-1;
5416 if (dontsort
== 0) {
5417 server
.sort_desc
= desc
;
5418 server
.sort_alpha
= alpha
;
5419 server
.sort_bypattern
= sortby
? 1 : 0;
5420 if (sortby
&& (start
!= 0 || end
!= vectorlen
-1))
5421 pqsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
, start
,end
);
5423 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
5426 /* Send command output to the output buffer, performing the specified
5427 * GET/DEL/INCR/DECR operations if any. */
5428 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
5429 if (storekey
== NULL
) {
5430 /* STORE option not specified, sent the sorting result to client */
5431 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
5432 for (j
= start
; j
<= end
; j
++) {
5435 addReplyBulkLen(c
,vector
[j
].obj
);
5436 addReply(c
,vector
[j
].obj
);
5437 addReply(c
,shared
.crlf
);
5439 listRewind(operations
);
5440 while((ln
= listYield(operations
))) {
5441 redisSortOperation
*sop
= ln
->value
;
5442 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
5445 if (sop
->type
== REDIS_SORT_GET
) {
5446 if (!val
|| val
->type
!= REDIS_STRING
) {
5447 addReply(c
,shared
.nullbulk
);
5449 addReplyBulkLen(c
,val
);
5451 addReply(c
,shared
.crlf
);
5454 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
5459 robj
*listObject
= createListObject();
5460 list
*listPtr
= (list
*) listObject
->ptr
;
5462 /* STORE option specified, set the sorting result as a List object */
5463 for (j
= start
; j
<= end
; j
++) {
5466 listAddNodeTail(listPtr
,vector
[j
].obj
);
5467 incrRefCount(vector
[j
].obj
);
5469 listRewind(operations
);
5470 while((ln
= listYield(operations
))) {
5471 redisSortOperation
*sop
= ln
->value
;
5472 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
5475 if (sop
->type
== REDIS_SORT_GET
) {
5476 if (!val
|| val
->type
!= REDIS_STRING
) {
5477 listAddNodeTail(listPtr
,createStringObject("",0));
5479 listAddNodeTail(listPtr
,val
);
5483 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
5487 if (dictReplace(c
->db
->dict
,storekey
,listObject
)) {
5488 incrRefCount(storekey
);
5490 /* Note: we add 1 because the DB is dirty anyway since even if the
5491 * SORT result is empty a new key is set and maybe the old content
5493 server
.dirty
+= 1+outputlen
;
5494 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",outputlen
));
5498 decrRefCount(sortval
);
5499 listRelease(operations
);
5500 for (j
= 0; j
< vectorlen
; j
++) {
5501 if (sortby
&& alpha
&& vector
[j
].u
.cmpobj
)
5502 decrRefCount(vector
[j
].u
.cmpobj
);
5507 /* Convert an amount of bytes into a human readable string in the form
5508 * of 100B, 2G, 100M, 4K, and so forth. */
5509 static void bytesToHuman(char *s
, unsigned long long n
) {
5514 sprintf(s
,"%lluB",n
);
5516 } else if (n
< (1024*1024)) {
5517 d
= (double)n
/(1024);
5518 sprintf(s
,"%.2fK",d
);
5519 } else if (n
< (1024LL*1024*1024)) {
5520 d
= (double)n
/(1024*1024);
5521 sprintf(s
,"%.2fM",d
);
5522 } else if (n
< (1024LL*1024*1024*1024)) {
5523 d
= (double)n
/(1024LL*1024*1024);
5524 sprintf(s
,"%.2fM",d
);
5528 /* Create the string returned by the INFO command. This is decoupled
5529 * by the INFO command itself as we need to report the same information
5530 * on memory corruption problems. */
5531 static sds
genRedisInfoString(void) {
5533 time_t uptime
= time(NULL
)-server
.stat_starttime
;
5537 bytesToHuman(hmem
,server
.usedmemory
);
5538 info
= sdscatprintf(sdsempty(),
5539 "redis_version:%s\r\n"
5541 "multiplexing_api:%s\r\n"
5542 "process_id:%ld\r\n"
5543 "uptime_in_seconds:%ld\r\n"
5544 "uptime_in_days:%ld\r\n"
5545 "connected_clients:%d\r\n"
5546 "connected_slaves:%d\r\n"
5547 "blocked_clients:%d\r\n"
5548 "used_memory:%zu\r\n"
5549 "used_memory_human:%s\r\n"
5550 "changes_since_last_save:%lld\r\n"
5551 "bgsave_in_progress:%d\r\n"
5552 "last_save_time:%ld\r\n"
5553 "bgrewriteaof_in_progress:%d\r\n"
5554 "total_connections_received:%lld\r\n"
5555 "total_commands_processed:%lld\r\n"
5559 (sizeof(long) == 8) ? "64" : "32",
5564 listLength(server
.clients
)-listLength(server
.slaves
),
5565 listLength(server
.slaves
),
5566 server
.blockedclients
,
5570 server
.bgsavechildpid
!= -1,
5572 server
.bgrewritechildpid
!= -1,
5573 server
.stat_numconnections
,
5574 server
.stat_numcommands
,
5575 server
.vm_enabled
!= 0,
5576 server
.masterhost
== NULL
? "master" : "slave"
5578 if (server
.masterhost
) {
5579 info
= sdscatprintf(info
,
5580 "master_host:%s\r\n"
5581 "master_port:%d\r\n"
5582 "master_link_status:%s\r\n"
5583 "master_last_io_seconds_ago:%d\r\n"
5586 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
5588 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1
5591 if (server
.vm_enabled
) {
5592 info
= sdscatprintf(info
,
5593 "vm_conf_max_memory:%llu\r\n"
5594 "vm_conf_page_size:%llu\r\n"
5595 "vm_conf_pages:%llu\r\n"
5596 "vm_stats_used_pages:%llu\r\n"
5597 "vm_stats_swapped_objects:%llu\r\n"
5598 "vm_stats_swappin_count:%llu\r\n"
5599 "vm_stats_swappout_count:%llu\r\n"
5600 ,(unsigned long long) server
.vm_max_memory
,
5601 (unsigned long long) server
.vm_page_size
,
5602 (unsigned long long) server
.vm_pages
,
5603 (unsigned long long) server
.vm_stats_used_pages
,
5604 (unsigned long long) server
.vm_stats_swapped_objects
,
5605 (unsigned long long) server
.vm_stats_swapins
,
5606 (unsigned long long) server
.vm_stats_swapouts
5609 for (j
= 0; j
< server
.dbnum
; j
++) {
5610 long long keys
, vkeys
;
5612 keys
= dictSize(server
.db
[j
].dict
);
5613 vkeys
= dictSize(server
.db
[j
].expires
);
5614 if (keys
|| vkeys
) {
5615 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
5622 static void infoCommand(redisClient
*c
) {
5623 sds info
= genRedisInfoString();
5624 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
5625 (unsigned long)sdslen(info
)));
5626 addReplySds(c
,info
);
5627 addReply(c
,shared
.crlf
);
5630 static void monitorCommand(redisClient
*c
) {
5631 /* ignore MONITOR if aleady slave or in monitor mode */
5632 if (c
->flags
& REDIS_SLAVE
) return;
5634 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
5636 listAddNodeTail(server
.monitors
,c
);
5637 addReply(c
,shared
.ok
);
5640 /* ================================= Expire ================================= */
5641 static int removeExpire(redisDb
*db
, robj
*key
) {
5642 if (dictDelete(db
->expires
,key
) == DICT_OK
) {
5649 static int setExpire(redisDb
*db
, robj
*key
, time_t when
) {
5650 if (dictAdd(db
->expires
,key
,(void*)when
) == DICT_ERR
) {
5658 /* Return the expire time of the specified key, or -1 if no expire
5659 * is associated with this key (i.e. the key is non volatile) */
5660 static time_t getExpire(redisDb
*db
, robj
*key
) {
5663 /* No expire? return ASAP */
5664 if (dictSize(db
->expires
) == 0 ||
5665 (de
= dictFind(db
->expires
,key
)) == NULL
) return -1;
5667 return (time_t) dictGetEntryVal(de
);
5670 static int expireIfNeeded(redisDb
*db
, robj
*key
) {
5674 /* No expire? return ASAP */
5675 if (dictSize(db
->expires
) == 0 ||
5676 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
5678 /* Lookup the expire */
5679 when
= (time_t) dictGetEntryVal(de
);
5680 if (time(NULL
) <= when
) return 0;
5682 /* Delete the key */
5683 dictDelete(db
->expires
,key
);
5684 return dictDelete(db
->dict
,key
) == DICT_OK
;
5687 static int deleteIfVolatile(redisDb
*db
, robj
*key
) {
5690 /* No expire? return ASAP */
5691 if (dictSize(db
->expires
) == 0 ||
5692 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
5694 /* Delete the key */
5696 dictDelete(db
->expires
,key
);
5697 return dictDelete(db
->dict
,key
) == DICT_OK
;
5700 static void expireGenericCommand(redisClient
*c
, robj
*key
, time_t seconds
) {
5703 de
= dictFind(c
->db
->dict
,key
);
5705 addReply(c
,shared
.czero
);
5709 if (deleteKey(c
->db
,key
)) server
.dirty
++;
5710 addReply(c
, shared
.cone
);
5713 time_t when
= time(NULL
)+seconds
;
5714 if (setExpire(c
->db
,key
,when
)) {
5715 addReply(c
,shared
.cone
);
5718 addReply(c
,shared
.czero
);
5724 static void expireCommand(redisClient
*c
) {
5725 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10));
5728 static void expireatCommand(redisClient
*c
) {
5729 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10)-time(NULL
));
5732 static void ttlCommand(redisClient
*c
) {
5736 expire
= getExpire(c
->db
,c
->argv
[1]);
5738 ttl
= (int) (expire
-time(NULL
));
5739 if (ttl
< 0) ttl
= -1;
5741 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",ttl
));
5744 /* ================================ MULTI/EXEC ============================== */
5746 /* Client state initialization for MULTI/EXEC */
5747 static void initClientMultiState(redisClient
*c
) {
5748 c
->mstate
.commands
= NULL
;
5749 c
->mstate
.count
= 0;
5752 /* Release all the resources associated with MULTI/EXEC state */
5753 static void freeClientMultiState(redisClient
*c
) {
5756 for (j
= 0; j
< c
->mstate
.count
; j
++) {
5758 multiCmd
*mc
= c
->mstate
.commands
+j
;
5760 for (i
= 0; i
< mc
->argc
; i
++)
5761 decrRefCount(mc
->argv
[i
]);
5764 zfree(c
->mstate
.commands
);
5767 /* Add a new command into the MULTI commands queue */
5768 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
) {
5772 c
->mstate
.commands
= zrealloc(c
->mstate
.commands
,
5773 sizeof(multiCmd
)*(c
->mstate
.count
+1));
5774 mc
= c
->mstate
.commands
+c
->mstate
.count
;
5777 mc
->argv
= zmalloc(sizeof(robj
*)*c
->argc
);
5778 memcpy(mc
->argv
,c
->argv
,sizeof(robj
*)*c
->argc
);
5779 for (j
= 0; j
< c
->argc
; j
++)
5780 incrRefCount(mc
->argv
[j
]);
5784 static void multiCommand(redisClient
*c
) {
5785 c
->flags
|= REDIS_MULTI
;
5786 addReply(c
,shared
.ok
);
5789 static void execCommand(redisClient
*c
) {
5794 if (!(c
->flags
& REDIS_MULTI
)) {
5795 addReplySds(c
,sdsnew("-ERR EXEC without MULTI\r\n"));
5799 orig_argv
= c
->argv
;
5800 orig_argc
= c
->argc
;
5801 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->mstate
.count
));
5802 for (j
= 0; j
< c
->mstate
.count
; j
++) {
5803 c
->argc
= c
->mstate
.commands
[j
].argc
;
5804 c
->argv
= c
->mstate
.commands
[j
].argv
;
5805 call(c
,c
->mstate
.commands
[j
].cmd
);
5807 c
->argv
= orig_argv
;
5808 c
->argc
= orig_argc
;
5809 freeClientMultiState(c
);
5810 initClientMultiState(c
);
5811 c
->flags
&= (~REDIS_MULTI
);
5814 /* =========================== Blocking Operations ========================= */
5816 /* Currently Redis blocking operations support is limited to list POP ops,
5817 * so the current implementation is not fully generic, but it is also not
5818 * completely specific so it will not require a rewrite to support new
5819 * kind of blocking operations in the future.
5821 * Still it's important to note that list blocking operations can be already
5822 * used as a notification mechanism in order to implement other blocking
5823 * operations at application level, so there must be a very strong evidence
5824 * of usefulness and generality before new blocking operations are implemented.
5826 * This is how the current blocking POP works, we use BLPOP as example:
5827 * - If the user calls BLPOP and the key exists and contains a non empty list
5828 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
5829 * if there is not to block.
5830 * - If instead BLPOP is called and the key does not exists or the list is
5831 * empty we need to block. In order to do so we remove the notification for
5832 * new data to read in the client socket (so that we'll not serve new
5833 * requests if the blocking request is not served). Also we put the client
5834 * in a dictionary (db->blockingkeys) mapping keys to a list of clients
5835 * blocking for this keys.
5836 * - If a PUSH operation against a key with blocked clients waiting is
5837 * performed, we serve the first in the list: basically instead to push
5838 * the new element inside the list we return it to the (first / oldest)
5839 * blocking client, unblock the client, and remove it form the list.
5841 * The above comment and the source code should be enough in order to understand
5842 * the implementation and modify / fix it later.
5845 /* Set a client in blocking mode for the specified key, with the specified
5847 static void blockForKeys(redisClient
*c
, robj
**keys
, int numkeys
, time_t timeout
) {
5852 c
->blockingkeys
= zmalloc(sizeof(robj
*)*numkeys
);
5853 c
->blockingkeysnum
= numkeys
;
5854 c
->blockingto
= timeout
;
5855 for (j
= 0; j
< numkeys
; j
++) {
5856 /* Add the key in the client structure, to map clients -> keys */
5857 c
->blockingkeys
[j
] = keys
[j
];
5858 incrRefCount(keys
[j
]);
5860 /* And in the other "side", to map keys -> clients */
5861 de
= dictFind(c
->db
->blockingkeys
,keys
[j
]);
5865 /* For every key we take a list of clients blocked for it */
5867 retval
= dictAdd(c
->db
->blockingkeys
,keys
[j
],l
);
5868 incrRefCount(keys
[j
]);
5869 assert(retval
== DICT_OK
);
5871 l
= dictGetEntryVal(de
);
5873 listAddNodeTail(l
,c
);
5875 /* Mark the client as a blocked client */
5876 c
->flags
|= REDIS_BLOCKED
;
5877 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
5878 server
.blockedclients
++;
5881 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
5882 static void unblockClient(redisClient
*c
) {
5887 assert(c
->blockingkeys
!= NULL
);
5888 /* The client may wait for multiple keys, so unblock it for every key. */
5889 for (j
= 0; j
< c
->blockingkeysnum
; j
++) {
5890 /* Remove this client from the list of clients waiting for this key. */
5891 de
= dictFind(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
5893 l
= dictGetEntryVal(de
);
5894 listDelNode(l
,listSearchKey(l
,c
));
5895 /* If the list is empty we need to remove it to avoid wasting memory */
5896 if (listLength(l
) == 0)
5897 dictDelete(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
5898 decrRefCount(c
->blockingkeys
[j
]);
5900 /* Cleanup the client structure */
5901 zfree(c
->blockingkeys
);
5902 c
->blockingkeys
= NULL
;
5903 c
->flags
&= (~REDIS_BLOCKED
);
5904 server
.blockedclients
--;
5905 /* Ok now we are ready to get read events from socket, note that we
5906 * can't trap errors here as it's possible that unblockClients() is
5907 * called from freeClient() itself, and the only thing we can do
5908 * if we failed to register the READABLE event is to kill the client.
5909 * Still the following function should never fail in the real world as
5910 * we are sure the file descriptor is sane, and we exit on out of mem. */
5911 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
, readQueryFromClient
, c
);
5912 /* As a final step we want to process data if there is some command waiting
5913 * in the input buffer. Note that this is safe even if unblockClient()
5914 * gets called from freeClient() because freeClient() will be smart
5915 * enough to call this function *after* c->querybuf was set to NULL. */
5916 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0) processInputBuffer(c
);
5919 /* This should be called from any function PUSHing into lists.
5920 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
5921 * 'ele' is the element pushed.
5923 * If the function returns 0 there was no client waiting for a list push
5926 * If the function returns 1 there was a client waiting for a list push
5927 * against this key, the element was passed to this client thus it's not
5928 * needed to actually add it to the list and the caller should return asap. */
5929 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
) {
5930 struct dictEntry
*de
;
5931 redisClient
*receiver
;
5935 de
= dictFind(c
->db
->blockingkeys
,key
);
5936 if (de
== NULL
) return 0;
5937 l
= dictGetEntryVal(de
);
5940 receiver
= ln
->value
;
5942 addReplySds(receiver
,sdsnew("*2\r\n"));
5943 addReplyBulkLen(receiver
,key
);
5944 addReply(receiver
,key
);
5945 addReply(receiver
,shared
.crlf
);
5946 addReplyBulkLen(receiver
,ele
);
5947 addReply(receiver
,ele
);
5948 addReply(receiver
,shared
.crlf
);
5949 unblockClient(receiver
);
5953 /* Blocking RPOP/LPOP */
5954 static void blockingPopGenericCommand(redisClient
*c
, int where
) {
5959 for (j
= 1; j
< c
->argc
-1; j
++) {
5960 o
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
5962 if (o
->type
!= REDIS_LIST
) {
5963 addReply(c
,shared
.wrongtypeerr
);
5966 list
*list
= o
->ptr
;
5967 if (listLength(list
) != 0) {
5968 /* If the list contains elements fall back to the usual
5969 * non-blocking POP operation */
5970 robj
*argv
[2], **orig_argv
;
5973 /* We need to alter the command arguments before to call
5974 * popGenericCommand() as the command takes a single key. */
5975 orig_argv
= c
->argv
;
5976 orig_argc
= c
->argc
;
5977 argv
[1] = c
->argv
[j
];
5981 /* Also the return value is different, we need to output
5982 * the multi bulk reply header and the key name. The
5983 * "real" command will add the last element (the value)
5984 * for us. If this souds like an hack to you it's just
5985 * because it is... */
5986 addReplySds(c
,sdsnew("*2\r\n"));
5987 addReplyBulkLen(c
,argv
[1]);
5988 addReply(c
,argv
[1]);
5989 addReply(c
,shared
.crlf
);
5990 popGenericCommand(c
,where
);
5992 /* Fix the client structure with the original stuff */
5993 c
->argv
= orig_argv
;
5994 c
->argc
= orig_argc
;
6000 /* If the list is empty or the key does not exists we must block */
6001 timeout
= strtol(c
->argv
[c
->argc
-1]->ptr
,NULL
,10);
6002 if (timeout
> 0) timeout
+= time(NULL
);
6003 blockForKeys(c
,c
->argv
+1,c
->argc
-2,timeout
);
6006 static void blpopCommand(redisClient
*c
) {
6007 blockingPopGenericCommand(c
,REDIS_HEAD
);
6010 static void brpopCommand(redisClient
*c
) {
6011 blockingPopGenericCommand(c
,REDIS_TAIL
);
6014 /* =============================== Replication ============================= */
6016 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6017 ssize_t nwritten
, ret
= size
;
6018 time_t start
= time(NULL
);
6022 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
6023 nwritten
= write(fd
,ptr
,size
);
6024 if (nwritten
== -1) return -1;
6028 if ((time(NULL
)-start
) > timeout
) {
6036 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6037 ssize_t nread
, totread
= 0;
6038 time_t start
= time(NULL
);
6042 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
6043 nread
= read(fd
,ptr
,size
);
6044 if (nread
== -1) return -1;
6049 if ((time(NULL
)-start
) > timeout
) {
6057 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6064 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
6067 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
6078 static void syncCommand(redisClient
*c
) {
6079 /* ignore SYNC if aleady slave or in monitor mode */
6080 if (c
->flags
& REDIS_SLAVE
) return;
6082 /* SYNC can't be issued when the server has pending data to send to
6083 * the client about already issued commands. We need a fresh reply
6084 * buffer registering the differences between the BGSAVE and the current
6085 * dataset, so that we can copy to other slaves if needed. */
6086 if (listLength(c
->reply
) != 0) {
6087 addReplySds(c
,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
6091 redisLog(REDIS_NOTICE
,"Slave ask for synchronization");
6092 /* Here we need to check if there is a background saving operation
6093 * in progress, or if it is required to start one */
6094 if (server
.bgsavechildpid
!= -1) {
6095 /* Ok a background save is in progress. Let's check if it is a good
6096 * one for replication, i.e. if there is another slave that is
6097 * registering differences since the server forked to save */
6101 listRewind(server
.slaves
);
6102 while((ln
= listYield(server
.slaves
))) {
6104 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) break;
6107 /* Perfect, the server is already registering differences for
6108 * another slave. Set the right state, and copy the buffer. */
6109 listRelease(c
->reply
);
6110 c
->reply
= listDup(slave
->reply
);
6111 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6112 redisLog(REDIS_NOTICE
,"Waiting for end of BGSAVE for SYNC");
6114 /* No way, we need to wait for the next BGSAVE in order to
6115 * register differences */
6116 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
6117 redisLog(REDIS_NOTICE
,"Waiting for next BGSAVE for SYNC");
6120 /* Ok we don't have a BGSAVE in progress, let's start one */
6121 redisLog(REDIS_NOTICE
,"Starting BGSAVE for SYNC");
6122 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
6123 redisLog(REDIS_NOTICE
,"Replication failed, can't BGSAVE");
6124 addReplySds(c
,sdsnew("-ERR Unalbe to perform background save\r\n"));
6127 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6130 c
->flags
|= REDIS_SLAVE
;
6132 listAddNodeTail(server
.slaves
,c
);
6136 static void sendBulkToSlave(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
6137 redisClient
*slave
= privdata
;
6139 REDIS_NOTUSED(mask
);
6140 char buf
[REDIS_IOBUF_LEN
];
6141 ssize_t nwritten
, buflen
;
6143 if (slave
->repldboff
== 0) {
6144 /* Write the bulk write count before to transfer the DB. In theory here
6145 * we don't know how much room there is in the output buffer of the
6146 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
6147 * operations) will never be smaller than the few bytes we need. */
6150 bulkcount
= sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
6152 if (write(fd
,bulkcount
,sdslen(bulkcount
)) != (signed)sdslen(bulkcount
))
6160 lseek(slave
->repldbfd
,slave
->repldboff
,SEEK_SET
);
6161 buflen
= read(slave
->repldbfd
,buf
,REDIS_IOBUF_LEN
);
6163 redisLog(REDIS_WARNING
,"Read error sending DB to slave: %s",
6164 (buflen
== 0) ? "premature EOF" : strerror(errno
));
6168 if ((nwritten
= write(fd
,buf
,buflen
)) == -1) {
6169 redisLog(REDIS_VERBOSE
,"Write error sending DB to slave: %s",
6174 slave
->repldboff
+= nwritten
;
6175 if (slave
->repldboff
== slave
->repldbsize
) {
6176 close(slave
->repldbfd
);
6177 slave
->repldbfd
= -1;
6178 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
6179 slave
->replstate
= REDIS_REPL_ONLINE
;
6180 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
,
6181 sendReplyToClient
, slave
) == AE_ERR
) {
6185 addReplySds(slave
,sdsempty());
6186 redisLog(REDIS_NOTICE
,"Synchronization with slave succeeded");
6190 /* This function is called at the end of every backgrond saving.
6191 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
6192 * otherwise REDIS_ERR is passed to the function.
6194 * The goal of this function is to handle slaves waiting for a successful
6195 * background saving in order to perform non-blocking synchronization. */
6196 static void updateSlavesWaitingBgsave(int bgsaveerr
) {
6198 int startbgsave
= 0;
6200 listRewind(server
.slaves
);
6201 while((ln
= listYield(server
.slaves
))) {
6202 redisClient
*slave
= ln
->value
;
6204 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) {
6206 slave
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6207 } else if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) {
6208 struct redis_stat buf
;
6210 if (bgsaveerr
!= REDIS_OK
) {
6212 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE child returned an error");
6215 if ((slave
->repldbfd
= open(server
.dbfilename
,O_RDONLY
)) == -1 ||
6216 redis_fstat(slave
->repldbfd
,&buf
) == -1) {
6218 redisLog(REDIS_WARNING
,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno
));
6221 slave
->repldboff
= 0;
6222 slave
->repldbsize
= buf
.st_size
;
6223 slave
->replstate
= REDIS_REPL_SEND_BULK
;
6224 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
6225 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
, sendBulkToSlave
, slave
) == AE_ERR
) {
6232 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
6233 listRewind(server
.slaves
);
6234 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE failed");
6235 while((ln
= listYield(server
.slaves
))) {
6236 redisClient
*slave
= ln
->value
;
6238 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
)
6245 static int syncWithMaster(void) {
6246 char buf
[1024], tmpfile
[256], authcmd
[1024];
6248 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
6252 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
6257 /* AUTH with the master if required. */
6258 if(server
.masterauth
) {
6259 snprintf(authcmd
, 1024, "AUTH %s\r\n", server
.masterauth
);
6260 if (syncWrite(fd
, authcmd
, strlen(server
.masterauth
)+7, 5) == -1) {
6262 redisLog(REDIS_WARNING
,"Unable to AUTH to MASTER: %s",
6266 /* Read the AUTH result. */
6267 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
6269 redisLog(REDIS_WARNING
,"I/O error reading auth result from MASTER: %s",
6273 if (buf
[0] != '+') {
6275 redisLog(REDIS_WARNING
,"Cannot AUTH to MASTER, is the masterauth password correct?");
6280 /* Issue the SYNC command */
6281 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
6283 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
6287 /* Read the bulk write count */
6288 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
6290 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
6294 if (buf
[0] != '$') {
6296 redisLog(REDIS_WARNING
,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
6299 dumpsize
= atoi(buf
+1);
6300 redisLog(REDIS_NOTICE
,"Receiving %d bytes data dump from MASTER",dumpsize
);
6301 /* Read the bulk write data on a temp file */
6302 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
6303 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
,0644);
6306 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
6310 int nread
, nwritten
;
6312 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
6314 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
6320 nwritten
= write(dfd
,buf
,nread
);
6321 if (nwritten
== -1) {
6322 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
6330 if (rename(tmpfile
,server
.dbfilename
) == -1) {
6331 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
6337 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
6338 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
6342 server
.master
= createClient(fd
);
6343 server
.master
->flags
|= REDIS_MASTER
;
6344 server
.master
->authenticated
= 1;
6345 server
.replstate
= REDIS_REPL_CONNECTED
;
6349 static void slaveofCommand(redisClient
*c
) {
6350 if (!strcasecmp(c
->argv
[1]->ptr
,"no") &&
6351 !strcasecmp(c
->argv
[2]->ptr
,"one")) {
6352 if (server
.masterhost
) {
6353 sdsfree(server
.masterhost
);
6354 server
.masterhost
= NULL
;
6355 if (server
.master
) freeClient(server
.master
);
6356 server
.replstate
= REDIS_REPL_NONE
;
6357 redisLog(REDIS_NOTICE
,"MASTER MODE enabled (user request)");
6360 sdsfree(server
.masterhost
);
6361 server
.masterhost
= sdsdup(c
->argv
[1]->ptr
);
6362 server
.masterport
= atoi(c
->argv
[2]->ptr
);
6363 if (server
.master
) freeClient(server
.master
);
6364 server
.replstate
= REDIS_REPL_CONNECT
;
6365 redisLog(REDIS_NOTICE
,"SLAVE OF %s:%d enabled (user request)",
6366 server
.masterhost
, server
.masterport
);
6368 addReply(c
,shared
.ok
);
6371 /* ============================ Maxmemory directive ======================== */
6373 /* Free one object form the pre-allocated objects free list. This is useful
6374 * under low mem conditions as by default we take 1 million free objects
6376 static void freeOneObjectFromFreelist(void) {
6379 listNode
*head
= listFirst(server
.objfreelist
);
6380 o
= listNodeValue(head
);
6381 listDelNode(server
.objfreelist
,head
);
6385 /* This function gets called when 'maxmemory' is set on the config file to limit
6386 * the max memory used by the server, and we are out of memory.
6387 * This function will try to, in order:
6389 * - Free objects from the free list
6390 * - Try to remove keys with an EXPIRE set
6392 * It is not possible to free enough memory to reach used-memory < maxmemory
6393 * the server will start refusing commands that will enlarge even more the
6396 static void freeMemoryIfNeeded(void) {
6397 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
6398 if (listLength(server
.objfreelist
)) {
6399 freeOneObjectFromFreelist();
6401 int j
, k
, freed
= 0;
6403 for (j
= 0; j
< server
.dbnum
; j
++) {
6405 robj
*minkey
= NULL
;
6406 struct dictEntry
*de
;
6408 if (dictSize(server
.db
[j
].expires
)) {
6410 /* From a sample of three keys drop the one nearest to
6411 * the natural expire */
6412 for (k
= 0; k
< 3; k
++) {
6415 de
= dictGetRandomKey(server
.db
[j
].expires
);
6416 t
= (time_t) dictGetEntryVal(de
);
6417 if (minttl
== -1 || t
< minttl
) {
6418 minkey
= dictGetEntryKey(de
);
6422 deleteKey(server
.db
+j
,minkey
);
6425 if (!freed
) return; /* nothing to free... */
6430 /* ============================== Append Only file ========================== */
6432 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
6433 sds buf
= sdsempty();
6439 /* The DB this command was targetting is not the same as the last command
6440 * we appendend. To issue a SELECT command is needed. */
6441 if (dictid
!= server
.appendseldb
) {
6444 snprintf(seldb
,sizeof(seldb
),"%d",dictid
);
6445 buf
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
6446 (unsigned long)strlen(seldb
),seldb
);
6447 server
.appendseldb
= dictid
;
6450 /* "Fix" the argv vector if the command is EXPIRE. We want to translate
6451 * EXPIREs into EXPIREATs calls */
6452 if (cmd
->proc
== expireCommand
) {
6455 tmpargv
[0] = createStringObject("EXPIREAT",8);
6456 tmpargv
[1] = argv
[1];
6457 incrRefCount(argv
[1]);
6458 when
= time(NULL
)+strtol(argv
[2]->ptr
,NULL
,10);
6459 tmpargv
[2] = createObject(REDIS_STRING
,
6460 sdscatprintf(sdsempty(),"%ld",when
));
6464 /* Append the actual command */
6465 buf
= sdscatprintf(buf
,"*%d\r\n",argc
);
6466 for (j
= 0; j
< argc
; j
++) {
6469 o
= getDecodedObject(o
);
6470 buf
= sdscatprintf(buf
,"$%lu\r\n",(unsigned long)sdslen(o
->ptr
));
6471 buf
= sdscatlen(buf
,o
->ptr
,sdslen(o
->ptr
));
6472 buf
= sdscatlen(buf
,"\r\n",2);
6476 /* Free the objects from the modified argv for EXPIREAT */
6477 if (cmd
->proc
== expireCommand
) {
6478 for (j
= 0; j
< 3; j
++)
6479 decrRefCount(argv
[j
]);
6482 /* We want to perform a single write. This should be guaranteed atomic
6483 * at least if the filesystem we are writing is a real physical one.
6484 * While this will save us against the server being killed I don't think
6485 * there is much to do about the whole server stopping for power problems
6487 nwritten
= write(server
.appendfd
,buf
,sdslen(buf
));
6488 if (nwritten
!= (signed)sdslen(buf
)) {
6489 /* Ooops, we are in troubles. The best thing to do for now is
6490 * to simply exit instead to give the illusion that everything is
6491 * working as expected. */
6492 if (nwritten
== -1) {
6493 redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
));
6495 redisLog(REDIS_WARNING
,"Exiting on short write while writing to the append-only file: %s",strerror(errno
));
6499 /* If a background append only file rewriting is in progress we want to
6500 * accumulate the differences between the child DB and the current one
6501 * in a buffer, so that when the child process will do its work we
6502 * can append the differences to the new append only file. */
6503 if (server
.bgrewritechildpid
!= -1)
6504 server
.bgrewritebuf
= sdscatlen(server
.bgrewritebuf
,buf
,sdslen(buf
));
6508 if (server
.appendfsync
== APPENDFSYNC_ALWAYS
||
6509 (server
.appendfsync
== APPENDFSYNC_EVERYSEC
&&
6510 now
-server
.lastfsync
> 1))
6512 fsync(server
.appendfd
); /* Let's try to get this data on the disk */
6513 server
.lastfsync
= now
;
6517 /* In Redis commands are always executed in the context of a client, so in
6518 * order to load the append only file we need to create a fake client. */
6519 static struct redisClient
*createFakeClient(void) {
6520 struct redisClient
*c
= zmalloc(sizeof(*c
));
6524 c
->querybuf
= sdsempty();
6528 /* We set the fake client as a slave waiting for the synchronization
6529 * so that Redis will not try to send replies to this client. */
6530 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
6531 c
->reply
= listCreate();
6532 listSetFreeMethod(c
->reply
,decrRefCount
);
6533 listSetDupMethod(c
->reply
,dupClientReplyValue
);
6537 static void freeFakeClient(struct redisClient
*c
) {
6538 sdsfree(c
->querybuf
);
6539 listRelease(c
->reply
);
6543 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
6544 * error (the append only file is zero-length) REDIS_ERR is returned. On
6545 * fatal error an error message is logged and the program exists. */
6546 int loadAppendOnlyFile(char *filename
) {
6547 struct redisClient
*fakeClient
;
6548 FILE *fp
= fopen(filename
,"r");
6549 struct redis_stat sb
;
6550 unsigned long long loadedkeys
= 0;
6552 if (redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0)
6556 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
6560 fakeClient
= createFakeClient();
6567 struct redisCommand
*cmd
;
6569 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
6575 if (buf
[0] != '*') goto fmterr
;
6577 argv
= zmalloc(sizeof(robj
*)*argc
);
6578 for (j
= 0; j
< argc
; j
++) {
6579 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
6580 if (buf
[0] != '$') goto fmterr
;
6581 len
= strtol(buf
+1,NULL
,10);
6582 argsds
= sdsnewlen(NULL
,len
);
6583 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
6584 argv
[j
] = createObject(REDIS_STRING
,argsds
);
6585 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
6588 /* Command lookup */
6589 cmd
= lookupCommand(argv
[0]->ptr
);
6591 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
6594 /* Try object sharing and encoding */
6595 if (server
.shareobjects
) {
6597 for(j
= 1; j
< argc
; j
++)
6598 argv
[j
] = tryObjectSharing(argv
[j
]);
6600 if (cmd
->flags
& REDIS_CMD_BULK
)
6601 tryObjectEncoding(argv
[argc
-1]);
6602 /* Run the command in the context of a fake client */
6603 fakeClient
->argc
= argc
;
6604 fakeClient
->argv
= argv
;
6605 cmd
->proc(fakeClient
);
6606 /* Discard the reply objects list from the fake client */
6607 while(listLength(fakeClient
->reply
))
6608 listDelNode(fakeClient
->reply
,listFirst(fakeClient
->reply
));
6609 /* Clean up, ready for the next command */
6610 for (j
= 0; j
< argc
; j
++) decrRefCount(argv
[j
]);
6612 /* Handle swapping while loading big datasets when VM is on */
6614 if (server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
6615 while (zmalloc_used_memory() > server
.vm_max_memory
) {
6616 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
6621 freeFakeClient(fakeClient
);
6626 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
6628 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
6632 redisLog(REDIS_WARNING
,"Bad file format reading the append only file");
6636 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
6637 static int fwriteBulk(FILE *fp
, robj
*obj
) {
6639 obj
= getDecodedObject(obj
);
6640 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(long)sdslen(obj
->ptr
));
6641 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) goto err
;
6642 if (sdslen(obj
->ptr
) && fwrite(obj
->ptr
,sdslen(obj
->ptr
),1,fp
) == 0)
6644 if (fwrite("\r\n",2,1,fp
) == 0) goto err
;
6652 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
6653 static int fwriteBulkDouble(FILE *fp
, double d
) {
6654 char buf
[128], dbuf
[128];
6656 snprintf(dbuf
,sizeof(dbuf
),"%.17g\r\n",d
);
6657 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(dbuf
)-2);
6658 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
6659 if (fwrite(dbuf
,strlen(dbuf
),1,fp
) == 0) return 0;
6663 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
6664 static int fwriteBulkLong(FILE *fp
, long l
) {
6665 char buf
[128], lbuf
[128];
6667 snprintf(lbuf
,sizeof(lbuf
),"%ld\r\n",l
);
6668 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(lbuf
)-2);
6669 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
6670 if (fwrite(lbuf
,strlen(lbuf
),1,fp
) == 0) return 0;
6674 /* Write a sequence of commands able to fully rebuild the dataset into
6675 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
6676 static int rewriteAppendOnlyFile(char *filename
) {
6677 dictIterator
*di
= NULL
;
6682 time_t now
= time(NULL
);
6684 /* Note that we have to use a different temp name here compared to the
6685 * one used by rewriteAppendOnlyFileBackground() function. */
6686 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
6687 fp
= fopen(tmpfile
,"w");
6689 redisLog(REDIS_WARNING
, "Failed rewriting the append only file: %s", strerror(errno
));
6692 for (j
= 0; j
< server
.dbnum
; j
++) {
6693 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
6694 redisDb
*db
= server
.db
+j
;
6696 if (dictSize(d
) == 0) continue;
6697 di
= dictGetIterator(d
);
6703 /* SELECT the new DB */
6704 if (fwrite(selectcmd
,sizeof(selectcmd
)-1,1,fp
) == 0) goto werr
;
6705 if (fwriteBulkLong(fp
,j
) == 0) goto werr
;
6707 /* Iterate this DB writing every entry */
6708 while((de
= dictNext(di
)) != NULL
) {
6713 key
= dictGetEntryKey(de
);
6714 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
6715 key
->storage
== REDIS_VM_SWAPPING
) {
6716 o
= dictGetEntryVal(de
);
6719 o
= vmPreviewObject(key
);
6720 key
= dupStringObject(key
);
6723 expiretime
= getExpire(db
,key
);
6725 /* Save the key and associated value */
6726 if (o
->type
== REDIS_STRING
) {
6727 /* Emit a SET command */
6728 char cmd
[]="*3\r\n$3\r\nSET\r\n";
6729 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6731 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6732 if (fwriteBulk(fp
,o
) == 0) goto werr
;
6733 } else if (o
->type
== REDIS_LIST
) {
6734 /* Emit the RPUSHes needed to rebuild the list */
6735 list
*list
= o
->ptr
;
6739 while((ln
= listYield(list
))) {
6740 char cmd
[]="*3\r\n$5\r\nRPUSH\r\n";
6741 robj
*eleobj
= listNodeValue(ln
);
6743 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6744 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6745 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6747 } else if (o
->type
== REDIS_SET
) {
6748 /* Emit the SADDs needed to rebuild the set */
6750 dictIterator
*di
= dictGetIterator(set
);
6753 while((de
= dictNext(di
)) != NULL
) {
6754 char cmd
[]="*3\r\n$4\r\nSADD\r\n";
6755 robj
*eleobj
= dictGetEntryKey(de
);
6757 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6758 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6759 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6761 dictReleaseIterator(di
);
6762 } else if (o
->type
== REDIS_ZSET
) {
6763 /* Emit the ZADDs needed to rebuild the sorted set */
6765 dictIterator
*di
= dictGetIterator(zs
->dict
);
6768 while((de
= dictNext(di
)) != NULL
) {
6769 char cmd
[]="*4\r\n$4\r\nZADD\r\n";
6770 robj
*eleobj
= dictGetEntryKey(de
);
6771 double *score
= dictGetEntryVal(de
);
6773 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6774 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6775 if (fwriteBulkDouble(fp
,*score
) == 0) goto werr
;
6776 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6778 dictReleaseIterator(di
);
6780 redisAssert(0 != 0);
6782 /* Save the expire time */
6783 if (expiretime
!= -1) {
6784 char cmd
[]="*3\r\n$8\r\nEXPIREAT\r\n";
6785 /* If this key is already expired skip it */
6786 if (expiretime
< now
) continue;
6787 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6788 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6789 if (fwriteBulkLong(fp
,expiretime
) == 0) goto werr
;
6791 /* We created a few temp objects if the key->value pair
6792 * was about a swapped out object. Free both. */
6798 dictReleaseIterator(di
);
6801 /* Make sure data will not remain on the OS's output buffers */
6806 /* Use RENAME to make sure the DB file is changed atomically only
6807 * if the generate DB file is ok. */
6808 if (rename(tmpfile
,filename
) == -1) {
6809 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
6813 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
6819 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
6820 if (di
) dictReleaseIterator(di
);
6824 /* This is how rewriting of the append only file in background works:
6826 * 1) The user calls BGREWRITEAOF
6827 * 2) Redis calls this function, that forks():
6828 * 2a) the child rewrite the append only file in a temp file.
6829 * 2b) the parent accumulates differences in server.bgrewritebuf.
6830 * 3) When the child finished '2a' exists.
6831 * 4) The parent will trap the exit code, if it's OK, will append the
6832 * data accumulated into server.bgrewritebuf into the temp file, and
6833 * finally will rename(2) the temp file in the actual file name.
6834 * The the new file is reopened as the new append only file. Profit!
6836 static int rewriteAppendOnlyFileBackground(void) {
6839 if (server
.bgrewritechildpid
!= -1) return REDIS_ERR
;
6840 if ((childpid
= fork()) == 0) {
6845 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
6846 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
6853 if (childpid
== -1) {
6854 redisLog(REDIS_WARNING
,
6855 "Can't rewrite append only file in background: fork: %s",
6859 redisLog(REDIS_NOTICE
,
6860 "Background append only file rewriting started by pid %d",childpid
);
6861 server
.bgrewritechildpid
= childpid
;
6862 /* We set appendseldb to -1 in order to force the next call to the
6863 * feedAppendOnlyFile() to issue a SELECT command, so the differences
6864 * accumulated by the parent into server.bgrewritebuf will start
6865 * with a SELECT statement and it will be safe to merge. */
6866 server
.appendseldb
= -1;
6869 return REDIS_OK
; /* unreached */
6872 static void bgrewriteaofCommand(redisClient
*c
) {
6873 if (server
.bgrewritechildpid
!= -1) {
6874 addReplySds(c
,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
6877 if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
6878 char *status
= "+Background append only file rewriting started\r\n";
6879 addReplySds(c
,sdsnew(status
));
6881 addReply(c
,shared
.err
);
6885 static void aofRemoveTempFile(pid_t childpid
) {
6888 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
6892 /* Virtual Memory is composed mainly of two subsystems:
6893 * - Blocking Virutal Memory
6894 * - Threaded Virtual Memory I/O
6895 * The two parts are not fully decoupled, but functions are split among two
6896 * different sections of the source code (delimited by comments) in order to
6897 * make more clear what functionality is about the blocking VM and what about
6898 * the threaded (not blocking) VM.
6902 * Redis VM is a blocking VM (one that blocks reading swapped values from
6903 * disk into memory when a value swapped out is needed in memory) that is made
6904 * unblocking by trying to examine the command argument vector in order to
6905 * load in background values that will likely be needed in order to exec
6906 * the command. The command is executed only once all the relevant keys
6907 * are loaded into memory.
6909 * This basically is almost as simple of a blocking VM, but almost as parallel
6910 * as a fully non-blocking VM.
6913 /* =================== Virtual Memory - Blocking Side ====================== */
6914 static void vmInit(void) {
6918 server
.vm_fp
= fopen("/tmp/redisvm","w+b");
6919 if (server
.vm_fp
== NULL
) {
6920 redisLog(REDIS_WARNING
,"Impossible to open the swap file. Exiting.");
6923 server
.vm_fd
= fileno(server
.vm_fp
);
6924 server
.vm_next_page
= 0;
6925 server
.vm_near_pages
= 0;
6926 server
.vm_stats_used_pages
= 0;
6927 server
.vm_stats_swapped_objects
= 0;
6928 server
.vm_stats_swapouts
= 0;
6929 server
.vm_stats_swapins
= 0;
6930 totsize
= server
.vm_pages
*server
.vm_page_size
;
6931 redisLog(REDIS_NOTICE
,"Allocating %lld bytes of swap file",totsize
);
6932 if (ftruncate(server
.vm_fd
,totsize
) == -1) {
6933 redisLog(REDIS_WARNING
,"Can't ftruncate swap file: %s. Exiting.",
6937 redisLog(REDIS_NOTICE
,"Swap file allocated with success");
6939 server
.vm_bitmap
= zmalloc((server
.vm_pages
+7)/8);
6940 redisLog(REDIS_VERBOSE
,"Allocated %lld bytes page table for %lld pages",
6941 (long long) (server
.vm_pages
+7)/8, server
.vm_pages
);
6942 memset(server
.vm_bitmap
,0,(server
.vm_pages
+7)/8);
6943 /* Try to remove the swap file, so the OS will really delete it from the
6944 * file system when Redis exists. */
6945 unlink("/tmp/redisvm");
6947 /* Initialize threaded I/O (used by Virtual Memory) */
6948 server
.io_newjobs
= listCreate();
6949 server
.io_processing
= listCreate();
6950 server
.io_processed
= listCreate();
6951 server
.io_clients
= listCreate();
6952 pthread_mutex_init(&server
.io_mutex
,NULL
);
6953 server
.io_active_threads
= 0;
6954 if (pipe(pipefds
) == -1) {
6955 redisLog(REDIS_WARNING
,"Unable to intialized VM: pipe(2): %s. Exiting."
6959 server
.io_ready_pipe_read
= pipefds
[0];
6960 server
.io_ready_pipe_write
= pipefds
[1];
6961 redisAssert(anetNonBlock(NULL
,server
.io_ready_pipe_read
) != ANET_ERR
);
6964 /* Mark the page as used */
6965 static void vmMarkPageUsed(off_t page
) {
6966 off_t byte
= page
/8;
6968 server
.vm_bitmap
[byte
] |= 1<<bit
;
6969 redisLog(REDIS_DEBUG
,"Mark used: %lld (byte:%lld bit:%d)\n",
6970 (long long)page
, (long long)byte
, bit
);
6973 /* Mark N contiguous pages as used, with 'page' being the first. */
6974 static void vmMarkPagesUsed(off_t page
, off_t count
) {
6977 for (j
= 0; j
< count
; j
++)
6978 vmMarkPageUsed(page
+j
);
6979 server
.vm_stats_used_pages
+= count
;
6982 /* Mark the page as free */
6983 static void vmMarkPageFree(off_t page
) {
6984 off_t byte
= page
/8;
6986 server
.vm_bitmap
[byte
] &= ~(1<<bit
);
6989 /* Mark N contiguous pages as free, with 'page' being the first. */
6990 static void vmMarkPagesFree(off_t page
, off_t count
) {
6993 for (j
= 0; j
< count
; j
++)
6994 vmMarkPageFree(page
+j
);
6995 server
.vm_stats_used_pages
-= count
;
6998 /* Test if the page is free */
6999 static int vmFreePage(off_t page
) {
7000 off_t byte
= page
/8;
7002 return (server
.vm_bitmap
[byte
] & (1<<bit
)) == 0;
7005 /* Find N contiguous free pages storing the first page of the cluster in *first.
7006 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
7007 * REDIS_ERR is returned.
7009 * This function uses a simple algorithm: we try to allocate
7010 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
7011 * again from the start of the swap file searching for free spaces.
7013 * If it looks pretty clear that there are no free pages near our offset
7014 * we try to find less populated places doing a forward jump of
7015 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
7016 * without hurry, and then we jump again and so forth...
7018 * This function can be improved using a free list to avoid to guess
7019 * too much, since we could collect data about freed pages.
7021 * note: I implemented this function just after watching an episode of
7022 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
7024 static int vmFindContiguousPages(off_t
*first
, int n
) {
7025 off_t base
, offset
= 0, since_jump
= 0, numfree
= 0;
7027 if (server
.vm_near_pages
== REDIS_VM_MAX_NEAR_PAGES
) {
7028 server
.vm_near_pages
= 0;
7029 server
.vm_next_page
= 0;
7031 server
.vm_near_pages
++; /* Yet another try for pages near to the old ones */
7032 base
= server
.vm_next_page
;
7034 while(offset
< server
.vm_pages
) {
7035 off_t
this = base
+offset
;
7037 redisLog(REDIS_DEBUG
, "THIS: %lld (%c)\n", (long long) this, vmFreePage(this) ? 'F' : 'X');
7038 /* If we overflow, restart from page zero */
7039 if (this >= server
.vm_pages
) {
7040 this -= server
.vm_pages
;
7042 /* Just overflowed, what we found on tail is no longer
7043 * interesting, as it's no longer contiguous. */
7047 if (vmFreePage(this)) {
7048 /* This is a free page */
7050 /* Already got N free pages? Return to the caller, with success */
7052 *first
= this-(n
-1);
7053 server
.vm_next_page
= this+1;
7057 /* The current one is not a free page */
7061 /* Fast-forward if the current page is not free and we already
7062 * searched enough near this place. */
7064 if (!numfree
&& since_jump
>= REDIS_VM_MAX_RANDOM_JUMP
/4) {
7065 offset
+= random() % REDIS_VM_MAX_RANDOM_JUMP
;
7067 /* Note that even if we rewind after the jump, we are don't need
7068 * to make sure numfree is set to zero as we only jump *if* it
7069 * is set to zero. */
7071 /* Otherwise just check the next page */
7078 /* Swap the 'val' object relative to 'key' into disk. Store all the information
7079 * needed to later retrieve the object into the key object.
7080 * If we can't find enough contiguous empty pages to swap the object on disk
7081 * REDIS_ERR is returned. */
7082 static int vmSwapObjectBlocking(robj
*key
, robj
*val
) {
7083 off_t pages
= rdbSavedObjectPages(val
);
7086 assert(key
->storage
== REDIS_VM_MEMORY
);
7087 assert(key
->refcount
== 1);
7088 if (vmFindContiguousPages(&page
,pages
) == REDIS_ERR
) return REDIS_ERR
;
7089 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
7090 redisLog(REDIS_WARNING
,
7091 "Critical VM problem in vmSwapObjectBlocking(): can't seek: %s",
7095 rdbSaveObject(server
.vm_fp
,val
);
7096 key
->vm
.page
= page
;
7097 key
->vm
.usedpages
= pages
;
7098 key
->storage
= REDIS_VM_SWAPPED
;
7099 key
->vtype
= val
->type
;
7100 decrRefCount(val
); /* Deallocate the object from memory. */
7101 vmMarkPagesUsed(page
,pages
);
7102 redisLog(REDIS_DEBUG
,"VM: object %s swapped out at %lld (%lld pages)",
7103 (unsigned char*) key
->ptr
,
7104 (unsigned long long) page
, (unsigned long long) pages
);
7105 server
.vm_stats_swapped_objects
++;
7106 server
.vm_stats_swapouts
++;
7107 fflush(server
.vm_fp
);
7111 static int vmSwapObjectThreaded(robj
*key
, robj
*val
) {
7118 /* Load the value object relative to the 'key' object from swap to memory.
7119 * The newly allocated object is returned.
7121 * If preview is true the unserialized object is returned to the caller but
7122 * no changes are made to the key object, nor the pages are marked as freed */
7123 static robj
*vmGenericLoadObject(robj
*key
, int preview
) {
7126 redisAssert(key
->storage
== REDIS_VM_SWAPPED
);
7127 if (fseeko(server
.vm_fp
,key
->vm
.page
*server
.vm_page_size
,SEEK_SET
) == -1) {
7128 redisLog(REDIS_WARNING
,
7129 "Unrecoverable VM problem in vmLoadObject(): can't seek: %s",
7133 val
= rdbLoadObject(key
->vtype
,server
.vm_fp
);
7135 redisLog(REDIS_WARNING
, "Unrecoverable VM problem in vmLoadObject(): can't load object from swap file: %s", strerror(errno
));
7139 key
->storage
= REDIS_VM_MEMORY
;
7140 key
->vm
.atime
= server
.unixtime
;
7141 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
7142 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk",
7143 (unsigned char*) key
->ptr
);
7144 server
.vm_stats_swapped_objects
--;
7146 redisLog(REDIS_DEBUG
, "VM: object %s previewed from disk",
7147 (unsigned char*) key
->ptr
);
7149 server
.vm_stats_swapins
++;
7153 /* Plain object loading, from swap to memory */
7154 static robj
*vmLoadObject(robj
*key
) {
7155 /* If we are loading the object in background, stop it, we
7156 * need to load this object synchronously ASAP. */
7157 if (key
->storage
== REDIS_VM_LOADING
)
7158 vmCancelThreadedIOJob(key
);
7159 return vmGenericLoadObject(key
,0);
7162 /* Just load the value on disk, without to modify the key.
7163 * This is useful when we want to perform some operation on the value
7164 * without to really bring it from swap to memory, like while saving the
7165 * dataset or rewriting the append only log. */
7166 static robj
*vmPreviewObject(robj
*key
) {
7167 return vmGenericLoadObject(key
,1);
7170 /* How a good candidate is this object for swapping?
7171 * The better candidate it is, the greater the returned value.
7173 * Currently we try to perform a fast estimation of the object size in
7174 * memory, and combine it with aging informations.
7176 * Basically swappability = idle-time * log(estimated size)
7178 * Bigger objects are preferred over smaller objects, but not
7179 * proportionally, this is why we use the logarithm. This algorithm is
7180 * just a first try and will probably be tuned later. */
7181 static double computeObjectSwappability(robj
*o
) {
7182 time_t age
= server
.unixtime
- o
->vm
.atime
;
7186 struct dictEntry
*de
;
7189 if (age
<= 0) return 0;
7192 if (o
->encoding
!= REDIS_ENCODING_RAW
) {
7195 asize
= sdslen(o
->ptr
)+sizeof(*o
)+sizeof(long)*2;
7200 listNode
*ln
= listFirst(l
);
7202 asize
= sizeof(list
);
7204 robj
*ele
= ln
->value
;
7207 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
7208 (sizeof(*o
)+sdslen(ele
->ptr
)) :
7210 asize
+= (sizeof(listNode
)+elesize
)*listLength(l
);
7215 z
= (o
->type
== REDIS_ZSET
);
7216 d
= z
? ((zset
*)o
->ptr
)->dict
: o
->ptr
;
7218 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
7219 if (z
) asize
+= sizeof(zset
)-sizeof(dict
);
7224 de
= dictGetRandomKey(d
);
7225 ele
= dictGetEntryKey(de
);
7226 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
7227 (sizeof(*o
)+sdslen(ele
->ptr
)) :
7229 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
7230 if (z
) asize
+= sizeof(zskiplistNode
)*dictSize(d
);
7234 return (double)asize
*log(1+asize
);
7237 /* Try to swap an object that's a good candidate for swapping.
7238 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
7239 * to swap any object at all.
7241 * If 'usethreaded' is true, Redis will try to swap the object in background
7242 * using I/O threads. */
7243 static int vmSwapOneObject(int usethreads
) {
7245 struct dictEntry
*best
= NULL
;
7246 double best_swappability
= 0;
7249 for (j
= 0; j
< server
.dbnum
; j
++) {
7250 redisDb
*db
= server
.db
+j
;
7251 int maxtries
= 1000;
7253 if (dictSize(db
->dict
) == 0) continue;
7254 for (i
= 0; i
< 5; i
++) {
7256 double swappability
;
7258 if (maxtries
) maxtries
--;
7259 de
= dictGetRandomKey(db
->dict
);
7260 key
= dictGetEntryKey(de
);
7261 val
= dictGetEntryVal(de
);
7262 if (key
->storage
!= REDIS_VM_MEMORY
) {
7263 if (maxtries
) i
--; /* don't count this try */
7266 swappability
= computeObjectSwappability(val
);
7267 if (!best
|| swappability
> best_swappability
) {
7269 best_swappability
= swappability
;
7274 redisLog(REDIS_DEBUG
,"No swappable key found!");
7277 key
= dictGetEntryKey(best
);
7278 val
= dictGetEntryVal(best
);
7280 redisLog(REDIS_DEBUG
,"Key with best swappability: %s, %f",
7281 key
->ptr
, best_swappability
);
7283 /* Unshare the key if needed */
7284 if (key
->refcount
> 1) {
7285 robj
*newkey
= dupStringObject(key
);
7287 key
= dictGetEntryKey(best
) = newkey
;
7291 vmSwapObjectThreaded(key
,val
);
7294 if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
7295 dictGetEntryVal(best
) = NULL
;
7303 static int vmSwapOneObjectBlocking() {
7304 return vmSwapOneObject(0);
7307 static int vmSwapOneObjectThreaded() {
7308 return vmSwapOneObject(1);
7311 /* Return true if it's safe to swap out objects in a given moment.
7312 * Basically we don't want to swap objects out while there is a BGSAVE
7313 * or a BGAEOREWRITE running in backgroud. */
7314 static int vmCanSwapOut(void) {
7315 return (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1);
7318 /* Delete a key if swapped. Returns 1 if the key was found, was swapped
7319 * and was deleted. Otherwise 0 is returned. */
7320 static int deleteIfSwapped(redisDb
*db
, robj
*key
) {
7324 if ((de
= dictFind(db
->dict
,key
)) == NULL
) return 0;
7325 foundkey
= dictGetEntryKey(de
);
7326 if (foundkey
->storage
== REDIS_VM_MEMORY
) return 0;
7331 /* =================== Virtual Memory - Threaded I/O ======================= */
7333 /* Every time a thread finished a Job, it writes a byte into the write side
7334 * of an unix pipe in order to "awake" the main thread, and this function
7336 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
,
7342 REDIS_NOTUSED(mask
);
7343 REDIS_NOTUSED(privdata
);
7345 /* For every byte we read in the read side of the pipe, there is one
7346 * I/O job completed to process. */
7347 while((retval
= read(fd
,buf
,1)) == 1) {
7348 redisLog(REDIS_DEBUG
,"Processing I/O completed job");
7350 if (retval
< 0 && errno
!= EAGAIN
) {
7351 redisLog(REDIS_WARNING
,
7352 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
7357 static void lockThreadedIO(void) {
7358 pthread_mutex_lock(&server
.io_mutex
);
7361 static void unlockThreadedIO(void) {
7362 pthread_mutex_unlock(&server
.io_mutex
);
7365 /* Remove the specified object from the threaded I/O queue if still not
7366 * processed, otherwise make sure to flag it as canceled. */
7367 static void vmCancelThreadedIOJob(robj
*o
) {
7369 server
.io_newjobs
, server
.io_processing
, server
.io_processed
7373 assert(o
->storage
== REDIS_VM_LOADING
|| o
->storage
== REDIS_VM_SWAPPING
);
7375 /* Search for a matching key in one of the queues */
7376 for (i
= 0; i
< 3; i
++) {
7379 listRewind(lists
[i
]);
7380 while ((ln
= listYield(lists
[i
])) != NULL
) {
7381 iojob
*job
= ln
->value
;
7383 if (compareStringObjects(job
->key
,o
) == 0) {
7385 case 0: /* io_newjobs */
7386 /* If the job was not yet processed the best thing to do
7387 * is to remove it from the queue at all */
7388 decrRefCount(job
->key
);
7389 if (job
->type
== REDIS_IOJOB_SWAP
)
7390 decrRefCount(job
->val
);
7391 listDelNode(lists
[i
],ln
);
7394 case 1: /* io_processing */
7395 case 2: /* io_processed */
7399 if (o
->storage
== REDIS_VM_LOADING
)
7400 o
->storage
= REDIS_VM_SWAPPED
;
7401 else if (o
->storage
== REDIS_VM_SWAPPING
)
7402 o
->storage
= REDIS_VM_MEMORY
;
7409 assert(1 != 1); /* We should never reach this */
7412 /* ================================= Debugging ============================== */
7414 static void debugCommand(redisClient
*c
) {
7415 if (!strcasecmp(c
->argv
[1]->ptr
,"segfault")) {
7417 } else if (!strcasecmp(c
->argv
[1]->ptr
,"reload")) {
7418 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
7419 addReply(c
,shared
.err
);
7423 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
7424 addReply(c
,shared
.err
);
7427 redisLog(REDIS_WARNING
,"DB reloaded by DEBUG RELOAD");
7428 addReply(c
,shared
.ok
);
7429 } else if (!strcasecmp(c
->argv
[1]->ptr
,"loadaof")) {
7431 if (loadAppendOnlyFile(server
.appendfilename
) != REDIS_OK
) {
7432 addReply(c
,shared
.err
);
7435 redisLog(REDIS_WARNING
,"Append Only File loaded by DEBUG LOADAOF");
7436 addReply(c
,shared
.ok
);
7437 } else if (!strcasecmp(c
->argv
[1]->ptr
,"object") && c
->argc
== 3) {
7438 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
7442 addReply(c
,shared
.nokeyerr
);
7445 key
= dictGetEntryKey(de
);
7446 val
= dictGetEntryVal(de
);
7447 if (server
.vm_enabled
&& key
->storage
== REDIS_VM_MEMORY
) {
7448 addReplySds(c
,sdscatprintf(sdsempty(),
7449 "+Key at:%p refcount:%d, value at:%p refcount:%d "
7450 "encoding:%d serializedlength:%lld\r\n",
7451 (void*)key
, key
->refcount
, (void*)val
, val
->refcount
,
7452 val
->encoding
, rdbSavedObjectLen(val
)));
7454 addReplySds(c
,sdscatprintf(sdsempty(),
7455 "+Key at:%p refcount:%d, value swapped at: page %llu "
7456 "using %llu pages\r\n",
7457 (void*)key
, key
->refcount
, (unsigned long long) key
->vm
.page
,
7458 (unsigned long long) key
->vm
.usedpages
));
7460 } else if (!strcasecmp(c
->argv
[1]->ptr
,"swapout") && c
->argc
== 3) {
7461 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
7464 if (!server
.vm_enabled
) {
7465 addReplySds(c
,sdsnew("-ERR Virtual Memory is disabled\r\n"));
7469 addReply(c
,shared
.nokeyerr
);
7472 key
= dictGetEntryKey(de
);
7473 val
= dictGetEntryVal(de
);
7474 /* If the key is shared we want to create a copy */
7475 if (key
->refcount
> 1) {
7476 robj
*newkey
= dupStringObject(key
);
7478 key
= dictGetEntryKey(de
) = newkey
;
7481 if (key
->storage
!= REDIS_VM_MEMORY
) {
7482 addReplySds(c
,sdsnew("-ERR This key is not in memory\r\n"));
7483 } else if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
7484 dictGetEntryVal(de
) = NULL
;
7485 addReply(c
,shared
.ok
);
7487 addReply(c
,shared
.err
);
7490 addReplySds(c
,sdsnew(
7491 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPOUT <key>|RELOAD]\r\n"));
7495 static void _redisAssert(char *estr
) {
7496 redisLog(REDIS_WARNING
,"=== ASSERTION FAILED ===");
7497 redisLog(REDIS_WARNING
,"==> %s\n",estr
);
7498 #ifdef HAVE_BACKTRACE
7499 redisLog(REDIS_WARNING
,"(forcing SIGSEGV in order to print the stack trace)");
7504 /* =================================== Main! ================================ */
7507 int linuxOvercommitMemoryValue(void) {
7508 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
7512 if (fgets(buf
,64,fp
) == NULL
) {
7521 void linuxOvercommitMemoryWarning(void) {
7522 if (linuxOvercommitMemoryValue() == 0) {
7523 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.");
7526 #endif /* __linux__ */
7528 static void daemonize(void) {
7532 if (fork() != 0) exit(0); /* parent exits */
7533 printf("New pid: %d\n", getpid());
7534 setsid(); /* create a new session */
7536 /* Every output goes to /dev/null. If Redis is daemonized but
7537 * the 'logfile' is set to 'stdout' in the configuration file
7538 * it will not log at all. */
7539 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
7540 dup2(fd
, STDIN_FILENO
);
7541 dup2(fd
, STDOUT_FILENO
);
7542 dup2(fd
, STDERR_FILENO
);
7543 if (fd
> STDERR_FILENO
) close(fd
);
7545 /* Try to write the pid file */
7546 fp
= fopen(server
.pidfile
,"w");
7548 fprintf(fp
,"%d\n",getpid());
7553 int main(int argc
, char **argv
) {
7556 resetServerSaveParams();
7557 loadServerConfig(argv
[1]);
7558 } else if (argc
> 2) {
7559 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
7562 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'");
7564 if (server
.daemonize
) daemonize();
7566 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
7568 linuxOvercommitMemoryWarning();
7570 if (server
.appendonly
) {
7571 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
7572 redisLog(REDIS_NOTICE
,"DB loaded from append only file");
7574 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
7575 redisLog(REDIS_NOTICE
,"DB loaded from disk");
7577 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
7579 aeDeleteEventLoop(server
.el
);
7583 /* ============================= Backtrace support ========================= */
7585 #ifdef HAVE_BACKTRACE
7586 static char *findFuncName(void *pointer
, unsigned long *offset
);
7588 static void *getMcontextEip(ucontext_t
*uc
) {
7589 #if defined(__FreeBSD__)
7590 return (void*) uc
->uc_mcontext
.mc_eip
;
7591 #elif defined(__dietlibc__)
7592 return (void*) uc
->uc_mcontext
.eip
;
7593 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
7595 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
7597 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
7599 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
7600 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
7601 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
7603 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
7605 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
7606 return (void*) uc
->uc_mcontext
.gregs
[REG_EIP
]; /* Linux 32/64 bit */
7607 #elif defined(__ia64__) /* Linux IA64 */
7608 return (void*) uc
->uc_mcontext
.sc_ip
;
7614 static void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
7616 char **messages
= NULL
;
7617 int i
, trace_size
= 0;
7618 unsigned long offset
=0;
7619 ucontext_t
*uc
= (ucontext_t
*) secret
;
7621 REDIS_NOTUSED(info
);
7623 redisLog(REDIS_WARNING
,
7624 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
7625 infostring
= genRedisInfoString();
7626 redisLog(REDIS_WARNING
, "%s",infostring
);
7627 /* It's not safe to sdsfree() the returned string under memory
7628 * corruption conditions. Let it leak as we are going to abort */
7630 trace_size
= backtrace(trace
, 100);
7631 /* overwrite sigaction with caller's address */
7632 if (getMcontextEip(uc
) != NULL
) {
7633 trace
[1] = getMcontextEip(uc
);
7635 messages
= backtrace_symbols(trace
, trace_size
);
7637 for (i
=1; i
<trace_size
; ++i
) {
7638 char *fn
= findFuncName(trace
[i
], &offset
), *p
;
7640 p
= strchr(messages
[i
],'+');
7641 if (!fn
|| (p
&& ((unsigned long)strtol(p
+1,NULL
,10)) < offset
)) {
7642 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
7644 redisLog(REDIS_WARNING
,"%d redis-server %p %s + %d", i
, trace
[i
], fn
, (unsigned int)offset
);
7647 /* free(messages); Don't call free() with possibly corrupted memory. */
7651 static void setupSigSegvAction(void) {
7652 struct sigaction act
;
7654 sigemptyset (&act
.sa_mask
);
7655 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
7656 * is used. Otherwise, sa_handler is used */
7657 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
7658 act
.sa_sigaction
= segvHandler
;
7659 sigaction (SIGSEGV
, &act
, NULL
);
7660 sigaction (SIGBUS
, &act
, NULL
);
7661 sigaction (SIGFPE
, &act
, NULL
);
7662 sigaction (SIGILL
, &act
, NULL
);
7663 sigaction (SIGBUS
, &act
, NULL
);
7667 #include "staticsymbols.h"
7668 /* This function try to convert a pointer into a function name. It's used in
7669 * oreder to provide a backtrace under segmentation fault that's able to
7670 * display functions declared as static (otherwise the backtrace is useless). */
7671 static char *findFuncName(void *pointer
, unsigned long *offset
){
7673 unsigned long off
, minoff
= 0;
7675 /* Try to match against the Symbol with the smallest offset */
7676 for (i
=0; symsTable
[i
].pointer
; i
++) {
7677 unsigned long lp
= (unsigned long) pointer
;
7679 if (lp
!= (unsigned long)-1 && lp
>= symsTable
[i
].pointer
) {
7680 off
=lp
-symsTable
[i
].pointer
;
7681 if (ret
< 0 || off
< minoff
) {
7687 if (ret
== -1) return NULL
;
7689 return symsTable
[ret
].name
;
7691 #else /* HAVE_BACKTRACE */
7692 static void setupSigSegvAction(void) {
7694 #endif /* HAVE_BACKTRACE */