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 "0.09"
46 #include <arpa/inet.h>
50 #include <sys/resource.h>
53 #include "ae.h" /* Event driven programming library */
54 #include "sds.h" /* Dynamic safe strings */
55 #include "anet.h" /* Networking the easy way */
56 #include "dict.h" /* Hash tables */
57 #include "adlist.h" /* Linked lists */
58 #include "zmalloc.h" /* total memory usage aware version of malloc/free */
65 /* Static server configuration */
66 #define REDIS_SERVERPORT 6379 /* TCP port */
67 #define REDIS_MAXIDLETIME (60*5) /* default client timeout */
68 #define REDIS_QUERYBUF_LEN 1024
69 #define REDIS_LOADBUF_LEN 1024
70 #define REDIS_MAX_ARGS 16
71 #define REDIS_DEFAULT_DBNUM 16
72 #define REDIS_CONFIGLINE_MAX 1024
73 #define REDIS_OBJFREELIST_MAX 1000000 /* Max number of objects to cache */
74 #define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
75 #define REDIS_EXPIRELOOKUPS_PER_CRON 100 /* try to expire 100 keys/second */
77 /* Hash table parameters */
78 #define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
79 #define REDIS_HT_MINSLOTS 16384 /* Never resize the HT under this */
82 #define REDIS_CMD_BULK 1
83 #define REDIS_CMD_INLINE 2
86 #define REDIS_STRING 0
91 /* Object types only used for dumping to disk */
92 #define REDIS_SELECTDB 254
95 /* Defines related to the dump file format. To store 32 bits lengths for short
96 * keys requires a lot of space, so we check the most significant 2 bits of
97 * the first byte to interpreter the length:
99 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
100 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
101 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
102 * 11|000000 this means: specially encoded object will follow. The six bits
103 * number specify the kind of object that follows.
104 * See the REDIS_RDB_ENC_* defines.
106 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
107 * values, will fit inside. */
108 #define REDIS_RDB_6BITLEN 0
109 #define REDIS_RDB_14BITLEN 1
110 #define REDIS_RDB_32BITLEN 2
111 #define REDIS_RDB_ENCVAL 3
112 #define REDIS_RDB_LENERR UINT_MAX
114 /* When a length of a string object stored on disk has the first two bits
115 * set, the remaining two bits specify a special encoding for the object
116 * accordingly to the following defines: */
117 #define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
118 #define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
119 #define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
120 #define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
123 #define REDIS_CLOSE 1 /* This client connection should be closed ASAP */
124 #define REDIS_SLAVE 2 /* This client is a slave server */
125 #define REDIS_MASTER 4 /* This client is a master server */
126 #define REDIS_MONITOR 8 /* This client is a slave monitor, see MONITOR */
128 /* Server replication state */
129 #define REDIS_REPL_NONE 0 /* No active replication */
130 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
131 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
133 /* List related stuff */
137 /* Sort operations */
138 #define REDIS_SORT_GET 0
139 #define REDIS_SORT_DEL 1
140 #define REDIS_SORT_INCR 2
141 #define REDIS_SORT_DECR 3
142 #define REDIS_SORT_ASC 4
143 #define REDIS_SORT_DESC 5
144 #define REDIS_SORTKEY_MAX 1024
147 #define REDIS_DEBUG 0
148 #define REDIS_NOTICE 1
149 #define REDIS_WARNING 2
151 /* Anti-warning macro... */
152 #define REDIS_NOTUSED(V) ((void) V)
154 /*================================= Data types ============================== */
156 /* A redis object, that is a type able to hold a string / list / set */
157 typedef struct redisObject
{
163 typedef struct redisDb
{
169 /* With multiplexing we need to take per-clinet state.
170 * Clients are taken in a liked list. */
171 typedef struct redisClient
{
176 robj
*argv
[REDIS_MAX_ARGS
];
178 int bulklen
; /* bulk read len. -1 if not in bulk read mode */
181 time_t lastinteraction
; /* time of the last interaction, used for timeout */
182 int flags
; /* REDIS_CLOSE | REDIS_SLAVE | REDIS_MONITOR */
183 int slaveseldb
; /* slave selected db, if this client is a slave */
184 int authenticated
; /* when requirepass is non-NULL */
192 /* Global server state structure */
198 unsigned int sharingpoolsize
;
199 long long dirty
; /* changes to DB from the last save */
201 list
*slaves
, *monitors
;
202 char neterr
[ANET_ERR_LEN
];
204 int cronloops
; /* number of times the cron function run */
205 list
*objfreelist
; /* A list of freed objects to avoid malloc() */
206 time_t lastsave
; /* Unix time of last save succeeede */
207 int usedmemory
; /* Used memory in megabytes */
208 /* Fields used only for stats */
209 time_t stat_starttime
; /* server start time */
210 long long stat_numcommands
; /* number of processed commands */
211 long long stat_numconnections
; /* number of connections received */
219 int bgsaveinprogress
;
220 struct saveparam
*saveparams
;
227 /* Replication related */
233 /* Sort parameters - qsort_r() is only available under BSD so we
234 * have to take this state global, in order to pass it to sortCompare() */
240 typedef void redisCommandProc(redisClient
*c
);
241 struct redisCommand
{
243 redisCommandProc
*proc
;
248 typedef struct _redisSortObject
{
256 typedef struct _redisSortOperation
{
259 } redisSortOperation
;
261 struct sharedObjectsStruct
{
262 robj
*crlf
, *ok
, *err
, *emptybulk
, *czero
, *cone
, *pong
, *space
,
263 *colon
, *nullbulk
, *nullmultibulk
,
264 *emptymultibulk
, *wrongtypeerr
, *nokeyerr
, *syntaxerr
, *sameobjecterr
,
265 *outofrangeerr
, *plus
,
266 *select0
, *select1
, *select2
, *select3
, *select4
,
267 *select5
, *select6
, *select7
, *select8
, *select9
;
270 /*================================ Prototypes =============================== */
272 static void freeStringObject(robj
*o
);
273 static void freeListObject(robj
*o
);
274 static void freeSetObject(robj
*o
);
275 static void decrRefCount(void *o
);
276 static robj
*createObject(int type
, void *ptr
);
277 static void freeClient(redisClient
*c
);
278 static int rdbLoad(char *filename
);
279 static void addReply(redisClient
*c
, robj
*obj
);
280 static void addReplySds(redisClient
*c
, sds s
);
281 static void incrRefCount(robj
*o
);
282 static int rdbSaveBackground(char *filename
);
283 static robj
*createStringObject(char *ptr
, size_t len
);
284 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
285 static int syncWithMaster(void);
286 static robj
*tryObjectSharing(robj
*o
);
287 static int removeExpire(redisDb
*db
, robj
*key
);
288 static int expireIfNeeded(redisDb
*db
, robj
*key
);
289 static int deleteIfVolatile(redisDb
*db
, robj
*key
);
290 static int deleteKey(redisDb
*db
, robj
*key
);
292 static void authCommand(redisClient
*c
);
293 static void pingCommand(redisClient
*c
);
294 static void echoCommand(redisClient
*c
);
295 static void setCommand(redisClient
*c
);
296 static void setnxCommand(redisClient
*c
);
297 static void getCommand(redisClient
*c
);
298 static void delCommand(redisClient
*c
);
299 static void existsCommand(redisClient
*c
);
300 static void incrCommand(redisClient
*c
);
301 static void decrCommand(redisClient
*c
);
302 static void incrbyCommand(redisClient
*c
);
303 static void decrbyCommand(redisClient
*c
);
304 static void selectCommand(redisClient
*c
);
305 static void randomkeyCommand(redisClient
*c
);
306 static void keysCommand(redisClient
*c
);
307 static void dbsizeCommand(redisClient
*c
);
308 static void lastsaveCommand(redisClient
*c
);
309 static void saveCommand(redisClient
*c
);
310 static void bgsaveCommand(redisClient
*c
);
311 static void shutdownCommand(redisClient
*c
);
312 static void moveCommand(redisClient
*c
);
313 static void renameCommand(redisClient
*c
);
314 static void renamenxCommand(redisClient
*c
);
315 static void lpushCommand(redisClient
*c
);
316 static void rpushCommand(redisClient
*c
);
317 static void lpopCommand(redisClient
*c
);
318 static void rpopCommand(redisClient
*c
);
319 static void llenCommand(redisClient
*c
);
320 static void lindexCommand(redisClient
*c
);
321 static void lrangeCommand(redisClient
*c
);
322 static void ltrimCommand(redisClient
*c
);
323 static void typeCommand(redisClient
*c
);
324 static void lsetCommand(redisClient
*c
);
325 static void saddCommand(redisClient
*c
);
326 static void sremCommand(redisClient
*c
);
327 static void sismemberCommand(redisClient
*c
);
328 static void scardCommand(redisClient
*c
);
329 static void sinterCommand(redisClient
*c
);
330 static void sinterstoreCommand(redisClient
*c
);
331 static void syncCommand(redisClient
*c
);
332 static void flushdbCommand(redisClient
*c
);
333 static void flushallCommand(redisClient
*c
);
334 static void sortCommand(redisClient
*c
);
335 static void lremCommand(redisClient
*c
);
336 static void infoCommand(redisClient
*c
);
337 static void mgetCommand(redisClient
*c
);
338 static void monitorCommand(redisClient
*c
);
339 static void expireCommand(redisClient
*c
);
341 /*================================= Globals ================================= */
344 static struct redisServer server
; /* server global state */
345 static struct redisCommand cmdTable
[] = {
346 {"get",getCommand
,2,REDIS_CMD_INLINE
},
347 {"set",setCommand
,3,REDIS_CMD_BULK
},
348 {"setnx",setnxCommand
,3,REDIS_CMD_BULK
},
349 {"del",delCommand
,2,REDIS_CMD_INLINE
},
350 {"exists",existsCommand
,2,REDIS_CMD_INLINE
},
351 {"incr",incrCommand
,2,REDIS_CMD_INLINE
},
352 {"decr",decrCommand
,2,REDIS_CMD_INLINE
},
353 {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
},
354 {"rpush",rpushCommand
,3,REDIS_CMD_BULK
},
355 {"lpush",lpushCommand
,3,REDIS_CMD_BULK
},
356 {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
},
357 {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
},
358 {"llen",llenCommand
,2,REDIS_CMD_INLINE
},
359 {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
},
360 {"lset",lsetCommand
,4,REDIS_CMD_BULK
},
361 {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
},
362 {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
},
363 {"lrem",lremCommand
,4,REDIS_CMD_BULK
},
364 {"sadd",saddCommand
,3,REDIS_CMD_BULK
},
365 {"srem",sremCommand
,3,REDIS_CMD_BULK
},
366 {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
},
367 {"scard",scardCommand
,2,REDIS_CMD_INLINE
},
368 {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
},
369 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
},
370 {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
},
371 {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
},
372 {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
},
373 {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
},
374 {"select",selectCommand
,2,REDIS_CMD_INLINE
},
375 {"move",moveCommand
,3,REDIS_CMD_INLINE
},
376 {"rename",renameCommand
,3,REDIS_CMD_INLINE
},
377 {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
},
378 {"keys",keysCommand
,2,REDIS_CMD_INLINE
},
379 {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
},
380 {"auth",authCommand
,2,REDIS_CMD_INLINE
},
381 {"ping",pingCommand
,1,REDIS_CMD_INLINE
},
382 {"echo",echoCommand
,2,REDIS_CMD_BULK
},
383 {"save",saveCommand
,1,REDIS_CMD_INLINE
},
384 {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
},
385 {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
},
386 {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
},
387 {"type",typeCommand
,2,REDIS_CMD_INLINE
},
388 {"sync",syncCommand
,1,REDIS_CMD_INLINE
},
389 {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
},
390 {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
},
391 {"sort",sortCommand
,-2,REDIS_CMD_INLINE
},
392 {"info",infoCommand
,1,REDIS_CMD_INLINE
},
393 {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
},
394 {"expire",expireCommand
,3,REDIS_CMD_INLINE
},
398 /*============================ Utility functions ============================ */
400 /* Glob-style pattern matching. */
401 int stringmatchlen(const char *pattern
, int patternLen
,
402 const char *string
, int stringLen
, int nocase
)
407 while (pattern
[1] == '*') {
412 return 1; /* match */
414 if (stringmatchlen(pattern
+1, patternLen
-1,
415 string
, stringLen
, nocase
))
416 return 1; /* match */
420 return 0; /* no match */
424 return 0; /* no match */
434 not = pattern
[0] == '^';
441 if (pattern
[0] == '\\') {
444 if (pattern
[0] == string
[0])
446 } else if (pattern
[0] == ']') {
448 } else if (patternLen
== 0) {
452 } else if (pattern
[1] == '-' && patternLen
>= 3) {
453 int start
= pattern
[0];
454 int end
= pattern
[2];
462 start
= tolower(start
);
468 if (c
>= start
&& c
<= end
)
472 if (pattern
[0] == string
[0])
475 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
485 return 0; /* no match */
491 if (patternLen
>= 2) {
498 if (pattern
[0] != string
[0])
499 return 0; /* no match */
501 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
502 return 0; /* no match */
510 if (stringLen
== 0) {
511 while(*pattern
== '*') {
518 if (patternLen
== 0 && stringLen
== 0)
523 void redisLog(int level
, const char *fmt
, ...)
528 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
532 if (level
>= server
.verbosity
) {
534 fprintf(fp
,"%c ",c
[level
]);
535 vfprintf(fp
, fmt
, ap
);
541 if (server
.logfile
) fclose(fp
);
544 /*====================== Hash table type implementation ==================== */
546 /* This is an hash table type that uses the SDS dynamic strings libary as
547 * keys and radis objects as values (objects can hold SDS strings,
550 static int sdsDictKeyCompare(void *privdata
, const void *key1
,
554 DICT_NOTUSED(privdata
);
556 l1
= sdslen((sds
)key1
);
557 l2
= sdslen((sds
)key2
);
558 if (l1
!= l2
) return 0;
559 return memcmp(key1
, key2
, l1
) == 0;
562 static void dictRedisObjectDestructor(void *privdata
, void *val
)
564 DICT_NOTUSED(privdata
);
569 static int dictSdsKeyCompare(void *privdata
, const void *key1
,
572 const robj
*o1
= key1
, *o2
= key2
;
573 return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
576 static unsigned int dictSdsHash(const void *key
) {
578 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
581 static dictType setDictType
= {
582 dictSdsHash
, /* hash function */
585 dictSdsKeyCompare
, /* key compare */
586 dictRedisObjectDestructor
, /* key destructor */
587 NULL
/* val destructor */
590 static dictType hashDictType
= {
591 dictSdsHash
, /* hash function */
594 dictSdsKeyCompare
, /* key compare */
595 dictRedisObjectDestructor
, /* key destructor */
596 dictRedisObjectDestructor
/* val destructor */
599 /* ========================= Random utility functions ======================= */
601 /* Redis generally does not try to recover from out of memory conditions
602 * when allocating objects or strings, it is not clear if it will be possible
603 * to report this condition to the client since the networking layer itself
604 * is based on heap allocation for send buffers, so we simply abort.
605 * At least the code will be simpler to read... */
606 static void oom(const char *msg
) {
607 fprintf(stderr
, "%s: Out of memory\n",msg
);
613 /* ====================== Redis server networking stuff ===================== */
614 void closeTimedoutClients(void) {
618 time_t now
= time(NULL
);
620 li
= listGetIterator(server
.clients
,AL_START_HEAD
);
622 while ((ln
= listNextElement(li
)) != NULL
) {
623 c
= listNodeValue(ln
);
624 if (!(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
625 (now
- c
->lastinteraction
> server
.maxidletime
)) {
626 redisLog(REDIS_DEBUG
,"Closing idle client");
630 listReleaseIterator(li
);
633 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
634 int j
, loops
= server
.cronloops
++;
635 REDIS_NOTUSED(eventLoop
);
637 REDIS_NOTUSED(clientData
);
639 /* Update the global state with the amount of used memory */
640 server
.usedmemory
= zmalloc_used_memory();
642 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
643 * we resize the hash table to save memory */
644 for (j
= 0; j
< server
.dbnum
; j
++) {
645 int size
, used
, vkeys
;
647 size
= dictSlots(server
.db
[j
].dict
);
648 used
= dictSize(server
.db
[j
].dict
);
649 vkeys
= dictSize(server
.db
[j
].expires
);
650 if (!(loops
% 5) && used
> 0) {
651 redisLog(REDIS_DEBUG
,"DB %d: %d keys (%d volatile) in %d slots HT.",j
,used
,vkeys
,size
);
652 /* dictPrintStats(server.dict); */
654 if (size
&& used
&& size
> REDIS_HT_MINSLOTS
&&
655 (used
*100/size
< REDIS_HT_MINFILL
)) {
656 redisLog(REDIS_NOTICE
,"The hash table %d is too sparse, resize it...",j
);
657 dictResize(server
.db
[j
].dict
);
658 redisLog(REDIS_NOTICE
,"Hash table %d resized.",j
);
662 /* Show information about connected clients */
664 redisLog(REDIS_DEBUG
,"%d clients connected (%d slaves), %d bytes in use",
665 listLength(server
.clients
)-listLength(server
.slaves
),
666 listLength(server
.slaves
),
668 dictSize(server
.sharingpool
));
671 /* Close connections of timedout clients */
673 closeTimedoutClients();
675 /* Check if a background saving in progress terminated */
676 if (server
.bgsaveinprogress
) {
678 if (wait4(-1,&statloc
,WNOHANG
,NULL
)) {
679 int exitcode
= WEXITSTATUS(statloc
);
681 redisLog(REDIS_NOTICE
,
682 "Background saving terminated with success");
684 server
.lastsave
= time(NULL
);
686 redisLog(REDIS_WARNING
,
687 "Background saving error");
689 server
.bgsaveinprogress
= 0;
692 /* If there is not a background saving in progress check if
693 * we have to save now */
694 time_t now
= time(NULL
);
695 for (j
= 0; j
< server
.saveparamslen
; j
++) {
696 struct saveparam
*sp
= server
.saveparams
+j
;
698 if (server
.dirty
>= sp
->changes
&&
699 now
-server
.lastsave
> sp
->seconds
) {
700 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
701 sp
->changes
, sp
->seconds
);
702 rdbSaveBackground(server
.dbfilename
);
708 /* Try to expire a few timed out keys */
709 for (j
= 0; j
< server
.dbnum
; j
++) {
710 redisDb
*db
= server
.db
+j
;
711 int num
= dictSize(db
->expires
);
714 time_t now
= time(NULL
);
716 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
717 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
722 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
723 t
= (time_t) dictGetEntryVal(de
);
725 deleteKey(db
,dictGetEntryKey(de
));
731 /* Check if we should connect to a MASTER */
732 if (server
.replstate
== REDIS_REPL_CONNECT
) {
733 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
734 if (syncWithMaster() == REDIS_OK
) {
735 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
741 static void createSharedObjects(void) {
742 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
743 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
744 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
745 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
746 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
747 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
748 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
749 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
750 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
752 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
753 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
754 "-ERR Operation against a key holding the wrong kind of value\r\n"));
755 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
756 "-ERR no such key\r\n"));
757 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
758 "-ERR syntax error\r\n"));
759 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
760 "-ERR source and destination objects are the same\r\n"));
761 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
762 "-ERR index out of range\r\n"));
763 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
764 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
765 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
766 shared
.select0
= createStringObject("select 0\r\n",10);
767 shared
.select1
= createStringObject("select 1\r\n",10);
768 shared
.select2
= createStringObject("select 2\r\n",10);
769 shared
.select3
= createStringObject("select 3\r\n",10);
770 shared
.select4
= createStringObject("select 4\r\n",10);
771 shared
.select5
= createStringObject("select 5\r\n",10);
772 shared
.select6
= createStringObject("select 6\r\n",10);
773 shared
.select7
= createStringObject("select 7\r\n",10);
774 shared
.select8
= createStringObject("select 8\r\n",10);
775 shared
.select9
= createStringObject("select 9\r\n",10);
778 static void appendServerSaveParams(time_t seconds
, int changes
) {
779 server
.saveparams
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1));
780 if (server
.saveparams
== NULL
) oom("appendServerSaveParams");
781 server
.saveparams
[server
.saveparamslen
].seconds
= seconds
;
782 server
.saveparams
[server
.saveparamslen
].changes
= changes
;
783 server
.saveparamslen
++;
786 static void ResetServerSaveParams() {
787 zfree(server
.saveparams
);
788 server
.saveparams
= NULL
;
789 server
.saveparamslen
= 0;
792 static void initServerConfig() {
793 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
794 server
.port
= REDIS_SERVERPORT
;
795 server
.verbosity
= REDIS_DEBUG
;
796 server
.maxidletime
= REDIS_MAXIDLETIME
;
797 server
.saveparams
= NULL
;
798 server
.logfile
= NULL
; /* NULL = log on standard output */
799 server
.bindaddr
= NULL
;
800 server
.glueoutputbuf
= 1;
801 server
.daemonize
= 0;
802 server
.pidfile
= "/var/run/redis.pid";
803 server
.dbfilename
= "dump.rdb";
804 server
.requirepass
= NULL
;
805 server
.shareobjects
= 0;
806 ResetServerSaveParams();
808 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
809 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
810 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
811 /* Replication related */
813 server
.masterhost
= NULL
;
814 server
.masterport
= 6379;
815 server
.master
= NULL
;
816 server
.replstate
= REDIS_REPL_NONE
;
819 static void initServer() {
822 signal(SIGHUP
, SIG_IGN
);
823 signal(SIGPIPE
, SIG_IGN
);
825 server
.clients
= listCreate();
826 server
.slaves
= listCreate();
827 server
.monitors
= listCreate();
828 server
.objfreelist
= listCreate();
829 createSharedObjects();
830 server
.el
= aeCreateEventLoop();
831 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
832 server
.sharingpool
= dictCreate(&setDictType
,NULL
);
833 server
.sharingpoolsize
= 1024;
834 if (!server
.db
|| !server
.clients
|| !server
.slaves
|| !server
.monitors
|| !server
.el
|| !server
.objfreelist
)
835 oom("server initialization"); /* Fatal OOM */
836 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
837 if (server
.fd
== -1) {
838 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
841 for (j
= 0; j
< server
.dbnum
; j
++) {
842 server
.db
[j
].dict
= dictCreate(&hashDictType
,NULL
);
843 server
.db
[j
].expires
= dictCreate(&setDictType
,NULL
);
846 server
.cronloops
= 0;
847 server
.bgsaveinprogress
= 0;
848 server
.lastsave
= time(NULL
);
850 server
.usedmemory
= 0;
851 server
.stat_numcommands
= 0;
852 server
.stat_numconnections
= 0;
853 server
.stat_starttime
= time(NULL
);
854 aeCreateTimeEvent(server
.el
, 1000, serverCron
, NULL
, NULL
);
857 /* Empty the whole database */
858 static void emptyDb() {
861 for (j
= 0; j
< server
.dbnum
; j
++) {
862 dictEmpty(server
.db
[j
].dict
);
863 dictEmpty(server
.db
[j
].expires
);
867 /* I agree, this is a very rudimental way to load a configuration...
868 will improve later if the config gets more complex */
869 static void loadServerConfig(char *filename
) {
870 FILE *fp
= fopen(filename
,"r");
871 char buf
[REDIS_CONFIGLINE_MAX
+1], *err
= NULL
;
876 redisLog(REDIS_WARNING
,"Fatal error, can't open config file");
879 while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) {
885 line
= sdstrim(line
," \t\r\n");
887 /* Skip comments and blank lines*/
888 if (line
[0] == '#' || line
[0] == '\0') {
893 /* Split into arguments */
894 argv
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
);
897 /* Execute config directives */
898 if (!strcmp(argv
[0],"timeout") && argc
== 2) {
899 server
.maxidletime
= atoi(argv
[1]);
900 if (server
.maxidletime
< 1) {
901 err
= "Invalid timeout value"; goto loaderr
;
903 } else if (!strcmp(argv
[0],"port") && argc
== 2) {
904 server
.port
= atoi(argv
[1]);
905 if (server
.port
< 1 || server
.port
> 65535) {
906 err
= "Invalid port"; goto loaderr
;
908 } else if (!strcmp(argv
[0],"bind") && argc
== 2) {
909 server
.bindaddr
= zstrdup(argv
[1]);
910 } else if (!strcmp(argv
[0],"save") && argc
== 3) {
911 int seconds
= atoi(argv
[1]);
912 int changes
= atoi(argv
[2]);
913 if (seconds
< 1 || changes
< 0) {
914 err
= "Invalid save parameters"; goto loaderr
;
916 appendServerSaveParams(seconds
,changes
);
917 } else if (!strcmp(argv
[0],"dir") && argc
== 2) {
918 if (chdir(argv
[1]) == -1) {
919 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s",
920 argv
[1], strerror(errno
));
923 } else if (!strcmp(argv
[0],"loglevel") && argc
== 2) {
924 if (!strcmp(argv
[1],"debug")) server
.verbosity
= REDIS_DEBUG
;
925 else if (!strcmp(argv
[1],"notice")) server
.verbosity
= REDIS_NOTICE
;
926 else if (!strcmp(argv
[1],"warning")) server
.verbosity
= REDIS_WARNING
;
928 err
= "Invalid log level. Must be one of debug, notice, warning";
931 } else if (!strcmp(argv
[0],"logfile") && argc
== 2) {
934 server
.logfile
= zstrdup(argv
[1]);
935 if (!strcmp(server
.logfile
,"stdout")) {
936 zfree(server
.logfile
);
937 server
.logfile
= NULL
;
939 if (server
.logfile
) {
940 /* Test if we are able to open the file. The server will not
941 * be able to abort just for this problem later... */
942 fp
= fopen(server
.logfile
,"a");
944 err
= sdscatprintf(sdsempty(),
945 "Can't open the log file: %s", strerror(errno
));
950 } else if (!strcmp(argv
[0],"databases") && argc
== 2) {
951 server
.dbnum
= atoi(argv
[1]);
952 if (server
.dbnum
< 1) {
953 err
= "Invalid number of databases"; goto loaderr
;
955 } else if (!strcmp(argv
[0],"slaveof") && argc
== 3) {
956 server
.masterhost
= sdsnew(argv
[1]);
957 server
.masterport
= atoi(argv
[2]);
958 server
.replstate
= REDIS_REPL_CONNECT
;
959 } else if (!strcmp(argv
[0],"glueoutputbuf") && argc
== 2) {
961 if (!strcmp(argv
[1],"yes")) server
.glueoutputbuf
= 1;
962 else if (!strcmp(argv
[1],"no")) server
.glueoutputbuf
= 0;
964 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
966 } else if (!strcmp(argv
[0],"shareobjects") && argc
== 2) {
968 if (!strcmp(argv
[1],"yes")) server
.shareobjects
= 1;
969 else if (!strcmp(argv
[1],"no")) server
.shareobjects
= 0;
971 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
973 } else if (!strcmp(argv
[0],"daemonize") && argc
== 2) {
975 if (!strcmp(argv
[1],"yes")) server
.daemonize
= 1;
976 else if (!strcmp(argv
[1],"no")) server
.daemonize
= 0;
978 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
980 } else if (!strcmp(argv
[0],"requirepass") && argc
== 2) {
981 server
.requirepass
= zstrdup(argv
[1]);
982 } else if (!strcmp(argv
[0],"pidfile") && argc
== 2) {
983 server
.pidfile
= zstrdup(argv
[1]);
985 err
= "Bad directive or wrong number of arguments"; goto loaderr
;
987 for (j
= 0; j
< argc
; j
++)
996 fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n");
997 fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
);
998 fprintf(stderr
, ">>> '%s'\n", line
);
999 fprintf(stderr
, "%s\n", err
);
1003 static void freeClientArgv(redisClient
*c
) {
1006 for (j
= 0; j
< c
->argc
; j
++)
1007 decrRefCount(c
->argv
[j
]);
1011 static void freeClient(redisClient
*c
) {
1014 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
1015 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1016 sdsfree(c
->querybuf
);
1017 listRelease(c
->reply
);
1020 ln
= listSearchKey(server
.clients
,c
);
1022 listDelNode(server
.clients
,ln
);
1023 if (c
->flags
& REDIS_SLAVE
) {
1024 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
1025 ln
= listSearchKey(l
,c
);
1029 if (c
->flags
& REDIS_MASTER
) {
1030 server
.master
= NULL
;
1031 server
.replstate
= REDIS_REPL_CONNECT
;
1036 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
1038 listNode
*ln
= c
->reply
->head
, *next
;
1043 totlen
+= sdslen(o
->ptr
);
1045 /* This optimization makes more sense if we don't have to copy
1047 if (totlen
> 1024) return;
1053 ln
= c
->reply
->head
;
1057 memcpy(buf
+copylen
,o
->ptr
,sdslen(o
->ptr
));
1058 copylen
+= sdslen(o
->ptr
);
1059 listDelNode(c
->reply
,ln
);
1062 /* Now the output buffer is empty, add the new single element */
1063 addReplySds(c
,sdsnewlen(buf
,totlen
));
1067 static void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1068 redisClient
*c
= privdata
;
1069 int nwritten
= 0, totwritten
= 0, objlen
;
1072 REDIS_NOTUSED(mask
);
1074 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
1075 glueReplyBuffersIfNeeded(c
);
1076 while(listLength(c
->reply
)) {
1077 o
= listNodeValue(listFirst(c
->reply
));
1078 objlen
= sdslen(o
->ptr
);
1081 listDelNode(c
->reply
,listFirst(c
->reply
));
1085 if (c
->flags
& REDIS_MASTER
) {
1086 nwritten
= objlen
- c
->sentlen
;
1088 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen
- c
->sentlen
);
1089 if (nwritten
<= 0) break;
1091 c
->sentlen
+= nwritten
;
1092 totwritten
+= nwritten
;
1093 /* If we fully sent the object on head go to the next one */
1094 if (c
->sentlen
== objlen
) {
1095 listDelNode(c
->reply
,listFirst(c
->reply
));
1099 if (nwritten
== -1) {
1100 if (errno
== EAGAIN
) {
1103 redisLog(REDIS_DEBUG
,
1104 "Error writing to client: %s", strerror(errno
));
1109 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
1110 if (listLength(c
->reply
) == 0) {
1112 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1116 static struct redisCommand
*lookupCommand(char *name
) {
1118 while(cmdTable
[j
].name
!= NULL
) {
1119 if (!strcmp(name
,cmdTable
[j
].name
)) return &cmdTable
[j
];
1125 /* resetClient prepare the client to process the next command */
1126 static void resetClient(redisClient
*c
) {
1131 /* If this function gets called we already read a whole
1132 * command, argments are in the client argv/argc fields.
1133 * processCommand() execute the command or prepare the
1134 * server for a bulk read from the client.
1136 * If 1 is returned the client is still alive and valid and
1137 * and other operations can be performed by the caller. Otherwise
1138 * if 0 is returned the client was destroied (i.e. after QUIT). */
1139 static int processCommand(redisClient
*c
) {
1140 struct redisCommand
*cmd
;
1143 sdstolower(c
->argv
[0]->ptr
);
1144 /* The QUIT command is handled as a special case. Normal command
1145 * procs are unable to close the client connection safely */
1146 if (!strcmp(c
->argv
[0]->ptr
,"quit")) {
1150 cmd
= lookupCommand(c
->argv
[0]->ptr
);
1152 addReplySds(c
,sdsnew("-ERR unknown command\r\n"));
1155 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
1156 (c
->argc
< -cmd
->arity
)) {
1157 addReplySds(c
,sdsnew("-ERR wrong number of arguments\r\n"));
1160 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
1161 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
1163 decrRefCount(c
->argv
[c
->argc
-1]);
1164 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
1166 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
1171 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
1172 /* It is possible that the bulk read is already in the
1173 * buffer. Check this condition and handle it accordingly */
1174 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
1175 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
1177 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
1182 /* Let's try to share objects on the command arguments vector */
1183 if (server
.shareobjects
) {
1185 for(j
= 1; j
< c
->argc
; j
++)
1186 c
->argv
[j
] = tryObjectSharing(c
->argv
[j
]);
1188 /* Check if the user is authenticated */
1189 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
1190 addReplySds(c
,sdsnew("-ERR operation not permitted\r\n"));
1195 /* Exec the command */
1196 dirty
= server
.dirty
;
1198 if (server
.dirty
-dirty
!= 0 && listLength(server
.slaves
))
1199 replicationFeedSlaves(server
.slaves
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1200 if (listLength(server
.monitors
))
1201 replicationFeedSlaves(server
.monitors
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1202 server
.stat_numcommands
++;
1204 /* Prepare the client for the next command */
1205 if (c
->flags
& REDIS_CLOSE
) {
1213 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
1214 listNode
*ln
= slaves
->head
;
1215 robj
*outv
[REDIS_MAX_ARGS
*4]; /* enough room for args, spaces, newlines */
1218 for (j
= 0; j
< argc
; j
++) {
1219 if (j
!= 0) outv
[outc
++] = shared
.space
;
1220 if ((cmd
->flags
& REDIS_CMD_BULK
) && j
== argc
-1) {
1223 lenobj
= createObject(REDIS_STRING
,
1224 sdscatprintf(sdsempty(),"%d\r\n",sdslen(argv
[j
]->ptr
)));
1225 lenobj
->refcount
= 0;
1226 outv
[outc
++] = lenobj
;
1228 outv
[outc
++] = argv
[j
];
1230 outv
[outc
++] = shared
.crlf
;
1233 redisClient
*slave
= ln
->value
;
1234 if (slave
->slaveseldb
!= dictid
) {
1238 case 0: selectcmd
= shared
.select0
; break;
1239 case 1: selectcmd
= shared
.select1
; break;
1240 case 2: selectcmd
= shared
.select2
; break;
1241 case 3: selectcmd
= shared
.select3
; break;
1242 case 4: selectcmd
= shared
.select4
; break;
1243 case 5: selectcmd
= shared
.select5
; break;
1244 case 6: selectcmd
= shared
.select6
; break;
1245 case 7: selectcmd
= shared
.select7
; break;
1246 case 8: selectcmd
= shared
.select8
; break;
1247 case 9: selectcmd
= shared
.select9
; break;
1249 selectcmd
= createObject(REDIS_STRING
,
1250 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
1251 selectcmd
->refcount
= 0;
1254 addReply(slave
,selectcmd
);
1255 slave
->slaveseldb
= dictid
;
1257 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
1262 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1263 redisClient
*c
= (redisClient
*) privdata
;
1264 char buf
[REDIS_QUERYBUF_LEN
];
1267 REDIS_NOTUSED(mask
);
1269 nread
= read(fd
, buf
, REDIS_QUERYBUF_LEN
);
1271 if (errno
== EAGAIN
) {
1274 redisLog(REDIS_DEBUG
, "Reading from client: %s",strerror(errno
));
1278 } else if (nread
== 0) {
1279 redisLog(REDIS_DEBUG
, "Client closed connection");
1284 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
1285 c
->lastinteraction
= time(NULL
);
1291 if (c
->bulklen
== -1) {
1292 /* Read the first line of the query */
1293 char *p
= strchr(c
->querybuf
,'\n');
1299 query
= c
->querybuf
;
1300 c
->querybuf
= sdsempty();
1301 querylen
= 1+(p
-(query
));
1302 if (sdslen(query
) > querylen
) {
1303 /* leave data after the first line of the query in the buffer */
1304 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
1306 *p
= '\0'; /* remove "\n" */
1307 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
1308 sdsupdatelen(query
);
1310 /* Now we can split the query in arguments */
1311 if (sdslen(query
) == 0) {
1312 /* Ignore empty query */
1316 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
1318 if (argv
== NULL
) oom("sdssplitlen");
1319 for (j
= 0; j
< argc
&& j
< REDIS_MAX_ARGS
; j
++) {
1320 if (sdslen(argv
[j
])) {
1321 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
1328 /* Execute the command. If the client is still valid
1329 * after processCommand() return and there is something
1330 * on the query buffer try to process the next command. */
1331 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
1333 } else if (sdslen(c
->querybuf
) >= 1024) {
1334 redisLog(REDIS_DEBUG
, "Client protocol error");
1339 /* Bulk read handling. Note that if we are at this point
1340 the client already sent a command terminated with a newline,
1341 we are reading the bulk data that is actually the last
1342 argument of the command. */
1343 int qbl
= sdslen(c
->querybuf
);
1345 if (c
->bulklen
<= qbl
) {
1346 /* Copy everything but the final CRLF as final argument */
1347 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
1349 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
1356 static int selectDb(redisClient
*c
, int id
) {
1357 if (id
< 0 || id
>= server
.dbnum
)
1359 c
->db
= &server
.db
[id
];
1363 static redisClient
*createClient(int fd
) {
1364 redisClient
*c
= zmalloc(sizeof(*c
));
1366 anetNonBlock(NULL
,fd
);
1367 anetTcpNoDelay(NULL
,fd
);
1368 if (!c
) return NULL
;
1371 c
->querybuf
= sdsempty();
1376 c
->lastinteraction
= time(NULL
);
1377 c
->authenticated
= 0;
1378 if ((c
->reply
= listCreate()) == NULL
) oom("listCreate");
1379 listSetFreeMethod(c
->reply
,decrRefCount
);
1380 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
1381 readQueryFromClient
, c
, NULL
) == AE_ERR
) {
1385 if (!listAddNodeTail(server
.clients
,c
)) oom("listAddNodeTail");
1389 static void addReply(redisClient
*c
, robj
*obj
) {
1390 if (listLength(c
->reply
) == 0 &&
1391 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
1392 sendReplyToClient
, c
, NULL
) == AE_ERR
) return;
1393 if (!listAddNodeTail(c
->reply
,obj
)) oom("listAddNodeTail");
1397 static void addReplySds(redisClient
*c
, sds s
) {
1398 robj
*o
= createObject(REDIS_STRING
,s
);
1403 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1407 REDIS_NOTUSED(mask
);
1408 REDIS_NOTUSED(privdata
);
1410 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
1411 if (cfd
== AE_ERR
) {
1412 redisLog(REDIS_DEBUG
,"Accepting client connection: %s", server
.neterr
);
1415 redisLog(REDIS_DEBUG
,"Accepted %s:%d", cip
, cport
);
1416 if (createClient(cfd
) == NULL
) {
1417 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
1418 close(cfd
); /* May be already closed, just ingore errors */
1421 server
.stat_numconnections
++;
1424 /* ======================= Redis objects implementation ===================== */
1426 static robj
*createObject(int type
, void *ptr
) {
1429 if (listLength(server
.objfreelist
)) {
1430 listNode
*head
= listFirst(server
.objfreelist
);
1431 o
= listNodeValue(head
);
1432 listDelNode(server
.objfreelist
,head
);
1434 o
= zmalloc(sizeof(*o
));
1436 if (!o
) oom("createObject");
1443 static robj
*createStringObject(char *ptr
, size_t len
) {
1444 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
1447 static robj
*createListObject(void) {
1448 list
*l
= listCreate();
1450 if (!l
) oom("listCreate");
1451 listSetFreeMethod(l
,decrRefCount
);
1452 return createObject(REDIS_LIST
,l
);
1455 static robj
*createSetObject(void) {
1456 dict
*d
= dictCreate(&setDictType
,NULL
);
1457 if (!d
) oom("dictCreate");
1458 return createObject(REDIS_SET
,d
);
1461 static void freeStringObject(robj
*o
) {
1465 static void freeListObject(robj
*o
) {
1466 listRelease((list
*) o
->ptr
);
1469 static void freeSetObject(robj
*o
) {
1470 dictRelease((dict
*) o
->ptr
);
1473 static void freeHashObject(robj
*o
) {
1474 dictRelease((dict
*) o
->ptr
);
1477 static void incrRefCount(robj
*o
) {
1479 #ifdef DEBUG_REFCOUNT
1480 if (o
->type
== REDIS_STRING
)
1481 printf("Increment '%s'(%p), now is: %d\n",o
->ptr
,o
,o
->refcount
);
1485 static void decrRefCount(void *obj
) {
1488 #ifdef DEBUG_REFCOUNT
1489 if (o
->type
== REDIS_STRING
)
1490 printf("Decrement '%s'(%p), now is: %d\n",o
->ptr
,o
,o
->refcount
-1);
1492 if (--(o
->refcount
) == 0) {
1494 case REDIS_STRING
: freeStringObject(o
); break;
1495 case REDIS_LIST
: freeListObject(o
); break;
1496 case REDIS_SET
: freeSetObject(o
); break;
1497 case REDIS_HASH
: freeHashObject(o
); break;
1498 default: assert(0 != 0); break;
1500 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
1501 !listAddNodeHead(server
.objfreelist
,o
))
1506 /* Try to share an object against the shared objects pool */
1507 static robj
*tryObjectSharing(robj
*o
) {
1508 struct dictEntry
*de
;
1511 if (o
== NULL
|| server
.shareobjects
== 0) return o
;
1513 assert(o
->type
== REDIS_STRING
);
1514 de
= dictFind(server
.sharingpool
,o
);
1516 robj
*shared
= dictGetEntryKey(de
);
1518 c
= ((unsigned long) dictGetEntryVal(de
))+1;
1519 dictGetEntryVal(de
) = (void*) c
;
1520 incrRefCount(shared
);
1524 /* Here we are using a stream algorihtm: Every time an object is
1525 * shared we increment its count, everytime there is a miss we
1526 * recrement the counter of a random object. If this object reaches
1527 * zero we remove the object and put the current object instead. */
1528 if (dictSize(server
.sharingpool
) >=
1529 server
.sharingpoolsize
) {
1530 de
= dictGetRandomKey(server
.sharingpool
);
1532 c
= ((unsigned long) dictGetEntryVal(de
))-1;
1533 dictGetEntryVal(de
) = (void*) c
;
1535 dictDelete(server
.sharingpool
,de
->key
);
1538 c
= 0; /* If the pool is empty we want to add this object */
1543 retval
= dictAdd(server
.sharingpool
,o
,(void*)1);
1544 assert(retval
== DICT_OK
);
1551 static robj
*lookupKey(redisDb
*db
, robj
*key
) {
1552 dictEntry
*de
= dictFind(db
->dict
,key
);
1553 return de
? dictGetEntryVal(de
) : NULL
;
1556 static robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
1557 expireIfNeeded(db
,key
);
1558 return lookupKey(db
,key
);
1561 static robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
1562 deleteIfVolatile(db
,key
);
1563 return lookupKey(db
,key
);
1566 static int deleteKey(redisDb
*db
, robj
*key
) {
1569 /* We need to protect key from destruction: after the first dictDelete()
1570 * it may happen that 'key' is no longer valid if we don't increment
1571 * it's count. This may happen when we get the object reference directly
1572 * from the hash table with dictRandomKey() or dict iterators */
1574 if (dictSize(db
->expires
)) dictDelete(db
->expires
,key
);
1575 retval
= dictDelete(db
->dict
,key
);
1578 return retval
== DICT_OK
;
1581 /*============================ DB saving/loading ============================ */
1583 static int rdbSaveType(FILE *fp
, unsigned char type
) {
1584 if (fwrite(&type
,1,1,fp
) == 0) return -1;
1588 /* check rdbLoadLen() comments for more info */
1589 static int rdbSaveLen(FILE *fp
, uint32_t len
) {
1590 unsigned char buf
[2];
1593 /* Save a 6 bit len */
1594 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
1595 if (fwrite(buf
,1,1,fp
) == 0) return -1;
1596 } else if (len
< (1<<14)) {
1597 /* Save a 14 bit len */
1598 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
1600 if (fwrite(buf
,2,1,fp
) == 0) return -1;
1602 /* Save a 32 bit len */
1603 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
1604 if (fwrite(buf
,1,1,fp
) == 0) return -1;
1606 if (fwrite(&len
,4,1,fp
) == 0) return -1;
1611 /* String objects in the form "2391" "-100" without any space and with a
1612 * range of values that can fit in an 8, 16 or 32 bit signed value can be
1613 * encoded as integers to save space */
1614 int rdbTryIntegerEncoding(sds s
, unsigned char *enc
) {
1616 char *endptr
, buf
[32];
1618 /* Check if it's possible to encode this value as a number */
1619 value
= strtoll(s
, &endptr
, 10);
1620 if (endptr
[0] != '\0') return 0;
1621 snprintf(buf
,32,"%lld",value
);
1623 /* If the number converted back into a string is not identical
1624 * then it's not possible to encode the string as integer */
1625 if (strlen(buf
) != sdslen(s
) || memcmp(buf
,s
,sdslen(s
))) return 0;
1627 /* Finally check if it fits in our ranges */
1628 if (value
>= -(1<<7) && value
<= (1<<7)-1) {
1629 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT8
;
1630 enc
[1] = value
&0xFF;
1632 } else if (value
>= -(1<<15) && value
<= (1<<15)-1) {
1633 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
;
1634 enc
[1] = value
&0xFF;
1635 enc
[2] = (value
>>8)&0xFF;
1637 } else if (value
>= -((long long)1<<31) && value
<= ((long long)1<<31)-1) {
1638 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT32
;
1639 enc
[1] = value
&0xFF;
1640 enc
[2] = (value
>>8)&0xFF;
1641 enc
[3] = (value
>>16)&0xFF;
1642 enc
[4] = (value
>>24)&0xFF;
1649 static int rdbSaveLzfStringObject(FILE *fp
, robj
*obj
) {
1650 unsigned int comprlen
, outlen
;
1654 /* We require at least four bytes compression for this to be worth it */
1655 outlen
= sdslen(obj
->ptr
)-4;
1656 if (outlen
<= 0) return 0;
1657 if ((out
= zmalloc(outlen
)) == NULL
) return 0;
1658 comprlen
= lzf_compress(obj
->ptr
, sdslen(obj
->ptr
), out
, outlen
);
1659 if (comprlen
== 0) {
1663 /* Data compressed! Let's save it on disk */
1664 byte
= (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_LZF
;
1665 if (fwrite(&byte
,1,1,fp
) == 0) goto writeerr
;
1666 if (rdbSaveLen(fp
,comprlen
) == -1) goto writeerr
;
1667 if (rdbSaveLen(fp
,sdslen(obj
->ptr
)) == -1) goto writeerr
;
1668 if (fwrite(out
,comprlen
,1,fp
) == 0) goto writeerr
;
1677 /* Save a string objet as [len][data] on disk. If the object is a string
1678 * representation of an integer value we try to safe it in a special form */
1679 static int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
1680 size_t len
= sdslen(obj
->ptr
);
1683 /* Try integer encoding */
1685 unsigned char buf
[5];
1686 if ((enclen
= rdbTryIntegerEncoding(obj
->ptr
,buf
)) > 0) {
1687 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
1692 /* Try LZF compression - under 20 bytes it's unable to compress even
1693 * aaaaaaaaaaaaaaaaaa so to try is just useful to make the CPU hot */
1697 retval
= rdbSaveLzfStringObject(fp
,obj
);
1698 if (retval
== -1) return -1;
1699 if (retval
> 0) return 0;
1700 /* retval == 0 means data can't be compressed, save the old way */
1703 /* Store verbatim */
1704 if (rdbSaveLen(fp
,len
) == -1) return -1;
1705 if (len
&& fwrite(obj
->ptr
,len
,1,fp
) == 0) return -1;
1709 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
1710 static int rdbSave(char *filename
) {
1711 dictIterator
*di
= NULL
;
1717 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
1718 fp
= fopen(tmpfile
,"w");
1720 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
1723 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
1724 for (j
= 0; j
< server
.dbnum
; j
++) {
1725 dict
*d
= server
.db
[j
].dict
;
1726 if (dictSize(d
) == 0) continue;
1727 di
= dictGetIterator(d
);
1733 /* Write the SELECT DB opcode */
1734 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
1735 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
1737 /* Iterate this DB writing every entry */
1738 while((de
= dictNext(di
)) != NULL
) {
1739 robj
*key
= dictGetEntryKey(de
);
1740 robj
*o
= dictGetEntryVal(de
);
1742 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
1743 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
1744 if (o
->type
== REDIS_STRING
) {
1745 /* Save a string value */
1746 if (rdbSaveStringObject(fp
,o
) == -1) goto werr
;
1747 } else if (o
->type
== REDIS_LIST
) {
1748 /* Save a list value */
1749 list
*list
= o
->ptr
;
1750 listNode
*ln
= list
->head
;
1752 if (rdbSaveLen(fp
,listLength(list
)) == -1) goto werr
;
1754 robj
*eleobj
= listNodeValue(ln
);
1756 if (rdbSaveStringObject(fp
,eleobj
) == -1) goto werr
;
1759 } else if (o
->type
== REDIS_SET
) {
1760 /* Save a set value */
1762 dictIterator
*di
= dictGetIterator(set
);
1765 if (!set
) oom("dictGetIteraotr");
1766 if (rdbSaveLen(fp
,dictSize(set
)) == -1) goto werr
;
1767 while((de
= dictNext(di
)) != NULL
) {
1768 robj
*eleobj
= dictGetEntryKey(de
);
1770 if (rdbSaveStringObject(fp
,eleobj
) == -1) goto werr
;
1772 dictReleaseIterator(di
);
1777 dictReleaseIterator(di
);
1780 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
1782 /* Make sure data will not remain on the OS's output buffers */
1787 /* Use RENAME to make sure the DB file is changed atomically only
1788 * if the generate DB file is ok. */
1789 if (rename(tmpfile
,filename
) == -1) {
1790 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destionation: %s", strerror(errno
));
1794 redisLog(REDIS_NOTICE
,"DB saved on disk");
1796 server
.lastsave
= time(NULL
);
1802 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
1803 if (di
) dictReleaseIterator(di
);
1807 static int rdbSaveBackground(char *filename
) {
1810 if (server
.bgsaveinprogress
) return REDIS_ERR
;
1811 if ((childpid
= fork()) == 0) {
1814 if (rdbSave(filename
) == REDIS_OK
) {
1821 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
1822 server
.bgsaveinprogress
= 1;
1825 return REDIS_OK
; /* unreached */
1828 static int rdbLoadType(FILE *fp
) {
1830 if (fread(&type
,1,1,fp
) == 0) return -1;
1834 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
1835 * of this file for a description of how this are stored on disk.
1837 * isencoded is set to 1 if the readed length is not actually a length but
1838 * an "encoding type", check the above comments for more info */
1839 static uint32_t rdbLoadLen(FILE *fp
, int rdbver
, int *isencoded
) {
1840 unsigned char buf
[2];
1843 if (isencoded
) *isencoded
= 0;
1845 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
1850 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
1851 type
= (buf
[0]&0xC0)>>6;
1852 if (type
== REDIS_RDB_6BITLEN
) {
1853 /* Read a 6 bit len */
1855 } else if (type
== REDIS_RDB_ENCVAL
) {
1856 /* Read a 6 bit len encoding type */
1857 if (isencoded
) *isencoded
= 1;
1859 } else if (type
== REDIS_RDB_14BITLEN
) {
1860 /* Read a 14 bit len */
1861 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
1862 return ((buf
[0]&0x3F)<<8)|buf
[1];
1864 /* Read a 32 bit len */
1865 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
1871 static robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
) {
1872 unsigned char enc
[4];
1875 if (enctype
== REDIS_RDB_ENC_INT8
) {
1876 if (fread(enc
,1,1,fp
) == 0) return NULL
;
1877 val
= (signed char)enc
[0];
1878 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
1880 if (fread(enc
,2,1,fp
) == 0) return NULL
;
1881 v
= enc
[0]|(enc
[1]<<8);
1883 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
1885 if (fread(enc
,4,1,fp
) == 0) return NULL
;
1886 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
1889 val
= 0; /* anti-warning */
1892 return createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",val
));
1895 static robj
*rdbLoadStringObject(FILE*fp
, int rdbver
) {
1900 len
= rdbLoadLen(fp
,rdbver
,&isencoded
);
1903 case REDIS_RDB_ENC_INT8
:
1904 case REDIS_RDB_ENC_INT16
:
1905 case REDIS_RDB_ENC_INT32
:
1906 return tryObjectSharing(rdbLoadIntegerObject(fp
,len
));
1912 if (len
== REDIS_RDB_LENERR
) return NULL
;
1913 val
= sdsnewlen(NULL
,len
);
1914 if (len
&& fread(val
,len
,1,fp
) == 0) {
1918 return tryObjectSharing(createObject(REDIS_STRING
,val
));
1921 static int rdbLoad(char *filename
) {
1923 robj
*keyobj
= NULL
;
1927 dict
*d
= server
.db
[0].dict
;
1930 fp
= fopen(filename
,"r");
1931 if (!fp
) return REDIS_ERR
;
1932 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
1934 if (memcmp(buf
,"REDIS",5) != 0) {
1936 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
1939 rdbver
= atoi(buf
+5);
1942 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
1949 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
1950 if (type
== REDIS_EOF
) break;
1951 /* Handle SELECT DB opcode as a special case */
1952 if (type
== REDIS_SELECTDB
) {
1953 if ((dbid
= rdbLoadLen(fp
,rdbver
,NULL
)) == REDIS_RDB_LENERR
)
1955 if (dbid
>= (unsigned)server
.dbnum
) {
1956 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
1959 d
= server
.db
[dbid
].dict
;
1963 if ((keyobj
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
1965 if (type
== REDIS_STRING
) {
1966 /* Read string value */
1967 if ((o
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
1968 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
1969 /* Read list/set value */
1972 if ((listlen
= rdbLoadLen(fp
,rdbver
,NULL
)) == REDIS_RDB_LENERR
)
1974 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
1975 /* Load every single element of the list/set */
1979 if ((ele
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
1980 if (type
== REDIS_LIST
) {
1981 if (!listAddNodeTail((list
*)o
->ptr
,ele
))
1982 oom("listAddNodeTail");
1984 if (dictAdd((dict
*)o
->ptr
,ele
,NULL
) == DICT_ERR
)
1991 /* Add the new object in the hash table */
1992 retval
= dictAdd(d
,keyobj
,o
);
1993 if (retval
== DICT_ERR
) {
1994 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj
->ptr
);
2002 eoferr
: /* unexpected end of file is handled here with a fatal exit */
2003 if (keyobj
) decrRefCount(keyobj
);
2004 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, exiting now.");
2006 return REDIS_ERR
; /* Just to avoid warning */
2009 /*================================== Commands =============================== */
2011 static void authCommand(redisClient
*c
) {
2012 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
2013 c
->authenticated
= 1;
2014 addReply(c
,shared
.ok
);
2016 c
->authenticated
= 0;
2017 addReply(c
,shared
.err
);
2021 static void pingCommand(redisClient
*c
) {
2022 addReply(c
,shared
.pong
);
2025 static void echoCommand(redisClient
*c
) {
2026 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
2027 (int)sdslen(c
->argv
[1]->ptr
)));
2028 addReply(c
,c
->argv
[1]);
2029 addReply(c
,shared
.crlf
);
2032 /*=================================== Strings =============================== */
2034 static void setGenericCommand(redisClient
*c
, int nx
) {
2037 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
2038 if (retval
== DICT_ERR
) {
2040 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
2041 incrRefCount(c
->argv
[2]);
2043 addReply(c
,shared
.czero
);
2047 incrRefCount(c
->argv
[1]);
2048 incrRefCount(c
->argv
[2]);
2051 removeExpire(c
->db
,c
->argv
[1]);
2052 addReply(c
, nx
? shared
.cone
: shared
.ok
);
2055 static void setCommand(redisClient
*c
) {
2056 setGenericCommand(c
,0);
2059 static void setnxCommand(redisClient
*c
) {
2060 setGenericCommand(c
,1);
2063 static void getCommand(redisClient
*c
) {
2064 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[1]);
2067 addReply(c
,shared
.nullbulk
);
2069 if (o
->type
!= REDIS_STRING
) {
2070 addReply(c
,shared
.wrongtypeerr
);
2072 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(o
->ptr
)));
2074 addReply(c
,shared
.crlf
);
2079 static void mgetCommand(redisClient
*c
) {
2082 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
2083 for (j
= 1; j
< c
->argc
; j
++) {
2084 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[j
]);
2086 addReply(c
,shared
.nullbulk
);
2088 if (o
->type
!= REDIS_STRING
) {
2089 addReply(c
,shared
.nullbulk
);
2091 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(o
->ptr
)));
2093 addReply(c
,shared
.crlf
);
2099 static void incrDecrCommand(redisClient
*c
, int incr
) {
2104 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2108 if (o
->type
!= REDIS_STRING
) {
2113 value
= strtoll(o
->ptr
, &eptr
, 10);
2118 o
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
));
2119 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],o
);
2120 if (retval
== DICT_ERR
) {
2121 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
2122 removeExpire(c
->db
,c
->argv
[1]);
2124 incrRefCount(c
->argv
[1]);
2127 addReply(c
,shared
.colon
);
2129 addReply(c
,shared
.crlf
);
2132 static void incrCommand(redisClient
*c
) {
2133 incrDecrCommand(c
,1);
2136 static void decrCommand(redisClient
*c
) {
2137 incrDecrCommand(c
,-1);
2140 static void incrbyCommand(redisClient
*c
) {
2141 int incr
= atoi(c
->argv
[2]->ptr
);
2142 incrDecrCommand(c
,incr
);
2145 static void decrbyCommand(redisClient
*c
) {
2146 int incr
= atoi(c
->argv
[2]->ptr
);
2147 incrDecrCommand(c
,-incr
);
2150 /* ========================= Type agnostic commands ========================= */
2152 static void delCommand(redisClient
*c
) {
2153 if (deleteKey(c
->db
,c
->argv
[1])) {
2155 addReply(c
,shared
.cone
);
2157 addReply(c
,shared
.czero
);
2161 static void existsCommand(redisClient
*c
) {
2162 addReply(c
,lookupKeyRead(c
->db
,c
->argv
[1]) ? shared
.cone
: shared
.czero
);
2165 static void selectCommand(redisClient
*c
) {
2166 int id
= atoi(c
->argv
[1]->ptr
);
2168 if (selectDb(c
,id
) == REDIS_ERR
) {
2169 addReplySds(c
,sdsnew("-ERR invalid DB index\r\n"));
2171 addReply(c
,shared
.ok
);
2175 static void randomkeyCommand(redisClient
*c
) {
2179 de
= dictGetRandomKey(c
->db
->dict
);
2180 if (expireIfNeeded(c
->db
,dictGetEntryKey(de
)) == 0) break;
2183 addReply(c
,shared
.crlf
);
2185 addReply(c
,shared
.plus
);
2186 addReply(c
,dictGetEntryKey(de
));
2187 addReply(c
,shared
.crlf
);
2191 static void keysCommand(redisClient
*c
) {
2194 sds pattern
= c
->argv
[1]->ptr
;
2195 int plen
= sdslen(pattern
);
2196 int numkeys
= 0, keyslen
= 0;
2197 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
2199 di
= dictGetIterator(c
->db
->dict
);
2200 if (!di
) oom("dictGetIterator");
2202 decrRefCount(lenobj
);
2203 while((de
= dictNext(di
)) != NULL
) {
2204 robj
*keyobj
= dictGetEntryKey(de
);
2206 sds key
= keyobj
->ptr
;
2207 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
2208 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
2209 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
2211 addReply(c
,shared
.space
);
2214 keyslen
+= sdslen(key
);
2218 dictReleaseIterator(di
);
2219 lenobj
->ptr
= sdscatprintf(sdsempty(),"$%lu\r\n",keyslen
+(numkeys
? (numkeys
-1) : 0));
2220 addReply(c
,shared
.crlf
);
2223 static void dbsizeCommand(redisClient
*c
) {
2225 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c
->db
->dict
)));
2228 static void lastsaveCommand(redisClient
*c
) {
2230 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
2233 static void typeCommand(redisClient
*c
) {
2237 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
2242 case REDIS_STRING
: type
= "+string"; break;
2243 case REDIS_LIST
: type
= "+list"; break;
2244 case REDIS_SET
: type
= "+set"; break;
2245 default: type
= "unknown"; break;
2248 addReplySds(c
,sdsnew(type
));
2249 addReply(c
,shared
.crlf
);
2252 static void saveCommand(redisClient
*c
) {
2253 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
2254 addReply(c
,shared
.ok
);
2256 addReply(c
,shared
.err
);
2260 static void bgsaveCommand(redisClient
*c
) {
2261 if (server
.bgsaveinprogress
) {
2262 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
2265 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
2266 addReply(c
,shared
.ok
);
2268 addReply(c
,shared
.err
);
2272 static void shutdownCommand(redisClient
*c
) {
2273 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
2274 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
2275 if (server
.daemonize
) {
2276 unlink(server
.pidfile
);
2278 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
2281 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
2282 addReplySds(c
,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
2286 static void renameGenericCommand(redisClient
*c
, int nx
) {
2289 /* To use the same key as src and dst is probably an error */
2290 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
2291 addReply(c
,shared
.sameobjecterr
);
2295 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2297 addReply(c
,shared
.nokeyerr
);
2301 deleteIfVolatile(c
->db
,c
->argv
[2]);
2302 if (dictAdd(c
->db
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
2305 addReply(c
,shared
.czero
);
2308 dictReplace(c
->db
->dict
,c
->argv
[2],o
);
2310 incrRefCount(c
->argv
[2]);
2312 deleteKey(c
->db
,c
->argv
[1]);
2314 addReply(c
,nx
? shared
.cone
: shared
.ok
);
2317 static void renameCommand(redisClient
*c
) {
2318 renameGenericCommand(c
,0);
2321 static void renamenxCommand(redisClient
*c
) {
2322 renameGenericCommand(c
,1);
2325 static void moveCommand(redisClient
*c
) {
2330 /* Obtain source and target DB pointers */
2333 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
2334 addReply(c
,shared
.outofrangeerr
);
2338 selectDb(c
,srcid
); /* Back to the source DB */
2340 /* If the user is moving using as target the same
2341 * DB as the source DB it is probably an error. */
2343 addReply(c
,shared
.sameobjecterr
);
2347 /* Check if the element exists and get a reference */
2348 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2350 addReply(c
,shared
.czero
);
2354 /* Try to add the element to the target DB */
2355 deleteIfVolatile(dst
,c
->argv
[1]);
2356 if (dictAdd(dst
->dict
,c
->argv
[1],o
) == DICT_ERR
) {
2357 addReply(c
,shared
.czero
);
2360 incrRefCount(c
->argv
[1]);
2363 /* OK! key moved, free the entry in the source DB */
2364 deleteKey(src
,c
->argv
[1]);
2366 addReply(c
,shared
.cone
);
2369 /* =================================== Lists ================================ */
2370 static void pushGenericCommand(redisClient
*c
, int where
) {
2374 lobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2376 lobj
= createListObject();
2378 if (where
== REDIS_HEAD
) {
2379 if (!listAddNodeHead(list
,c
->argv
[2])) oom("listAddNodeHead");
2381 if (!listAddNodeTail(list
,c
->argv
[2])) oom("listAddNodeTail");
2383 dictAdd(c
->db
->dict
,c
->argv
[1],lobj
);
2384 incrRefCount(c
->argv
[1]);
2385 incrRefCount(c
->argv
[2]);
2387 if (lobj
->type
!= REDIS_LIST
) {
2388 addReply(c
,shared
.wrongtypeerr
);
2392 if (where
== REDIS_HEAD
) {
2393 if (!listAddNodeHead(list
,c
->argv
[2])) oom("listAddNodeHead");
2395 if (!listAddNodeTail(list
,c
->argv
[2])) oom("listAddNodeTail");
2397 incrRefCount(c
->argv
[2]);
2400 addReply(c
,shared
.ok
);
2403 static void lpushCommand(redisClient
*c
) {
2404 pushGenericCommand(c
,REDIS_HEAD
);
2407 static void rpushCommand(redisClient
*c
) {
2408 pushGenericCommand(c
,REDIS_TAIL
);
2411 static void llenCommand(redisClient
*c
) {
2415 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
2417 addReply(c
,shared
.czero
);
2420 if (o
->type
!= REDIS_LIST
) {
2421 addReply(c
,shared
.wrongtypeerr
);
2424 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(l
)));
2429 static void lindexCommand(redisClient
*c
) {
2431 int index
= atoi(c
->argv
[2]->ptr
);
2433 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
2435 addReply(c
,shared
.nullbulk
);
2437 if (o
->type
!= REDIS_LIST
) {
2438 addReply(c
,shared
.wrongtypeerr
);
2440 list
*list
= o
->ptr
;
2443 ln
= listIndex(list
, index
);
2445 addReply(c
,shared
.nullbulk
);
2447 robj
*ele
= listNodeValue(ln
);
2448 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2450 addReply(c
,shared
.crlf
);
2456 static void lsetCommand(redisClient
*c
) {
2458 int index
= atoi(c
->argv
[2]->ptr
);
2460 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2462 addReply(c
,shared
.nokeyerr
);
2464 if (o
->type
!= REDIS_LIST
) {
2465 addReply(c
,shared
.wrongtypeerr
);
2467 list
*list
= o
->ptr
;
2470 ln
= listIndex(list
, index
);
2472 addReply(c
,shared
.outofrangeerr
);
2474 robj
*ele
= listNodeValue(ln
);
2477 listNodeValue(ln
) = c
->argv
[3];
2478 incrRefCount(c
->argv
[3]);
2479 addReply(c
,shared
.ok
);
2486 static void popGenericCommand(redisClient
*c
, int where
) {
2489 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2491 addReply(c
,shared
.nullbulk
);
2493 if (o
->type
!= REDIS_LIST
) {
2494 addReply(c
,shared
.wrongtypeerr
);
2496 list
*list
= o
->ptr
;
2499 if (where
== REDIS_HEAD
)
2500 ln
= listFirst(list
);
2502 ln
= listLast(list
);
2505 addReply(c
,shared
.nullbulk
);
2507 robj
*ele
= listNodeValue(ln
);
2508 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2510 addReply(c
,shared
.crlf
);
2511 listDelNode(list
,ln
);
2518 static void lpopCommand(redisClient
*c
) {
2519 popGenericCommand(c
,REDIS_HEAD
);
2522 static void rpopCommand(redisClient
*c
) {
2523 popGenericCommand(c
,REDIS_TAIL
);
2526 static void lrangeCommand(redisClient
*c
) {
2528 int start
= atoi(c
->argv
[2]->ptr
);
2529 int end
= atoi(c
->argv
[3]->ptr
);
2531 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
2533 addReply(c
,shared
.nullmultibulk
);
2535 if (o
->type
!= REDIS_LIST
) {
2536 addReply(c
,shared
.wrongtypeerr
);
2538 list
*list
= o
->ptr
;
2540 int llen
= listLength(list
);
2544 /* convert negative indexes */
2545 if (start
< 0) start
= llen
+start
;
2546 if (end
< 0) end
= llen
+end
;
2547 if (start
< 0) start
= 0;
2548 if (end
< 0) end
= 0;
2550 /* indexes sanity checks */
2551 if (start
> end
|| start
>= llen
) {
2552 /* Out of range start or start > end result in empty list */
2553 addReply(c
,shared
.emptymultibulk
);
2556 if (end
>= llen
) end
= llen
-1;
2557 rangelen
= (end
-start
)+1;
2559 /* Return the result in form of a multi-bulk reply */
2560 ln
= listIndex(list
, start
);
2561 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
2562 for (j
= 0; j
< rangelen
; j
++) {
2563 ele
= listNodeValue(ln
);
2564 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2566 addReply(c
,shared
.crlf
);
2573 static void ltrimCommand(redisClient
*c
) {
2575 int start
= atoi(c
->argv
[2]->ptr
);
2576 int end
= atoi(c
->argv
[3]->ptr
);
2578 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2580 addReply(c
,shared
.nokeyerr
);
2582 if (o
->type
!= REDIS_LIST
) {
2583 addReply(c
,shared
.wrongtypeerr
);
2585 list
*list
= o
->ptr
;
2587 int llen
= listLength(list
);
2588 int j
, ltrim
, rtrim
;
2590 /* convert negative indexes */
2591 if (start
< 0) start
= llen
+start
;
2592 if (end
< 0) end
= llen
+end
;
2593 if (start
< 0) start
= 0;
2594 if (end
< 0) end
= 0;
2596 /* indexes sanity checks */
2597 if (start
> end
|| start
>= llen
) {
2598 /* Out of range start or start > end result in empty list */
2602 if (end
>= llen
) end
= llen
-1;
2607 /* Remove list elements to perform the trim */
2608 for (j
= 0; j
< ltrim
; j
++) {
2609 ln
= listFirst(list
);
2610 listDelNode(list
,ln
);
2612 for (j
= 0; j
< rtrim
; j
++) {
2613 ln
= listLast(list
);
2614 listDelNode(list
,ln
);
2616 addReply(c
,shared
.ok
);
2622 static void lremCommand(redisClient
*c
) {
2625 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2627 addReply(c
,shared
.nokeyerr
);
2629 if (o
->type
!= REDIS_LIST
) {
2630 addReply(c
,shared
.wrongtypeerr
);
2632 list
*list
= o
->ptr
;
2633 listNode
*ln
, *next
;
2634 int toremove
= atoi(c
->argv
[2]->ptr
);
2639 toremove
= -toremove
;
2642 ln
= fromtail
? list
->tail
: list
->head
;
2644 robj
*ele
= listNodeValue(ln
);
2646 next
= fromtail
? ln
->prev
: ln
->next
;
2647 if (sdscmp(ele
->ptr
,c
->argv
[3]->ptr
) == 0) {
2648 listDelNode(list
,ln
);
2651 if (toremove
&& removed
== toremove
) break;
2655 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
2660 /* ==================================== Sets ================================ */
2662 static void saddCommand(redisClient
*c
) {
2665 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2667 set
= createSetObject();
2668 dictAdd(c
->db
->dict
,c
->argv
[1],set
);
2669 incrRefCount(c
->argv
[1]);
2671 if (set
->type
!= REDIS_SET
) {
2672 addReply(c
,shared
.wrongtypeerr
);
2676 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
2677 incrRefCount(c
->argv
[2]);
2679 addReply(c
,shared
.cone
);
2681 addReply(c
,shared
.czero
);
2685 static void sremCommand(redisClient
*c
) {
2688 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2690 addReply(c
,shared
.czero
);
2692 if (set
->type
!= REDIS_SET
) {
2693 addReply(c
,shared
.wrongtypeerr
);
2696 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
2698 addReply(c
,shared
.cone
);
2700 addReply(c
,shared
.czero
);
2705 static void sismemberCommand(redisClient
*c
) {
2708 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
2710 addReply(c
,shared
.czero
);
2712 if (set
->type
!= REDIS_SET
) {
2713 addReply(c
,shared
.wrongtypeerr
);
2716 if (dictFind(set
->ptr
,c
->argv
[2]))
2717 addReply(c
,shared
.cone
);
2719 addReply(c
,shared
.czero
);
2723 static void scardCommand(redisClient
*c
) {
2727 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
2729 addReply(c
,shared
.czero
);
2732 if (o
->type
!= REDIS_SET
) {
2733 addReply(c
,shared
.wrongtypeerr
);
2736 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",
2742 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
2743 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
2745 return dictSize(*d1
)-dictSize(*d2
);
2748 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
) {
2749 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
2752 robj
*lenobj
= NULL
, *dstset
= NULL
;
2753 int j
, cardinality
= 0;
2755 if (!dv
) oom("sinterCommand");
2756 for (j
= 0; j
< setsnum
; j
++) {
2760 lookupKeyWrite(c
->db
,setskeys
[j
]) :
2761 lookupKeyRead(c
->db
,setskeys
[j
]);
2764 addReply(c
,shared
.nokeyerr
);
2767 if (setobj
->type
!= REDIS_SET
) {
2769 addReply(c
,shared
.wrongtypeerr
);
2772 dv
[j
] = setobj
->ptr
;
2774 /* Sort sets from the smallest to largest, this will improve our
2775 * algorithm's performace */
2776 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
2778 /* The first thing we should output is the total number of elements...
2779 * since this is a multi-bulk write, but at this stage we don't know
2780 * the intersection set size, so we use a trick, append an empty object
2781 * to the output list and save the pointer to later modify it with the
2784 lenobj
= createObject(REDIS_STRING
,NULL
);
2786 decrRefCount(lenobj
);
2788 /* If we have a target key where to store the resulting set
2789 * create this key with an empty set inside */
2790 dstset
= createSetObject();
2791 deleteKey(c
->db
,dstkey
);
2792 dictAdd(c
->db
->dict
,dstkey
,dstset
);
2793 incrRefCount(dstkey
);
2796 /* Iterate all the elements of the first (smallest) set, and test
2797 * the element against all the other sets, if at least one set does
2798 * not include the element it is discarded */
2799 di
= dictGetIterator(dv
[0]);
2800 if (!di
) oom("dictGetIterator");
2802 while((de
= dictNext(di
)) != NULL
) {
2805 for (j
= 1; j
< setsnum
; j
++)
2806 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
2808 continue; /* at least one set does not contain the member */
2809 ele
= dictGetEntryKey(de
);
2811 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",sdslen(ele
->ptr
)));
2813 addReply(c
,shared
.crlf
);
2816 dictAdd(dstset
->ptr
,ele
,NULL
);
2820 dictReleaseIterator(di
);
2823 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%d\r\n",cardinality
);
2825 addReply(c
,shared
.ok
);
2829 static void sinterCommand(redisClient
*c
) {
2830 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
2833 static void sinterstoreCommand(redisClient
*c
) {
2834 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
2837 static void flushdbCommand(redisClient
*c
) {
2838 dictEmpty(c
->db
->dict
);
2839 dictEmpty(c
->db
->expires
);
2840 addReply(c
,shared
.ok
);
2841 rdbSave(server
.dbfilename
);
2844 static void flushallCommand(redisClient
*c
) {
2846 addReply(c
,shared
.ok
);
2847 rdbSave(server
.dbfilename
);
2850 redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
2851 redisSortOperation
*so
= zmalloc(sizeof(*so
));
2852 if (!so
) oom("createSortOperation");
2854 so
->pattern
= pattern
;
2858 /* Return the value associated to the key with a name obtained
2859 * substituting the first occurence of '*' in 'pattern' with 'subst' */
2860 robj
*lookupKeyByPattern(redisDb
*db
, robj
*pattern
, robj
*subst
) {
2864 int prefixlen
, sublen
, postfixlen
;
2865 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
2869 char buf
[REDIS_SORTKEY_MAX
+1];
2872 spat
= pattern
->ptr
;
2874 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
2875 p
= strchr(spat
,'*');
2876 if (!p
) return NULL
;
2879 sublen
= sdslen(ssub
);
2880 postfixlen
= sdslen(spat
)-(prefixlen
+1);
2881 memcpy(keyname
.buf
,spat
,prefixlen
);
2882 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
2883 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
2884 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
2885 keyname
.len
= prefixlen
+sublen
+postfixlen
;
2887 keyobj
.refcount
= 1;
2888 keyobj
.type
= REDIS_STRING
;
2889 keyobj
.ptr
= ((char*)&keyname
)+(sizeof(long)*2);
2891 /* printf("lookup '%s' => %p\n", keyname.buf,de); */
2892 return lookupKeyRead(db
,&keyobj
);
2895 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
2896 * the additional parameter is not standard but a BSD-specific we have to
2897 * pass sorting parameters via the global 'server' structure */
2898 static int sortCompare(const void *s1
, const void *s2
) {
2899 const redisSortObject
*so1
= s1
, *so2
= s2
;
2902 if (!server
.sort_alpha
) {
2903 /* Numeric sorting. Here it's trivial as we precomputed scores */
2904 if (so1
->u
.score
> so2
->u
.score
) {
2906 } else if (so1
->u
.score
< so2
->u
.score
) {
2912 /* Alphanumeric sorting */
2913 if (server
.sort_bypattern
) {
2914 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
2915 /* At least one compare object is NULL */
2916 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
2918 else if (so1
->u
.cmpobj
== NULL
)
2923 /* We have both the objects, use strcoll */
2924 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
2927 /* Compare elements directly */
2928 cmp
= strcoll(so1
->obj
->ptr
,so2
->obj
->ptr
);
2931 return server
.sort_desc
? -cmp
: cmp
;
2934 /* The SORT command is the most complex command in Redis. Warning: this code
2935 * is optimized for speed and a bit less for readability */
2936 static void sortCommand(redisClient
*c
) {
2939 int desc
= 0, alpha
= 0;
2940 int limit_start
= 0, limit_count
= -1, start
, end
;
2941 int j
, dontsort
= 0, vectorlen
;
2942 int getop
= 0; /* GET operation counter */
2943 robj
*sortval
, *sortby
= NULL
;
2944 redisSortObject
*vector
; /* Resulting vector to sort */
2946 /* Lookup the key to sort. It must be of the right types */
2947 sortval
= lookupKeyRead(c
->db
,c
->argv
[1]);
2948 if (sortval
== NULL
) {
2949 addReply(c
,shared
.nokeyerr
);
2952 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
) {
2953 addReply(c
,shared
.wrongtypeerr
);
2957 /* Create a list of operations to perform for every sorted element.
2958 * Operations can be GET/DEL/INCR/DECR */
2959 operations
= listCreate();
2960 listSetFreeMethod(operations
,zfree
);
2963 /* Now we need to protect sortval incrementing its count, in the future
2964 * SORT may have options able to overwrite/delete keys during the sorting
2965 * and the sorted key itself may get destroied */
2966 incrRefCount(sortval
);
2968 /* The SORT command has an SQL-alike syntax, parse it */
2969 while(j
< c
->argc
) {
2970 int leftargs
= c
->argc
-j
-1;
2971 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
2973 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
2975 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
2977 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
2978 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
2979 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
2981 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
2982 sortby
= c
->argv
[j
+1];
2983 /* If the BY pattern does not contain '*', i.e. it is constant,
2984 * we don't need to sort nor to lookup the weight keys. */
2985 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
2987 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
2988 listAddNodeTail(operations
,createSortOperation(
2989 REDIS_SORT_GET
,c
->argv
[j
+1]));
2992 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"del") && leftargs
>= 1) {
2993 listAddNodeTail(operations
,createSortOperation(
2994 REDIS_SORT_DEL
,c
->argv
[j
+1]));
2996 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"incr") && leftargs
>= 1) {
2997 listAddNodeTail(operations
,createSortOperation(
2998 REDIS_SORT_INCR
,c
->argv
[j
+1]));
3000 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
3001 listAddNodeTail(operations
,createSortOperation(
3002 REDIS_SORT_DECR
,c
->argv
[j
+1]));
3005 decrRefCount(sortval
);
3006 listRelease(operations
);
3007 addReply(c
,shared
.syntaxerr
);
3013 /* Load the sorting vector with all the objects to sort */
3014 vectorlen
= (sortval
->type
== REDIS_LIST
) ?
3015 listLength((list
*)sortval
->ptr
) :
3016 dictSize((dict
*)sortval
->ptr
);
3017 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
3018 if (!vector
) oom("allocating objects vector for SORT");
3020 if (sortval
->type
== REDIS_LIST
) {
3021 list
*list
= sortval
->ptr
;
3022 listNode
*ln
= list
->head
;
3024 robj
*ele
= ln
->value
;
3025 vector
[j
].obj
= ele
;
3026 vector
[j
].u
.score
= 0;
3027 vector
[j
].u
.cmpobj
= NULL
;
3032 dict
*set
= sortval
->ptr
;
3036 di
= dictGetIterator(set
);
3037 if (!di
) oom("dictGetIterator");
3038 while((setele
= dictNext(di
)) != NULL
) {
3039 vector
[j
].obj
= dictGetEntryKey(setele
);
3040 vector
[j
].u
.score
= 0;
3041 vector
[j
].u
.cmpobj
= NULL
;
3044 dictReleaseIterator(di
);
3046 assert(j
== vectorlen
);
3048 /* Now it's time to load the right scores in the sorting vector */
3049 if (dontsort
== 0) {
3050 for (j
= 0; j
< vectorlen
; j
++) {
3054 byval
= lookupKeyByPattern(c
->db
,sortby
,vector
[j
].obj
);
3055 if (!byval
|| byval
->type
!= REDIS_STRING
) continue;
3057 vector
[j
].u
.cmpobj
= byval
;
3058 incrRefCount(byval
);
3060 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
3063 if (!alpha
) vector
[j
].u
.score
= strtod(vector
[j
].obj
->ptr
,NULL
);
3068 /* We are ready to sort the vector... perform a bit of sanity check
3069 * on the LIMIT option too. We'll use a partial version of quicksort. */
3070 start
= (limit_start
< 0) ? 0 : limit_start
;
3071 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
3072 if (start
>= vectorlen
) {
3073 start
= vectorlen
-1;
3076 if (end
>= vectorlen
) end
= vectorlen
-1;
3078 if (dontsort
== 0) {
3079 server
.sort_desc
= desc
;
3080 server
.sort_alpha
= alpha
;
3081 server
.sort_bypattern
= sortby
? 1 : 0;
3082 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
3085 /* Send command output to the output buffer, performing the specified
3086 * GET/DEL/INCR/DECR operations if any. */
3087 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
3088 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
3089 for (j
= start
; j
<= end
; j
++) {
3090 listNode
*ln
= operations
->head
;
3092 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
3093 sdslen(vector
[j
].obj
->ptr
)));
3094 addReply(c
,vector
[j
].obj
);
3095 addReply(c
,shared
.crlf
);
3098 redisSortOperation
*sop
= ln
->value
;
3099 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
3102 if (sop
->type
== REDIS_SORT_GET
) {
3103 if (!val
|| val
->type
!= REDIS_STRING
) {
3104 addReply(c
,shared
.nullbulk
);
3106 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
3109 addReply(c
,shared
.crlf
);
3111 } else if (sop
->type
== REDIS_SORT_DEL
) {
3119 decrRefCount(sortval
);
3120 listRelease(operations
);
3121 for (j
= 0; j
< vectorlen
; j
++) {
3122 if (sortby
&& alpha
&& vector
[j
].u
.cmpobj
)
3123 decrRefCount(vector
[j
].u
.cmpobj
);
3128 static void infoCommand(redisClient
*c
) {
3130 time_t uptime
= time(NULL
)-server
.stat_starttime
;
3132 info
= sdscatprintf(sdsempty(),
3133 "redis_version:%s\r\n"
3134 "connected_clients:%d\r\n"
3135 "connected_slaves:%d\r\n"
3136 "used_memory:%d\r\n"
3137 "changes_since_last_save:%lld\r\n"
3138 "last_save_time:%d\r\n"
3139 "total_connections_received:%lld\r\n"
3140 "total_commands_processed:%lld\r\n"
3141 "uptime_in_seconds:%d\r\n"
3142 "uptime_in_days:%d\r\n"
3144 listLength(server
.clients
)-listLength(server
.slaves
),
3145 listLength(server
.slaves
),
3149 server
.stat_numconnections
,
3150 server
.stat_numcommands
,
3154 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",sdslen(info
)));
3155 addReplySds(c
,info
);
3156 addReply(c
,shared
.crlf
);
3159 static void monitorCommand(redisClient
*c
) {
3160 /* ignore MONITOR if aleady slave or in monitor mode */
3161 if (c
->flags
& REDIS_SLAVE
) return;
3163 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
3165 if (!listAddNodeTail(server
.monitors
,c
)) oom("listAddNodeTail");
3166 addReply(c
,shared
.ok
);
3169 /* ================================= Expire ================================= */
3170 static int removeExpire(redisDb
*db
, robj
*key
) {
3171 if (dictDelete(db
->expires
,key
) == DICT_OK
) {
3178 static int setExpire(redisDb
*db
, robj
*key
, time_t when
) {
3179 if (dictAdd(db
->expires
,key
,(void*)when
) == DICT_ERR
) {
3187 static int expireIfNeeded(redisDb
*db
, robj
*key
) {
3191 /* No expire? return ASAP */
3192 if (dictSize(db
->expires
) == 0 ||
3193 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
3195 /* Lookup the expire */
3196 when
= (time_t) dictGetEntryVal(de
);
3197 if (time(NULL
) <= when
) return 0;
3199 /* Delete the key */
3200 dictDelete(db
->expires
,key
);
3201 return dictDelete(db
->dict
,key
) == DICT_OK
;
3204 static int deleteIfVolatile(redisDb
*db
, robj
*key
) {
3207 /* No expire? return ASAP */
3208 if (dictSize(db
->expires
) == 0 ||
3209 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
3211 /* Delete the key */
3212 dictDelete(db
->expires
,key
);
3213 return dictDelete(db
->dict
,key
) == DICT_OK
;
3216 static void expireCommand(redisClient
*c
) {
3218 int seconds
= atoi(c
->argv
[2]->ptr
);
3220 de
= dictFind(c
->db
->dict
,c
->argv
[1]);
3222 addReply(c
,shared
.czero
);
3226 addReply(c
, shared
.czero
);
3229 time_t when
= time(NULL
)+seconds
;
3230 if (setExpire(c
->db
,c
->argv
[1],when
))
3231 addReply(c
,shared
.cone
);
3233 addReply(c
,shared
.czero
);
3238 /* =============================== Replication ============================= */
3240 /* Send the whole output buffer syncronously to the slave. This a general operation in theory, but it is actually useful only for replication. */
3241 static int flushClientOutput(redisClient
*c
) {
3243 time_t start
= time(NULL
);
3245 while(listLength(c
->reply
)) {
3246 if (time(NULL
)-start
> 5) return REDIS_ERR
; /* 5 seconds timeout */
3247 retval
= aeWait(c
->fd
,AE_WRITABLE
,1000);
3250 } else if (retval
& AE_WRITABLE
) {
3251 sendReplyToClient(NULL
, c
->fd
, c
, AE_WRITABLE
);
3257 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) {
3258 ssize_t nwritten
, ret
= size
;
3259 time_t start
= time(NULL
);
3263 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
3264 nwritten
= write(fd
,ptr
,size
);
3265 if (nwritten
== -1) return -1;
3269 if ((time(NULL
)-start
) > timeout
) {
3277 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) {
3278 ssize_t nread
, totread
= 0;
3279 time_t start
= time(NULL
);
3283 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
3284 nread
= read(fd
,ptr
,size
);
3285 if (nread
== -1) return -1;
3290 if ((time(NULL
)-start
) > timeout
) {
3298 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
3305 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
3308 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
3319 static void syncCommand(redisClient
*c
) {
3322 time_t start
= time(NULL
);
3325 /* ignore SYNC if aleady slave or in monitor mode */
3326 if (c
->flags
& REDIS_SLAVE
) return;
3328 redisLog(REDIS_NOTICE
,"Slave ask for syncronization");
3329 if (flushClientOutput(c
) == REDIS_ERR
||
3330 rdbSave(server
.dbfilename
) != REDIS_OK
)
3333 fd
= open(server
.dbfilename
, O_RDONLY
);
3334 if (fd
== -1 || fstat(fd
,&sb
) == -1) goto closeconn
;
3337 snprintf(sizebuf
,32,"$%d\r\n",len
);
3338 if (syncWrite(c
->fd
,sizebuf
,strlen(sizebuf
),5) == -1) goto closeconn
;
3343 if (time(NULL
)-start
> REDIS_MAX_SYNC_TIME
) goto closeconn
;
3344 nread
= read(fd
,buf
,1024);
3345 if (nread
== -1) goto closeconn
;
3347 if (syncWrite(c
->fd
,buf
,nread
,5) == -1) goto closeconn
;
3349 if (syncWrite(c
->fd
,"\r\n",2,5) == -1) goto closeconn
;
3351 c
->flags
|= REDIS_SLAVE
;
3353 if (!listAddNodeTail(server
.slaves
,c
)) oom("listAddNodeTail");
3354 redisLog(REDIS_NOTICE
,"Syncronization with slave succeeded");
3358 if (fd
!= -1) close(fd
);
3359 c
->flags
|= REDIS_CLOSE
;
3360 redisLog(REDIS_WARNING
,"Syncronization with slave failed");
3364 static int syncWithMaster(void) {
3365 char buf
[1024], tmpfile
[256];
3367 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
3371 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
3375 /* Issue the SYNC command */
3376 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
3378 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
3382 /* Read the bulk write count */
3383 if (syncReadLine(fd
,buf
,1024,5) == -1) {
3385 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
3389 dumpsize
= atoi(buf
+1);
3390 redisLog(REDIS_NOTICE
,"Receiving %d bytes data dump from MASTER",dumpsize
);
3391 /* Read the bulk write data on a temp file */
3392 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
3393 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
,0644);
3396 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
3400 int nread
, nwritten
;
3402 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
3404 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
3410 nwritten
= write(dfd
,buf
,nread
);
3411 if (nwritten
== -1) {
3412 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
3420 if (rename(tmpfile
,server
.dbfilename
) == -1) {
3421 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
3427 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
3428 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
3432 server
.master
= createClient(fd
);
3433 server
.master
->flags
|= REDIS_MASTER
;
3434 server
.replstate
= REDIS_REPL_CONNECTED
;
3438 /* =================================== Main! ================================ */
3440 static void daemonize(void) {
3444 if (fork() != 0) exit(0); /* parent exits */
3445 setsid(); /* create a new session */
3447 /* Every output goes to /dev/null. If Redis is daemonized but
3448 * the 'logfile' is set to 'stdout' in the configuration file
3449 * it will not log at all. */
3450 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
3451 dup2(fd
, STDIN_FILENO
);
3452 dup2(fd
, STDOUT_FILENO
);
3453 dup2(fd
, STDERR_FILENO
);
3454 if (fd
> STDERR_FILENO
) close(fd
);
3456 /* Try to write the pid file */
3457 fp
= fopen(server
.pidfile
,"w");
3459 fprintf(fp
,"%d\n",getpid());
3464 int main(int argc
, char **argv
) {
3467 ResetServerSaveParams();
3468 loadServerConfig(argv
[1]);
3469 } else if (argc
> 2) {
3470 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
3474 if (server
.daemonize
) daemonize();
3475 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
3476 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
3477 redisLog(REDIS_NOTICE
,"DB loaded from disk");
3478 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
3479 acceptHandler
, NULL
, NULL
) == AE_ERR
) oom("creating file event");
3480 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
3482 aeDeleteEventLoop(server
.el
);