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 skip it */
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
*rdbLoadLzfStringObject(FILE*fp
, int rdbver
) {
1896 unsigned int len
, clen
;
1897 unsigned char *c
= NULL
;
1900 if ((clen
= rdbLoadLen(fp
,rdbver
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
1901 if ((len
= rdbLoadLen(fp
,rdbver
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
1902 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
1903 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
1904 if (fread(c
,clen
,1,fp
) == 0) goto err
;
1905 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
1906 return createObject(REDIS_STRING
,val
);
1913 static robj
*rdbLoadStringObject(FILE*fp
, int rdbver
) {
1918 len
= rdbLoadLen(fp
,rdbver
,&isencoded
);
1921 case REDIS_RDB_ENC_INT8
:
1922 case REDIS_RDB_ENC_INT16
:
1923 case REDIS_RDB_ENC_INT32
:
1924 return tryObjectSharing(rdbLoadIntegerObject(fp
,len
));
1925 case REDIS_RDB_ENC_LZF
:
1926 return tryObjectSharing(rdbLoadLzfStringObject(fp
,rdbver
));
1932 if (len
== REDIS_RDB_LENERR
) return NULL
;
1933 val
= sdsnewlen(NULL
,len
);
1934 if (len
&& fread(val
,len
,1,fp
) == 0) {
1938 return tryObjectSharing(createObject(REDIS_STRING
,val
));
1941 static int rdbLoad(char *filename
) {
1943 robj
*keyobj
= NULL
;
1947 dict
*d
= server
.db
[0].dict
;
1950 fp
= fopen(filename
,"r");
1951 if (!fp
) return REDIS_ERR
;
1952 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
1954 if (memcmp(buf
,"REDIS",5) != 0) {
1956 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
1959 rdbver
= atoi(buf
+5);
1962 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
1969 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
1970 if (type
== REDIS_EOF
) break;
1971 /* Handle SELECT DB opcode as a special case */
1972 if (type
== REDIS_SELECTDB
) {
1973 if ((dbid
= rdbLoadLen(fp
,rdbver
,NULL
)) == REDIS_RDB_LENERR
)
1975 if (dbid
>= (unsigned)server
.dbnum
) {
1976 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
1979 d
= server
.db
[dbid
].dict
;
1983 if ((keyobj
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
1985 if (type
== REDIS_STRING
) {
1986 /* Read string value */
1987 if ((o
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
1988 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
1989 /* Read list/set value */
1992 if ((listlen
= rdbLoadLen(fp
,rdbver
,NULL
)) == REDIS_RDB_LENERR
)
1994 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
1995 /* Load every single element of the list/set */
1999 if ((ele
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
2000 if (type
== REDIS_LIST
) {
2001 if (!listAddNodeTail((list
*)o
->ptr
,ele
))
2002 oom("listAddNodeTail");
2004 if (dictAdd((dict
*)o
->ptr
,ele
,NULL
) == DICT_ERR
)
2011 /* Add the new object in the hash table */
2012 retval
= dictAdd(d
,keyobj
,o
);
2013 if (retval
== DICT_ERR
) {
2014 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj
->ptr
);
2022 eoferr
: /* unexpected end of file is handled here with a fatal exit */
2023 if (keyobj
) decrRefCount(keyobj
);
2024 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, exiting now.");
2026 return REDIS_ERR
; /* Just to avoid warning */
2029 /*================================== Commands =============================== */
2031 static void authCommand(redisClient
*c
) {
2032 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
2033 c
->authenticated
= 1;
2034 addReply(c
,shared
.ok
);
2036 c
->authenticated
= 0;
2037 addReply(c
,shared
.err
);
2041 static void pingCommand(redisClient
*c
) {
2042 addReply(c
,shared
.pong
);
2045 static void echoCommand(redisClient
*c
) {
2046 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
2047 (int)sdslen(c
->argv
[1]->ptr
)));
2048 addReply(c
,c
->argv
[1]);
2049 addReply(c
,shared
.crlf
);
2052 /*=================================== Strings =============================== */
2054 static void setGenericCommand(redisClient
*c
, int nx
) {
2057 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
2058 if (retval
== DICT_ERR
) {
2060 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
2061 incrRefCount(c
->argv
[2]);
2063 addReply(c
,shared
.czero
);
2067 incrRefCount(c
->argv
[1]);
2068 incrRefCount(c
->argv
[2]);
2071 removeExpire(c
->db
,c
->argv
[1]);
2072 addReply(c
, nx
? shared
.cone
: shared
.ok
);
2075 static void setCommand(redisClient
*c
) {
2076 setGenericCommand(c
,0);
2079 static void setnxCommand(redisClient
*c
) {
2080 setGenericCommand(c
,1);
2083 static void getCommand(redisClient
*c
) {
2084 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[1]);
2087 addReply(c
,shared
.nullbulk
);
2089 if (o
->type
!= REDIS_STRING
) {
2090 addReply(c
,shared
.wrongtypeerr
);
2092 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(o
->ptr
)));
2094 addReply(c
,shared
.crlf
);
2099 static void mgetCommand(redisClient
*c
) {
2102 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
2103 for (j
= 1; j
< c
->argc
; j
++) {
2104 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[j
]);
2106 addReply(c
,shared
.nullbulk
);
2108 if (o
->type
!= REDIS_STRING
) {
2109 addReply(c
,shared
.nullbulk
);
2111 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(o
->ptr
)));
2113 addReply(c
,shared
.crlf
);
2119 static void incrDecrCommand(redisClient
*c
, int incr
) {
2124 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2128 if (o
->type
!= REDIS_STRING
) {
2133 value
= strtoll(o
->ptr
, &eptr
, 10);
2138 o
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
));
2139 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],o
);
2140 if (retval
== DICT_ERR
) {
2141 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
2142 removeExpire(c
->db
,c
->argv
[1]);
2144 incrRefCount(c
->argv
[1]);
2147 addReply(c
,shared
.colon
);
2149 addReply(c
,shared
.crlf
);
2152 static void incrCommand(redisClient
*c
) {
2153 incrDecrCommand(c
,1);
2156 static void decrCommand(redisClient
*c
) {
2157 incrDecrCommand(c
,-1);
2160 static void incrbyCommand(redisClient
*c
) {
2161 int incr
= atoi(c
->argv
[2]->ptr
);
2162 incrDecrCommand(c
,incr
);
2165 static void decrbyCommand(redisClient
*c
) {
2166 int incr
= atoi(c
->argv
[2]->ptr
);
2167 incrDecrCommand(c
,-incr
);
2170 /* ========================= Type agnostic commands ========================= */
2172 static void delCommand(redisClient
*c
) {
2173 if (deleteKey(c
->db
,c
->argv
[1])) {
2175 addReply(c
,shared
.cone
);
2177 addReply(c
,shared
.czero
);
2181 static void existsCommand(redisClient
*c
) {
2182 addReply(c
,lookupKeyRead(c
->db
,c
->argv
[1]) ? shared
.cone
: shared
.czero
);
2185 static void selectCommand(redisClient
*c
) {
2186 int id
= atoi(c
->argv
[1]->ptr
);
2188 if (selectDb(c
,id
) == REDIS_ERR
) {
2189 addReplySds(c
,sdsnew("-ERR invalid DB index\r\n"));
2191 addReply(c
,shared
.ok
);
2195 static void randomkeyCommand(redisClient
*c
) {
2199 de
= dictGetRandomKey(c
->db
->dict
);
2200 if (expireIfNeeded(c
->db
,dictGetEntryKey(de
)) == 0) break;
2203 addReply(c
,shared
.crlf
);
2205 addReply(c
,shared
.plus
);
2206 addReply(c
,dictGetEntryKey(de
));
2207 addReply(c
,shared
.crlf
);
2211 static void keysCommand(redisClient
*c
) {
2214 sds pattern
= c
->argv
[1]->ptr
;
2215 int plen
= sdslen(pattern
);
2216 int numkeys
= 0, keyslen
= 0;
2217 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
2219 di
= dictGetIterator(c
->db
->dict
);
2220 if (!di
) oom("dictGetIterator");
2222 decrRefCount(lenobj
);
2223 while((de
= dictNext(di
)) != NULL
) {
2224 robj
*keyobj
= dictGetEntryKey(de
);
2226 sds key
= keyobj
->ptr
;
2227 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
2228 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
2229 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
2231 addReply(c
,shared
.space
);
2234 keyslen
+= sdslen(key
);
2238 dictReleaseIterator(di
);
2239 lenobj
->ptr
= sdscatprintf(sdsempty(),"$%lu\r\n",keyslen
+(numkeys
? (numkeys
-1) : 0));
2240 addReply(c
,shared
.crlf
);
2243 static void dbsizeCommand(redisClient
*c
) {
2245 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c
->db
->dict
)));
2248 static void lastsaveCommand(redisClient
*c
) {
2250 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
2253 static void typeCommand(redisClient
*c
) {
2257 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
2262 case REDIS_STRING
: type
= "+string"; break;
2263 case REDIS_LIST
: type
= "+list"; break;
2264 case REDIS_SET
: type
= "+set"; break;
2265 default: type
= "unknown"; break;
2268 addReplySds(c
,sdsnew(type
));
2269 addReply(c
,shared
.crlf
);
2272 static void saveCommand(redisClient
*c
) {
2273 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
2274 addReply(c
,shared
.ok
);
2276 addReply(c
,shared
.err
);
2280 static void bgsaveCommand(redisClient
*c
) {
2281 if (server
.bgsaveinprogress
) {
2282 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
2285 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
2286 addReply(c
,shared
.ok
);
2288 addReply(c
,shared
.err
);
2292 static void shutdownCommand(redisClient
*c
) {
2293 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
2294 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
2295 if (server
.daemonize
) {
2296 unlink(server
.pidfile
);
2298 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
2301 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
2302 addReplySds(c
,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
2306 static void renameGenericCommand(redisClient
*c
, int nx
) {
2309 /* To use the same key as src and dst is probably an error */
2310 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
2311 addReply(c
,shared
.sameobjecterr
);
2315 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2317 addReply(c
,shared
.nokeyerr
);
2321 deleteIfVolatile(c
->db
,c
->argv
[2]);
2322 if (dictAdd(c
->db
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
2325 addReply(c
,shared
.czero
);
2328 dictReplace(c
->db
->dict
,c
->argv
[2],o
);
2330 incrRefCount(c
->argv
[2]);
2332 deleteKey(c
->db
,c
->argv
[1]);
2334 addReply(c
,nx
? shared
.cone
: shared
.ok
);
2337 static void renameCommand(redisClient
*c
) {
2338 renameGenericCommand(c
,0);
2341 static void renamenxCommand(redisClient
*c
) {
2342 renameGenericCommand(c
,1);
2345 static void moveCommand(redisClient
*c
) {
2350 /* Obtain source and target DB pointers */
2353 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
2354 addReply(c
,shared
.outofrangeerr
);
2358 selectDb(c
,srcid
); /* Back to the source DB */
2360 /* If the user is moving using as target the same
2361 * DB as the source DB it is probably an error. */
2363 addReply(c
,shared
.sameobjecterr
);
2367 /* Check if the element exists and get a reference */
2368 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2370 addReply(c
,shared
.czero
);
2374 /* Try to add the element to the target DB */
2375 deleteIfVolatile(dst
,c
->argv
[1]);
2376 if (dictAdd(dst
->dict
,c
->argv
[1],o
) == DICT_ERR
) {
2377 addReply(c
,shared
.czero
);
2380 incrRefCount(c
->argv
[1]);
2383 /* OK! key moved, free the entry in the source DB */
2384 deleteKey(src
,c
->argv
[1]);
2386 addReply(c
,shared
.cone
);
2389 /* =================================== Lists ================================ */
2390 static void pushGenericCommand(redisClient
*c
, int where
) {
2394 lobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2396 lobj
= createListObject();
2398 if (where
== REDIS_HEAD
) {
2399 if (!listAddNodeHead(list
,c
->argv
[2])) oom("listAddNodeHead");
2401 if (!listAddNodeTail(list
,c
->argv
[2])) oom("listAddNodeTail");
2403 dictAdd(c
->db
->dict
,c
->argv
[1],lobj
);
2404 incrRefCount(c
->argv
[1]);
2405 incrRefCount(c
->argv
[2]);
2407 if (lobj
->type
!= REDIS_LIST
) {
2408 addReply(c
,shared
.wrongtypeerr
);
2412 if (where
== REDIS_HEAD
) {
2413 if (!listAddNodeHead(list
,c
->argv
[2])) oom("listAddNodeHead");
2415 if (!listAddNodeTail(list
,c
->argv
[2])) oom("listAddNodeTail");
2417 incrRefCount(c
->argv
[2]);
2420 addReply(c
,shared
.ok
);
2423 static void lpushCommand(redisClient
*c
) {
2424 pushGenericCommand(c
,REDIS_HEAD
);
2427 static void rpushCommand(redisClient
*c
) {
2428 pushGenericCommand(c
,REDIS_TAIL
);
2431 static void llenCommand(redisClient
*c
) {
2435 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
2437 addReply(c
,shared
.czero
);
2440 if (o
->type
!= REDIS_LIST
) {
2441 addReply(c
,shared
.wrongtypeerr
);
2444 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(l
)));
2449 static void lindexCommand(redisClient
*c
) {
2451 int index
= atoi(c
->argv
[2]->ptr
);
2453 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
2455 addReply(c
,shared
.nullbulk
);
2457 if (o
->type
!= REDIS_LIST
) {
2458 addReply(c
,shared
.wrongtypeerr
);
2460 list
*list
= o
->ptr
;
2463 ln
= listIndex(list
, index
);
2465 addReply(c
,shared
.nullbulk
);
2467 robj
*ele
= listNodeValue(ln
);
2468 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2470 addReply(c
,shared
.crlf
);
2476 static void lsetCommand(redisClient
*c
) {
2478 int index
= atoi(c
->argv
[2]->ptr
);
2480 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2482 addReply(c
,shared
.nokeyerr
);
2484 if (o
->type
!= REDIS_LIST
) {
2485 addReply(c
,shared
.wrongtypeerr
);
2487 list
*list
= o
->ptr
;
2490 ln
= listIndex(list
, index
);
2492 addReply(c
,shared
.outofrangeerr
);
2494 robj
*ele
= listNodeValue(ln
);
2497 listNodeValue(ln
) = c
->argv
[3];
2498 incrRefCount(c
->argv
[3]);
2499 addReply(c
,shared
.ok
);
2506 static void popGenericCommand(redisClient
*c
, int where
) {
2509 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2511 addReply(c
,shared
.nullbulk
);
2513 if (o
->type
!= REDIS_LIST
) {
2514 addReply(c
,shared
.wrongtypeerr
);
2516 list
*list
= o
->ptr
;
2519 if (where
== REDIS_HEAD
)
2520 ln
= listFirst(list
);
2522 ln
= listLast(list
);
2525 addReply(c
,shared
.nullbulk
);
2527 robj
*ele
= listNodeValue(ln
);
2528 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2530 addReply(c
,shared
.crlf
);
2531 listDelNode(list
,ln
);
2538 static void lpopCommand(redisClient
*c
) {
2539 popGenericCommand(c
,REDIS_HEAD
);
2542 static void rpopCommand(redisClient
*c
) {
2543 popGenericCommand(c
,REDIS_TAIL
);
2546 static void lrangeCommand(redisClient
*c
) {
2548 int start
= atoi(c
->argv
[2]->ptr
);
2549 int end
= atoi(c
->argv
[3]->ptr
);
2551 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
2553 addReply(c
,shared
.nullmultibulk
);
2555 if (o
->type
!= REDIS_LIST
) {
2556 addReply(c
,shared
.wrongtypeerr
);
2558 list
*list
= o
->ptr
;
2560 int llen
= listLength(list
);
2564 /* convert negative indexes */
2565 if (start
< 0) start
= llen
+start
;
2566 if (end
< 0) end
= llen
+end
;
2567 if (start
< 0) start
= 0;
2568 if (end
< 0) end
= 0;
2570 /* indexes sanity checks */
2571 if (start
> end
|| start
>= llen
) {
2572 /* Out of range start or start > end result in empty list */
2573 addReply(c
,shared
.emptymultibulk
);
2576 if (end
>= llen
) end
= llen
-1;
2577 rangelen
= (end
-start
)+1;
2579 /* Return the result in form of a multi-bulk reply */
2580 ln
= listIndex(list
, start
);
2581 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
2582 for (j
= 0; j
< rangelen
; j
++) {
2583 ele
= listNodeValue(ln
);
2584 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2586 addReply(c
,shared
.crlf
);
2593 static void ltrimCommand(redisClient
*c
) {
2595 int start
= atoi(c
->argv
[2]->ptr
);
2596 int end
= atoi(c
->argv
[3]->ptr
);
2598 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2600 addReply(c
,shared
.nokeyerr
);
2602 if (o
->type
!= REDIS_LIST
) {
2603 addReply(c
,shared
.wrongtypeerr
);
2605 list
*list
= o
->ptr
;
2607 int llen
= listLength(list
);
2608 int j
, ltrim
, rtrim
;
2610 /* convert negative indexes */
2611 if (start
< 0) start
= llen
+start
;
2612 if (end
< 0) end
= llen
+end
;
2613 if (start
< 0) start
= 0;
2614 if (end
< 0) end
= 0;
2616 /* indexes sanity checks */
2617 if (start
> end
|| start
>= llen
) {
2618 /* Out of range start or start > end result in empty list */
2622 if (end
>= llen
) end
= llen
-1;
2627 /* Remove list elements to perform the trim */
2628 for (j
= 0; j
< ltrim
; j
++) {
2629 ln
= listFirst(list
);
2630 listDelNode(list
,ln
);
2632 for (j
= 0; j
< rtrim
; j
++) {
2633 ln
= listLast(list
);
2634 listDelNode(list
,ln
);
2636 addReply(c
,shared
.ok
);
2642 static void lremCommand(redisClient
*c
) {
2645 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2647 addReply(c
,shared
.nokeyerr
);
2649 if (o
->type
!= REDIS_LIST
) {
2650 addReply(c
,shared
.wrongtypeerr
);
2652 list
*list
= o
->ptr
;
2653 listNode
*ln
, *next
;
2654 int toremove
= atoi(c
->argv
[2]->ptr
);
2659 toremove
= -toremove
;
2662 ln
= fromtail
? list
->tail
: list
->head
;
2664 robj
*ele
= listNodeValue(ln
);
2666 next
= fromtail
? ln
->prev
: ln
->next
;
2667 if (sdscmp(ele
->ptr
,c
->argv
[3]->ptr
) == 0) {
2668 listDelNode(list
,ln
);
2671 if (toremove
&& removed
== toremove
) break;
2675 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
2680 /* ==================================== Sets ================================ */
2682 static void saddCommand(redisClient
*c
) {
2685 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2687 set
= createSetObject();
2688 dictAdd(c
->db
->dict
,c
->argv
[1],set
);
2689 incrRefCount(c
->argv
[1]);
2691 if (set
->type
!= REDIS_SET
) {
2692 addReply(c
,shared
.wrongtypeerr
);
2696 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
2697 incrRefCount(c
->argv
[2]);
2699 addReply(c
,shared
.cone
);
2701 addReply(c
,shared
.czero
);
2705 static void sremCommand(redisClient
*c
) {
2708 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2710 addReply(c
,shared
.czero
);
2712 if (set
->type
!= REDIS_SET
) {
2713 addReply(c
,shared
.wrongtypeerr
);
2716 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
2718 addReply(c
,shared
.cone
);
2720 addReply(c
,shared
.czero
);
2725 static void sismemberCommand(redisClient
*c
) {
2728 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
2730 addReply(c
,shared
.czero
);
2732 if (set
->type
!= REDIS_SET
) {
2733 addReply(c
,shared
.wrongtypeerr
);
2736 if (dictFind(set
->ptr
,c
->argv
[2]))
2737 addReply(c
,shared
.cone
);
2739 addReply(c
,shared
.czero
);
2743 static void scardCommand(redisClient
*c
) {
2747 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
2749 addReply(c
,shared
.czero
);
2752 if (o
->type
!= REDIS_SET
) {
2753 addReply(c
,shared
.wrongtypeerr
);
2756 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",
2762 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
2763 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
2765 return dictSize(*d1
)-dictSize(*d2
);
2768 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
) {
2769 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
2772 robj
*lenobj
= NULL
, *dstset
= NULL
;
2773 int j
, cardinality
= 0;
2775 if (!dv
) oom("sinterCommand");
2776 for (j
= 0; j
< setsnum
; j
++) {
2780 lookupKeyWrite(c
->db
,setskeys
[j
]) :
2781 lookupKeyRead(c
->db
,setskeys
[j
]);
2784 addReply(c
,shared
.nokeyerr
);
2787 if (setobj
->type
!= REDIS_SET
) {
2789 addReply(c
,shared
.wrongtypeerr
);
2792 dv
[j
] = setobj
->ptr
;
2794 /* Sort sets from the smallest to largest, this will improve our
2795 * algorithm's performace */
2796 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
2798 /* The first thing we should output is the total number of elements...
2799 * since this is a multi-bulk write, but at this stage we don't know
2800 * the intersection set size, so we use a trick, append an empty object
2801 * to the output list and save the pointer to later modify it with the
2804 lenobj
= createObject(REDIS_STRING
,NULL
);
2806 decrRefCount(lenobj
);
2808 /* If we have a target key where to store the resulting set
2809 * create this key with an empty set inside */
2810 dstset
= createSetObject();
2811 deleteKey(c
->db
,dstkey
);
2812 dictAdd(c
->db
->dict
,dstkey
,dstset
);
2813 incrRefCount(dstkey
);
2816 /* Iterate all the elements of the first (smallest) set, and test
2817 * the element against all the other sets, if at least one set does
2818 * not include the element it is discarded */
2819 di
= dictGetIterator(dv
[0]);
2820 if (!di
) oom("dictGetIterator");
2822 while((de
= dictNext(di
)) != NULL
) {
2825 for (j
= 1; j
< setsnum
; j
++)
2826 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
2828 continue; /* at least one set does not contain the member */
2829 ele
= dictGetEntryKey(de
);
2831 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",sdslen(ele
->ptr
)));
2833 addReply(c
,shared
.crlf
);
2836 dictAdd(dstset
->ptr
,ele
,NULL
);
2840 dictReleaseIterator(di
);
2843 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%d\r\n",cardinality
);
2845 addReply(c
,shared
.ok
);
2849 static void sinterCommand(redisClient
*c
) {
2850 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
2853 static void sinterstoreCommand(redisClient
*c
) {
2854 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
2857 static void flushdbCommand(redisClient
*c
) {
2858 dictEmpty(c
->db
->dict
);
2859 dictEmpty(c
->db
->expires
);
2860 addReply(c
,shared
.ok
);
2861 rdbSave(server
.dbfilename
);
2864 static void flushallCommand(redisClient
*c
) {
2866 addReply(c
,shared
.ok
);
2867 rdbSave(server
.dbfilename
);
2870 redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
2871 redisSortOperation
*so
= zmalloc(sizeof(*so
));
2872 if (!so
) oom("createSortOperation");
2874 so
->pattern
= pattern
;
2878 /* Return the value associated to the key with a name obtained
2879 * substituting the first occurence of '*' in 'pattern' with 'subst' */
2880 robj
*lookupKeyByPattern(redisDb
*db
, robj
*pattern
, robj
*subst
) {
2884 int prefixlen
, sublen
, postfixlen
;
2885 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
2889 char buf
[REDIS_SORTKEY_MAX
+1];
2892 spat
= pattern
->ptr
;
2894 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
2895 p
= strchr(spat
,'*');
2896 if (!p
) return NULL
;
2899 sublen
= sdslen(ssub
);
2900 postfixlen
= sdslen(spat
)-(prefixlen
+1);
2901 memcpy(keyname
.buf
,spat
,prefixlen
);
2902 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
2903 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
2904 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
2905 keyname
.len
= prefixlen
+sublen
+postfixlen
;
2907 keyobj
.refcount
= 1;
2908 keyobj
.type
= REDIS_STRING
;
2909 keyobj
.ptr
= ((char*)&keyname
)+(sizeof(long)*2);
2911 /* printf("lookup '%s' => %p\n", keyname.buf,de); */
2912 return lookupKeyRead(db
,&keyobj
);
2915 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
2916 * the additional parameter is not standard but a BSD-specific we have to
2917 * pass sorting parameters via the global 'server' structure */
2918 static int sortCompare(const void *s1
, const void *s2
) {
2919 const redisSortObject
*so1
= s1
, *so2
= s2
;
2922 if (!server
.sort_alpha
) {
2923 /* Numeric sorting. Here it's trivial as we precomputed scores */
2924 if (so1
->u
.score
> so2
->u
.score
) {
2926 } else if (so1
->u
.score
< so2
->u
.score
) {
2932 /* Alphanumeric sorting */
2933 if (server
.sort_bypattern
) {
2934 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
2935 /* At least one compare object is NULL */
2936 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
2938 else if (so1
->u
.cmpobj
== NULL
)
2943 /* We have both the objects, use strcoll */
2944 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
2947 /* Compare elements directly */
2948 cmp
= strcoll(so1
->obj
->ptr
,so2
->obj
->ptr
);
2951 return server
.sort_desc
? -cmp
: cmp
;
2954 /* The SORT command is the most complex command in Redis. Warning: this code
2955 * is optimized for speed and a bit less for readability */
2956 static void sortCommand(redisClient
*c
) {
2959 int desc
= 0, alpha
= 0;
2960 int limit_start
= 0, limit_count
= -1, start
, end
;
2961 int j
, dontsort
= 0, vectorlen
;
2962 int getop
= 0; /* GET operation counter */
2963 robj
*sortval
, *sortby
= NULL
;
2964 redisSortObject
*vector
; /* Resulting vector to sort */
2966 /* Lookup the key to sort. It must be of the right types */
2967 sortval
= lookupKeyRead(c
->db
,c
->argv
[1]);
2968 if (sortval
== NULL
) {
2969 addReply(c
,shared
.nokeyerr
);
2972 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
) {
2973 addReply(c
,shared
.wrongtypeerr
);
2977 /* Create a list of operations to perform for every sorted element.
2978 * Operations can be GET/DEL/INCR/DECR */
2979 operations
= listCreate();
2980 listSetFreeMethod(operations
,zfree
);
2983 /* Now we need to protect sortval incrementing its count, in the future
2984 * SORT may have options able to overwrite/delete keys during the sorting
2985 * and the sorted key itself may get destroied */
2986 incrRefCount(sortval
);
2988 /* The SORT command has an SQL-alike syntax, parse it */
2989 while(j
< c
->argc
) {
2990 int leftargs
= c
->argc
-j
-1;
2991 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
2993 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
2995 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
2997 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
2998 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
2999 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
3001 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
3002 sortby
= c
->argv
[j
+1];
3003 /* If the BY pattern does not contain '*', i.e. it is constant,
3004 * we don't need to sort nor to lookup the weight keys. */
3005 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
3007 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
3008 listAddNodeTail(operations
,createSortOperation(
3009 REDIS_SORT_GET
,c
->argv
[j
+1]));
3012 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"del") && leftargs
>= 1) {
3013 listAddNodeTail(operations
,createSortOperation(
3014 REDIS_SORT_DEL
,c
->argv
[j
+1]));
3016 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"incr") && leftargs
>= 1) {
3017 listAddNodeTail(operations
,createSortOperation(
3018 REDIS_SORT_INCR
,c
->argv
[j
+1]));
3020 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
3021 listAddNodeTail(operations
,createSortOperation(
3022 REDIS_SORT_DECR
,c
->argv
[j
+1]));
3025 decrRefCount(sortval
);
3026 listRelease(operations
);
3027 addReply(c
,shared
.syntaxerr
);
3033 /* Load the sorting vector with all the objects to sort */
3034 vectorlen
= (sortval
->type
== REDIS_LIST
) ?
3035 listLength((list
*)sortval
->ptr
) :
3036 dictSize((dict
*)sortval
->ptr
);
3037 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
3038 if (!vector
) oom("allocating objects vector for SORT");
3040 if (sortval
->type
== REDIS_LIST
) {
3041 list
*list
= sortval
->ptr
;
3042 listNode
*ln
= list
->head
;
3044 robj
*ele
= ln
->value
;
3045 vector
[j
].obj
= ele
;
3046 vector
[j
].u
.score
= 0;
3047 vector
[j
].u
.cmpobj
= NULL
;
3052 dict
*set
= sortval
->ptr
;
3056 di
= dictGetIterator(set
);
3057 if (!di
) oom("dictGetIterator");
3058 while((setele
= dictNext(di
)) != NULL
) {
3059 vector
[j
].obj
= dictGetEntryKey(setele
);
3060 vector
[j
].u
.score
= 0;
3061 vector
[j
].u
.cmpobj
= NULL
;
3064 dictReleaseIterator(di
);
3066 assert(j
== vectorlen
);
3068 /* Now it's time to load the right scores in the sorting vector */
3069 if (dontsort
== 0) {
3070 for (j
= 0; j
< vectorlen
; j
++) {
3074 byval
= lookupKeyByPattern(c
->db
,sortby
,vector
[j
].obj
);
3075 if (!byval
|| byval
->type
!= REDIS_STRING
) continue;
3077 vector
[j
].u
.cmpobj
= byval
;
3078 incrRefCount(byval
);
3080 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
3083 if (!alpha
) vector
[j
].u
.score
= strtod(vector
[j
].obj
->ptr
,NULL
);
3088 /* We are ready to sort the vector... perform a bit of sanity check
3089 * on the LIMIT option too. We'll use a partial version of quicksort. */
3090 start
= (limit_start
< 0) ? 0 : limit_start
;
3091 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
3092 if (start
>= vectorlen
) {
3093 start
= vectorlen
-1;
3096 if (end
>= vectorlen
) end
= vectorlen
-1;
3098 if (dontsort
== 0) {
3099 server
.sort_desc
= desc
;
3100 server
.sort_alpha
= alpha
;
3101 server
.sort_bypattern
= sortby
? 1 : 0;
3102 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
3105 /* Send command output to the output buffer, performing the specified
3106 * GET/DEL/INCR/DECR operations if any. */
3107 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
3108 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
3109 for (j
= start
; j
<= end
; j
++) {
3110 listNode
*ln
= operations
->head
;
3112 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
3113 sdslen(vector
[j
].obj
->ptr
)));
3114 addReply(c
,vector
[j
].obj
);
3115 addReply(c
,shared
.crlf
);
3118 redisSortOperation
*sop
= ln
->value
;
3119 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
3122 if (sop
->type
== REDIS_SORT_GET
) {
3123 if (!val
|| val
->type
!= REDIS_STRING
) {
3124 addReply(c
,shared
.nullbulk
);
3126 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
3129 addReply(c
,shared
.crlf
);
3131 } else if (sop
->type
== REDIS_SORT_DEL
) {
3139 decrRefCount(sortval
);
3140 listRelease(operations
);
3141 for (j
= 0; j
< vectorlen
; j
++) {
3142 if (sortby
&& alpha
&& vector
[j
].u
.cmpobj
)
3143 decrRefCount(vector
[j
].u
.cmpobj
);
3148 static void infoCommand(redisClient
*c
) {
3150 time_t uptime
= time(NULL
)-server
.stat_starttime
;
3152 info
= sdscatprintf(sdsempty(),
3153 "redis_version:%s\r\n"
3154 "connected_clients:%d\r\n"
3155 "connected_slaves:%d\r\n"
3156 "used_memory:%d\r\n"
3157 "changes_since_last_save:%lld\r\n"
3158 "last_save_time:%d\r\n"
3159 "total_connections_received:%lld\r\n"
3160 "total_commands_processed:%lld\r\n"
3161 "uptime_in_seconds:%d\r\n"
3162 "uptime_in_days:%d\r\n"
3164 listLength(server
.clients
)-listLength(server
.slaves
),
3165 listLength(server
.slaves
),
3169 server
.stat_numconnections
,
3170 server
.stat_numcommands
,
3174 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",sdslen(info
)));
3175 addReplySds(c
,info
);
3176 addReply(c
,shared
.crlf
);
3179 static void monitorCommand(redisClient
*c
) {
3180 /* ignore MONITOR if aleady slave or in monitor mode */
3181 if (c
->flags
& REDIS_SLAVE
) return;
3183 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
3185 if (!listAddNodeTail(server
.monitors
,c
)) oom("listAddNodeTail");
3186 addReply(c
,shared
.ok
);
3189 /* ================================= Expire ================================= */
3190 static int removeExpire(redisDb
*db
, robj
*key
) {
3191 if (dictDelete(db
->expires
,key
) == DICT_OK
) {
3198 static int setExpire(redisDb
*db
, robj
*key
, time_t when
) {
3199 if (dictAdd(db
->expires
,key
,(void*)when
) == DICT_ERR
) {
3207 static int expireIfNeeded(redisDb
*db
, robj
*key
) {
3211 /* No expire? return ASAP */
3212 if (dictSize(db
->expires
) == 0 ||
3213 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
3215 /* Lookup the expire */
3216 when
= (time_t) dictGetEntryVal(de
);
3217 if (time(NULL
) <= when
) return 0;
3219 /* Delete the key */
3220 dictDelete(db
->expires
,key
);
3221 return dictDelete(db
->dict
,key
) == DICT_OK
;
3224 static int deleteIfVolatile(redisDb
*db
, robj
*key
) {
3227 /* No expire? return ASAP */
3228 if (dictSize(db
->expires
) == 0 ||
3229 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
3231 /* Delete the key */
3232 dictDelete(db
->expires
,key
);
3233 return dictDelete(db
->dict
,key
) == DICT_OK
;
3236 static void expireCommand(redisClient
*c
) {
3238 int seconds
= atoi(c
->argv
[2]->ptr
);
3240 de
= dictFind(c
->db
->dict
,c
->argv
[1]);
3242 addReply(c
,shared
.czero
);
3246 addReply(c
, shared
.czero
);
3249 time_t when
= time(NULL
)+seconds
;
3250 if (setExpire(c
->db
,c
->argv
[1],when
))
3251 addReply(c
,shared
.cone
);
3253 addReply(c
,shared
.czero
);
3258 /* =============================== Replication ============================= */
3260 /* Send the whole output buffer syncronously to the slave. This a general operation in theory, but it is actually useful only for replication. */
3261 static int flushClientOutput(redisClient
*c
) {
3263 time_t start
= time(NULL
);
3265 while(listLength(c
->reply
)) {
3266 if (time(NULL
)-start
> 5) return REDIS_ERR
; /* 5 seconds timeout */
3267 retval
= aeWait(c
->fd
,AE_WRITABLE
,1000);
3270 } else if (retval
& AE_WRITABLE
) {
3271 sendReplyToClient(NULL
, c
->fd
, c
, AE_WRITABLE
);
3277 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) {
3278 ssize_t nwritten
, ret
= size
;
3279 time_t start
= time(NULL
);
3283 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
3284 nwritten
= write(fd
,ptr
,size
);
3285 if (nwritten
== -1) return -1;
3289 if ((time(NULL
)-start
) > timeout
) {
3297 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) {
3298 ssize_t nread
, totread
= 0;
3299 time_t start
= time(NULL
);
3303 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
3304 nread
= read(fd
,ptr
,size
);
3305 if (nread
== -1) return -1;
3310 if ((time(NULL
)-start
) > timeout
) {
3318 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
3325 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
3328 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
3339 static void syncCommand(redisClient
*c
) {
3342 time_t start
= time(NULL
);
3345 /* ignore SYNC if aleady slave or in monitor mode */
3346 if (c
->flags
& REDIS_SLAVE
) return;
3348 redisLog(REDIS_NOTICE
,"Slave ask for syncronization");
3349 if (flushClientOutput(c
) == REDIS_ERR
||
3350 rdbSave(server
.dbfilename
) != REDIS_OK
)
3353 fd
= open(server
.dbfilename
, O_RDONLY
);
3354 if (fd
== -1 || fstat(fd
,&sb
) == -1) goto closeconn
;
3357 snprintf(sizebuf
,32,"$%d\r\n",len
);
3358 if (syncWrite(c
->fd
,sizebuf
,strlen(sizebuf
),5) == -1) goto closeconn
;
3363 if (time(NULL
)-start
> REDIS_MAX_SYNC_TIME
) goto closeconn
;
3364 nread
= read(fd
,buf
,1024);
3365 if (nread
== -1) goto closeconn
;
3367 if (syncWrite(c
->fd
,buf
,nread
,5) == -1) goto closeconn
;
3369 if (syncWrite(c
->fd
,"\r\n",2,5) == -1) goto closeconn
;
3371 c
->flags
|= REDIS_SLAVE
;
3373 if (!listAddNodeTail(server
.slaves
,c
)) oom("listAddNodeTail");
3374 redisLog(REDIS_NOTICE
,"Syncronization with slave succeeded");
3378 if (fd
!= -1) close(fd
);
3379 c
->flags
|= REDIS_CLOSE
;
3380 redisLog(REDIS_WARNING
,"Syncronization with slave failed");
3384 static int syncWithMaster(void) {
3385 char buf
[1024], tmpfile
[256];
3387 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
3391 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
3395 /* Issue the SYNC command */
3396 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
3398 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
3402 /* Read the bulk write count */
3403 if (syncReadLine(fd
,buf
,1024,5) == -1) {
3405 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
3409 dumpsize
= atoi(buf
+1);
3410 redisLog(REDIS_NOTICE
,"Receiving %d bytes data dump from MASTER",dumpsize
);
3411 /* Read the bulk write data on a temp file */
3412 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
3413 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
,0644);
3416 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
3420 int nread
, nwritten
;
3422 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
3424 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
3430 nwritten
= write(dfd
,buf
,nread
);
3431 if (nwritten
== -1) {
3432 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
3440 if (rename(tmpfile
,server
.dbfilename
) == -1) {
3441 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
3447 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
3448 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
3452 server
.master
= createClient(fd
);
3453 server
.master
->flags
|= REDIS_MASTER
;
3454 server
.replstate
= REDIS_REPL_CONNECTED
;
3458 /* =================================== Main! ================================ */
3460 static void daemonize(void) {
3464 if (fork() != 0) exit(0); /* parent exits */
3465 setsid(); /* create a new session */
3467 /* Every output goes to /dev/null. If Redis is daemonized but
3468 * the 'logfile' is set to 'stdout' in the configuration file
3469 * it will not log at all. */
3470 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
3471 dup2(fd
, STDIN_FILENO
);
3472 dup2(fd
, STDOUT_FILENO
);
3473 dup2(fd
, STDERR_FILENO
);
3474 if (fd
> STDERR_FILENO
) close(fd
);
3476 /* Try to write the pid file */
3477 fp
= fopen(server
.pidfile
,"w");
3479 fprintf(fp
,"%d\n",getpid());
3484 int main(int argc
, char **argv
) {
3487 ResetServerSaveParams();
3488 loadServerConfig(argv
[1]);
3489 } else if (argc
> 2) {
3490 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
3494 if (server
.daemonize
) daemonize();
3495 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
3496 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
3497 redisLog(REDIS_NOTICE
,"DB loaded from disk");
3498 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
3499 acceptHandler
, NULL
, NULL
) == AE_ERR
) oom("creating file event");
3500 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
3502 aeDeleteEventLoop(server
.el
);