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_EXPIRETIME 253
93 #define REDIS_SELECTDB 254
96 /* Defines related to the dump file format. To store 32 bits lengths for short
97 * keys requires a lot of space, so we check the most significant 2 bits of
98 * the first byte to interpreter the length:
100 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
101 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
102 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
103 * 11|000000 this means: specially encoded object will follow. The six bits
104 * number specify the kind of object that follows.
105 * See the REDIS_RDB_ENC_* defines.
107 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
108 * values, will fit inside. */
109 #define REDIS_RDB_6BITLEN 0
110 #define REDIS_RDB_14BITLEN 1
111 #define REDIS_RDB_32BITLEN 2
112 #define REDIS_RDB_ENCVAL 3
113 #define REDIS_RDB_LENERR UINT_MAX
115 /* When a length of a string object stored on disk has the first two bits
116 * set, the remaining two bits specify a special encoding for the object
117 * accordingly to the following defines: */
118 #define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
119 #define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
120 #define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
121 #define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
124 #define REDIS_CLOSE 1 /* This client connection should be closed ASAP */
125 #define REDIS_SLAVE 2 /* This client is a slave server */
126 #define REDIS_MASTER 4 /* This client is a master server */
127 #define REDIS_MONITOR 8 /* This client is a slave monitor, see MONITOR */
129 /* Server replication state */
130 #define REDIS_REPL_NONE 0 /* No active replication */
131 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
132 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
134 /* List related stuff */
138 /* Sort operations */
139 #define REDIS_SORT_GET 0
140 #define REDIS_SORT_DEL 1
141 #define REDIS_SORT_INCR 2
142 #define REDIS_SORT_DECR 3
143 #define REDIS_SORT_ASC 4
144 #define REDIS_SORT_DESC 5
145 #define REDIS_SORTKEY_MAX 1024
148 #define REDIS_DEBUG 0
149 #define REDIS_NOTICE 1
150 #define REDIS_WARNING 2
152 /* Anti-warning macro... */
153 #define REDIS_NOTUSED(V) ((void) V)
155 /*================================= Data types ============================== */
157 /* A redis object, that is a type able to hold a string / list / set */
158 typedef struct redisObject
{
164 typedef struct redisDb
{
170 /* With multiplexing we need to take per-clinet state.
171 * Clients are taken in a liked list. */
172 typedef struct redisClient
{
177 robj
*argv
[REDIS_MAX_ARGS
];
179 int bulklen
; /* bulk read len. -1 if not in bulk read mode */
182 time_t lastinteraction
; /* time of the last interaction, used for timeout */
183 int flags
; /* REDIS_CLOSE | REDIS_SLAVE | REDIS_MONITOR */
184 int slaveseldb
; /* slave selected db, if this client is a slave */
185 int authenticated
; /* when requirepass is non-NULL */
193 /* Global server state structure */
199 unsigned int sharingpoolsize
;
200 long long dirty
; /* changes to DB from the last save */
202 list
*slaves
, *monitors
;
203 char neterr
[ANET_ERR_LEN
];
205 int cronloops
; /* number of times the cron function run */
206 list
*objfreelist
; /* A list of freed objects to avoid malloc() */
207 time_t lastsave
; /* Unix time of last save succeeede */
208 int usedmemory
; /* Used memory in megabytes */
209 /* Fields used only for stats */
210 time_t stat_starttime
; /* server start time */
211 long long stat_numcommands
; /* number of processed commands */
212 long long stat_numconnections
; /* number of connections received */
220 int bgsaveinprogress
;
221 struct saveparam
*saveparams
;
228 /* Replication related */
234 /* Sort parameters - qsort_r() is only available under BSD so we
235 * have to take this state global, in order to pass it to sortCompare() */
241 typedef void redisCommandProc(redisClient
*c
);
242 struct redisCommand
{
244 redisCommandProc
*proc
;
249 typedef struct _redisSortObject
{
257 typedef struct _redisSortOperation
{
260 } redisSortOperation
;
262 struct sharedObjectsStruct
{
263 robj
*crlf
, *ok
, *err
, *emptybulk
, *czero
, *cone
, *pong
, *space
,
264 *colon
, *nullbulk
, *nullmultibulk
,
265 *emptymultibulk
, *wrongtypeerr
, *nokeyerr
, *syntaxerr
, *sameobjecterr
,
266 *outofrangeerr
, *plus
,
267 *select0
, *select1
, *select2
, *select3
, *select4
,
268 *select5
, *select6
, *select7
, *select8
, *select9
;
271 /*================================ Prototypes =============================== */
273 static void freeStringObject(robj
*o
);
274 static void freeListObject(robj
*o
);
275 static void freeSetObject(robj
*o
);
276 static void decrRefCount(void *o
);
277 static robj
*createObject(int type
, void *ptr
);
278 static void freeClient(redisClient
*c
);
279 static int rdbLoad(char *filename
);
280 static void addReply(redisClient
*c
, robj
*obj
);
281 static void addReplySds(redisClient
*c
, sds s
);
282 static void incrRefCount(robj
*o
);
283 static int rdbSaveBackground(char *filename
);
284 static robj
*createStringObject(char *ptr
, size_t len
);
285 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
286 static int syncWithMaster(void);
287 static robj
*tryObjectSharing(robj
*o
);
288 static int removeExpire(redisDb
*db
, robj
*key
);
289 static int expireIfNeeded(redisDb
*db
, robj
*key
);
290 static int deleteIfVolatile(redisDb
*db
, robj
*key
);
291 static int deleteKey(redisDb
*db
, robj
*key
);
292 static time_t getExpire(redisDb
*db
, robj
*key
);
293 static int setExpire(redisDb
*db
, robj
*key
, time_t when
);
295 static void authCommand(redisClient
*c
);
296 static void pingCommand(redisClient
*c
);
297 static void echoCommand(redisClient
*c
);
298 static void setCommand(redisClient
*c
);
299 static void setnxCommand(redisClient
*c
);
300 static void getCommand(redisClient
*c
);
301 static void delCommand(redisClient
*c
);
302 static void existsCommand(redisClient
*c
);
303 static void incrCommand(redisClient
*c
);
304 static void decrCommand(redisClient
*c
);
305 static void incrbyCommand(redisClient
*c
);
306 static void decrbyCommand(redisClient
*c
);
307 static void selectCommand(redisClient
*c
);
308 static void randomkeyCommand(redisClient
*c
);
309 static void keysCommand(redisClient
*c
);
310 static void dbsizeCommand(redisClient
*c
);
311 static void lastsaveCommand(redisClient
*c
);
312 static void saveCommand(redisClient
*c
);
313 static void bgsaveCommand(redisClient
*c
);
314 static void shutdownCommand(redisClient
*c
);
315 static void moveCommand(redisClient
*c
);
316 static void renameCommand(redisClient
*c
);
317 static void renamenxCommand(redisClient
*c
);
318 static void lpushCommand(redisClient
*c
);
319 static void rpushCommand(redisClient
*c
);
320 static void lpopCommand(redisClient
*c
);
321 static void rpopCommand(redisClient
*c
);
322 static void llenCommand(redisClient
*c
);
323 static void lindexCommand(redisClient
*c
);
324 static void lrangeCommand(redisClient
*c
);
325 static void ltrimCommand(redisClient
*c
);
326 static void typeCommand(redisClient
*c
);
327 static void lsetCommand(redisClient
*c
);
328 static void saddCommand(redisClient
*c
);
329 static void sremCommand(redisClient
*c
);
330 static void sismemberCommand(redisClient
*c
);
331 static void scardCommand(redisClient
*c
);
332 static void sinterCommand(redisClient
*c
);
333 static void sinterstoreCommand(redisClient
*c
);
334 static void syncCommand(redisClient
*c
);
335 static void flushdbCommand(redisClient
*c
);
336 static void flushallCommand(redisClient
*c
);
337 static void sortCommand(redisClient
*c
);
338 static void lremCommand(redisClient
*c
);
339 static void infoCommand(redisClient
*c
);
340 static void mgetCommand(redisClient
*c
);
341 static void monitorCommand(redisClient
*c
);
342 static void expireCommand(redisClient
*c
);
344 /*================================= Globals ================================= */
347 static struct redisServer server
; /* server global state */
348 static struct redisCommand cmdTable
[] = {
349 {"get",getCommand
,2,REDIS_CMD_INLINE
},
350 {"set",setCommand
,3,REDIS_CMD_BULK
},
351 {"setnx",setnxCommand
,3,REDIS_CMD_BULK
},
352 {"del",delCommand
,2,REDIS_CMD_INLINE
},
353 {"exists",existsCommand
,2,REDIS_CMD_INLINE
},
354 {"incr",incrCommand
,2,REDIS_CMD_INLINE
},
355 {"decr",decrCommand
,2,REDIS_CMD_INLINE
},
356 {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
},
357 {"rpush",rpushCommand
,3,REDIS_CMD_BULK
},
358 {"lpush",lpushCommand
,3,REDIS_CMD_BULK
},
359 {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
},
360 {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
},
361 {"llen",llenCommand
,2,REDIS_CMD_INLINE
},
362 {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
},
363 {"lset",lsetCommand
,4,REDIS_CMD_BULK
},
364 {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
},
365 {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
},
366 {"lrem",lremCommand
,4,REDIS_CMD_BULK
},
367 {"sadd",saddCommand
,3,REDIS_CMD_BULK
},
368 {"srem",sremCommand
,3,REDIS_CMD_BULK
},
369 {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
},
370 {"scard",scardCommand
,2,REDIS_CMD_INLINE
},
371 {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
},
372 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
},
373 {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
},
374 {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
},
375 {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
},
376 {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
},
377 {"select",selectCommand
,2,REDIS_CMD_INLINE
},
378 {"move",moveCommand
,3,REDIS_CMD_INLINE
},
379 {"rename",renameCommand
,3,REDIS_CMD_INLINE
},
380 {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
},
381 {"keys",keysCommand
,2,REDIS_CMD_INLINE
},
382 {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
},
383 {"auth",authCommand
,2,REDIS_CMD_INLINE
},
384 {"ping",pingCommand
,1,REDIS_CMD_INLINE
},
385 {"echo",echoCommand
,2,REDIS_CMD_BULK
},
386 {"save",saveCommand
,1,REDIS_CMD_INLINE
},
387 {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
},
388 {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
},
389 {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
},
390 {"type",typeCommand
,2,REDIS_CMD_INLINE
},
391 {"sync",syncCommand
,1,REDIS_CMD_INLINE
},
392 {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
},
393 {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
},
394 {"sort",sortCommand
,-2,REDIS_CMD_INLINE
},
395 {"info",infoCommand
,1,REDIS_CMD_INLINE
},
396 {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
},
397 {"expire",expireCommand
,3,REDIS_CMD_INLINE
},
401 /*============================ Utility functions ============================ */
403 /* Glob-style pattern matching. */
404 int stringmatchlen(const char *pattern
, int patternLen
,
405 const char *string
, int stringLen
, int nocase
)
410 while (pattern
[1] == '*') {
415 return 1; /* match */
417 if (stringmatchlen(pattern
+1, patternLen
-1,
418 string
, stringLen
, nocase
))
419 return 1; /* match */
423 return 0; /* no match */
427 return 0; /* no match */
437 not = pattern
[0] == '^';
444 if (pattern
[0] == '\\') {
447 if (pattern
[0] == string
[0])
449 } else if (pattern
[0] == ']') {
451 } else if (patternLen
== 0) {
455 } else if (pattern
[1] == '-' && patternLen
>= 3) {
456 int start
= pattern
[0];
457 int end
= pattern
[2];
465 start
= tolower(start
);
471 if (c
>= start
&& c
<= end
)
475 if (pattern
[0] == string
[0])
478 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
488 return 0; /* no match */
494 if (patternLen
>= 2) {
501 if (pattern
[0] != string
[0])
502 return 0; /* no match */
504 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
505 return 0; /* no match */
513 if (stringLen
== 0) {
514 while(*pattern
== '*') {
521 if (patternLen
== 0 && stringLen
== 0)
526 void redisLog(int level
, const char *fmt
, ...)
531 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
535 if (level
>= server
.verbosity
) {
537 fprintf(fp
,"%c ",c
[level
]);
538 vfprintf(fp
, fmt
, ap
);
544 if (server
.logfile
) fclose(fp
);
547 /*====================== Hash table type implementation ==================== */
549 /* This is an hash table type that uses the SDS dynamic strings libary as
550 * keys and radis objects as values (objects can hold SDS strings,
553 static int sdsDictKeyCompare(void *privdata
, const void *key1
,
557 DICT_NOTUSED(privdata
);
559 l1
= sdslen((sds
)key1
);
560 l2
= sdslen((sds
)key2
);
561 if (l1
!= l2
) return 0;
562 return memcmp(key1
, key2
, l1
) == 0;
565 static void dictRedisObjectDestructor(void *privdata
, void *val
)
567 DICT_NOTUSED(privdata
);
572 static int dictSdsKeyCompare(void *privdata
, const void *key1
,
575 const robj
*o1
= key1
, *o2
= key2
;
576 return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
579 static unsigned int dictSdsHash(const void *key
) {
581 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
584 static dictType setDictType
= {
585 dictSdsHash
, /* hash function */
588 dictSdsKeyCompare
, /* key compare */
589 dictRedisObjectDestructor
, /* key destructor */
590 NULL
/* val destructor */
593 static dictType hashDictType
= {
594 dictSdsHash
, /* hash function */
597 dictSdsKeyCompare
, /* key compare */
598 dictRedisObjectDestructor
, /* key destructor */
599 dictRedisObjectDestructor
/* val destructor */
602 /* ========================= Random utility functions ======================= */
604 /* Redis generally does not try to recover from out of memory conditions
605 * when allocating objects or strings, it is not clear if it will be possible
606 * to report this condition to the client since the networking layer itself
607 * is based on heap allocation for send buffers, so we simply abort.
608 * At least the code will be simpler to read... */
609 static void oom(const char *msg
) {
610 fprintf(stderr
, "%s: Out of memory\n",msg
);
616 /* ====================== Redis server networking stuff ===================== */
617 void closeTimedoutClients(void) {
621 time_t now
= time(NULL
);
623 li
= listGetIterator(server
.clients
,AL_START_HEAD
);
625 while ((ln
= listNextElement(li
)) != NULL
) {
626 c
= listNodeValue(ln
);
627 if (!(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
628 (now
- c
->lastinteraction
> server
.maxidletime
)) {
629 redisLog(REDIS_DEBUG
,"Closing idle client");
633 listReleaseIterator(li
);
636 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
637 int j
, loops
= server
.cronloops
++;
638 REDIS_NOTUSED(eventLoop
);
640 REDIS_NOTUSED(clientData
);
642 /* Update the global state with the amount of used memory */
643 server
.usedmemory
= zmalloc_used_memory();
645 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
646 * we resize the hash table to save memory */
647 for (j
= 0; j
< server
.dbnum
; j
++) {
648 int size
, used
, vkeys
;
650 size
= dictSlots(server
.db
[j
].dict
);
651 used
= dictSize(server
.db
[j
].dict
);
652 vkeys
= dictSize(server
.db
[j
].expires
);
653 if (!(loops
% 5) && used
> 0) {
654 redisLog(REDIS_DEBUG
,"DB %d: %d keys (%d volatile) in %d slots HT.",j
,used
,vkeys
,size
);
655 /* dictPrintStats(server.dict); */
657 if (size
&& used
&& size
> REDIS_HT_MINSLOTS
&&
658 (used
*100/size
< REDIS_HT_MINFILL
)) {
659 redisLog(REDIS_NOTICE
,"The hash table %d is too sparse, resize it...",j
);
660 dictResize(server
.db
[j
].dict
);
661 redisLog(REDIS_NOTICE
,"Hash table %d resized.",j
);
665 /* Show information about connected clients */
667 redisLog(REDIS_DEBUG
,"%d clients connected (%d slaves), %d bytes in use",
668 listLength(server
.clients
)-listLength(server
.slaves
),
669 listLength(server
.slaves
),
671 dictSize(server
.sharingpool
));
674 /* Close connections of timedout clients */
676 closeTimedoutClients();
678 /* Check if a background saving in progress terminated */
679 if (server
.bgsaveinprogress
) {
681 if (wait4(-1,&statloc
,WNOHANG
,NULL
)) {
682 int exitcode
= WEXITSTATUS(statloc
);
684 redisLog(REDIS_NOTICE
,
685 "Background saving terminated with success");
687 server
.lastsave
= time(NULL
);
689 redisLog(REDIS_WARNING
,
690 "Background saving error");
692 server
.bgsaveinprogress
= 0;
695 /* If there is not a background saving in progress check if
696 * we have to save now */
697 time_t now
= time(NULL
);
698 for (j
= 0; j
< server
.saveparamslen
; j
++) {
699 struct saveparam
*sp
= server
.saveparams
+j
;
701 if (server
.dirty
>= sp
->changes
&&
702 now
-server
.lastsave
> sp
->seconds
) {
703 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
704 sp
->changes
, sp
->seconds
);
705 rdbSaveBackground(server
.dbfilename
);
711 /* Try to expire a few timed out keys */
712 for (j
= 0; j
< server
.dbnum
; j
++) {
713 redisDb
*db
= server
.db
+j
;
714 int num
= dictSize(db
->expires
);
717 time_t now
= time(NULL
);
719 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
720 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
725 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
726 t
= (time_t) dictGetEntryVal(de
);
728 deleteKey(db
,dictGetEntryKey(de
));
734 /* Check if we should connect to a MASTER */
735 if (server
.replstate
== REDIS_REPL_CONNECT
) {
736 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
737 if (syncWithMaster() == REDIS_OK
) {
738 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
744 static void createSharedObjects(void) {
745 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
746 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
747 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
748 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
749 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
750 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
751 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
752 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
753 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
755 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
756 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
757 "-ERR Operation against a key holding the wrong kind of value\r\n"));
758 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
759 "-ERR no such key\r\n"));
760 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
761 "-ERR syntax error\r\n"));
762 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
763 "-ERR source and destination objects are the same\r\n"));
764 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
765 "-ERR index out of range\r\n"));
766 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
767 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
768 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
769 shared
.select0
= createStringObject("select 0\r\n",10);
770 shared
.select1
= createStringObject("select 1\r\n",10);
771 shared
.select2
= createStringObject("select 2\r\n",10);
772 shared
.select3
= createStringObject("select 3\r\n",10);
773 shared
.select4
= createStringObject("select 4\r\n",10);
774 shared
.select5
= createStringObject("select 5\r\n",10);
775 shared
.select6
= createStringObject("select 6\r\n",10);
776 shared
.select7
= createStringObject("select 7\r\n",10);
777 shared
.select8
= createStringObject("select 8\r\n",10);
778 shared
.select9
= createStringObject("select 9\r\n",10);
781 static void appendServerSaveParams(time_t seconds
, int changes
) {
782 server
.saveparams
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1));
783 if (server
.saveparams
== NULL
) oom("appendServerSaveParams");
784 server
.saveparams
[server
.saveparamslen
].seconds
= seconds
;
785 server
.saveparams
[server
.saveparamslen
].changes
= changes
;
786 server
.saveparamslen
++;
789 static void ResetServerSaveParams() {
790 zfree(server
.saveparams
);
791 server
.saveparams
= NULL
;
792 server
.saveparamslen
= 0;
795 static void initServerConfig() {
796 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
797 server
.port
= REDIS_SERVERPORT
;
798 server
.verbosity
= REDIS_DEBUG
;
799 server
.maxidletime
= REDIS_MAXIDLETIME
;
800 server
.saveparams
= NULL
;
801 server
.logfile
= NULL
; /* NULL = log on standard output */
802 server
.bindaddr
= NULL
;
803 server
.glueoutputbuf
= 1;
804 server
.daemonize
= 0;
805 server
.pidfile
= "/var/run/redis.pid";
806 server
.dbfilename
= "dump.rdb";
807 server
.requirepass
= NULL
;
808 server
.shareobjects
= 0;
809 ResetServerSaveParams();
811 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
812 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
813 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
814 /* Replication related */
816 server
.masterhost
= NULL
;
817 server
.masterport
= 6379;
818 server
.master
= NULL
;
819 server
.replstate
= REDIS_REPL_NONE
;
822 static void initServer() {
825 signal(SIGHUP
, SIG_IGN
);
826 signal(SIGPIPE
, SIG_IGN
);
828 server
.clients
= listCreate();
829 server
.slaves
= listCreate();
830 server
.monitors
= listCreate();
831 server
.objfreelist
= listCreate();
832 createSharedObjects();
833 server
.el
= aeCreateEventLoop();
834 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
835 server
.sharingpool
= dictCreate(&setDictType
,NULL
);
836 server
.sharingpoolsize
= 1024;
837 if (!server
.db
|| !server
.clients
|| !server
.slaves
|| !server
.monitors
|| !server
.el
|| !server
.objfreelist
)
838 oom("server initialization"); /* Fatal OOM */
839 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
840 if (server
.fd
== -1) {
841 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
844 for (j
= 0; j
< server
.dbnum
; j
++) {
845 server
.db
[j
].dict
= dictCreate(&hashDictType
,NULL
);
846 server
.db
[j
].expires
= dictCreate(&setDictType
,NULL
);
849 server
.cronloops
= 0;
850 server
.bgsaveinprogress
= 0;
851 server
.lastsave
= time(NULL
);
853 server
.usedmemory
= 0;
854 server
.stat_numcommands
= 0;
855 server
.stat_numconnections
= 0;
856 server
.stat_starttime
= time(NULL
);
857 aeCreateTimeEvent(server
.el
, 1000, serverCron
, NULL
, NULL
);
860 /* Empty the whole database */
861 static void emptyDb() {
864 for (j
= 0; j
< server
.dbnum
; j
++) {
865 dictEmpty(server
.db
[j
].dict
);
866 dictEmpty(server
.db
[j
].expires
);
870 /* I agree, this is a very rudimental way to load a configuration...
871 will improve later if the config gets more complex */
872 static void loadServerConfig(char *filename
) {
873 FILE *fp
= fopen(filename
,"r");
874 char buf
[REDIS_CONFIGLINE_MAX
+1], *err
= NULL
;
879 redisLog(REDIS_WARNING
,"Fatal error, can't open config file");
882 while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) {
888 line
= sdstrim(line
," \t\r\n");
890 /* Skip comments and blank lines*/
891 if (line
[0] == '#' || line
[0] == '\0') {
896 /* Split into arguments */
897 argv
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
);
900 /* Execute config directives */
901 if (!strcmp(argv
[0],"timeout") && argc
== 2) {
902 server
.maxidletime
= atoi(argv
[1]);
903 if (server
.maxidletime
< 1) {
904 err
= "Invalid timeout value"; goto loaderr
;
906 } else if (!strcmp(argv
[0],"port") && argc
== 2) {
907 server
.port
= atoi(argv
[1]);
908 if (server
.port
< 1 || server
.port
> 65535) {
909 err
= "Invalid port"; goto loaderr
;
911 } else if (!strcmp(argv
[0],"bind") && argc
== 2) {
912 server
.bindaddr
= zstrdup(argv
[1]);
913 } else if (!strcmp(argv
[0],"save") && argc
== 3) {
914 int seconds
= atoi(argv
[1]);
915 int changes
= atoi(argv
[2]);
916 if (seconds
< 1 || changes
< 0) {
917 err
= "Invalid save parameters"; goto loaderr
;
919 appendServerSaveParams(seconds
,changes
);
920 } else if (!strcmp(argv
[0],"dir") && argc
== 2) {
921 if (chdir(argv
[1]) == -1) {
922 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s",
923 argv
[1], strerror(errno
));
926 } else if (!strcmp(argv
[0],"loglevel") && argc
== 2) {
927 if (!strcmp(argv
[1],"debug")) server
.verbosity
= REDIS_DEBUG
;
928 else if (!strcmp(argv
[1],"notice")) server
.verbosity
= REDIS_NOTICE
;
929 else if (!strcmp(argv
[1],"warning")) server
.verbosity
= REDIS_WARNING
;
931 err
= "Invalid log level. Must be one of debug, notice, warning";
934 } else if (!strcmp(argv
[0],"logfile") && argc
== 2) {
937 server
.logfile
= zstrdup(argv
[1]);
938 if (!strcmp(server
.logfile
,"stdout")) {
939 zfree(server
.logfile
);
940 server
.logfile
= NULL
;
942 if (server
.logfile
) {
943 /* Test if we are able to open the file. The server will not
944 * be able to abort just for this problem later... */
945 fp
= fopen(server
.logfile
,"a");
947 err
= sdscatprintf(sdsempty(),
948 "Can't open the log file: %s", strerror(errno
));
953 } else if (!strcmp(argv
[0],"databases") && argc
== 2) {
954 server
.dbnum
= atoi(argv
[1]);
955 if (server
.dbnum
< 1) {
956 err
= "Invalid number of databases"; goto loaderr
;
958 } else if (!strcmp(argv
[0],"slaveof") && argc
== 3) {
959 server
.masterhost
= sdsnew(argv
[1]);
960 server
.masterport
= atoi(argv
[2]);
961 server
.replstate
= REDIS_REPL_CONNECT
;
962 } else if (!strcmp(argv
[0],"glueoutputbuf") && argc
== 2) {
964 if (!strcmp(argv
[1],"yes")) server
.glueoutputbuf
= 1;
965 else if (!strcmp(argv
[1],"no")) server
.glueoutputbuf
= 0;
967 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
969 } else if (!strcmp(argv
[0],"shareobjects") && argc
== 2) {
971 if (!strcmp(argv
[1],"yes")) server
.shareobjects
= 1;
972 else if (!strcmp(argv
[1],"no")) server
.shareobjects
= 0;
974 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
976 } else if (!strcmp(argv
[0],"daemonize") && argc
== 2) {
978 if (!strcmp(argv
[1],"yes")) server
.daemonize
= 1;
979 else if (!strcmp(argv
[1],"no")) server
.daemonize
= 0;
981 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
983 } else if (!strcmp(argv
[0],"requirepass") && argc
== 2) {
984 server
.requirepass
= zstrdup(argv
[1]);
985 } else if (!strcmp(argv
[0],"pidfile") && argc
== 2) {
986 server
.pidfile
= zstrdup(argv
[1]);
988 err
= "Bad directive or wrong number of arguments"; goto loaderr
;
990 for (j
= 0; j
< argc
; j
++)
999 fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n");
1000 fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
);
1001 fprintf(stderr
, ">>> '%s'\n", line
);
1002 fprintf(stderr
, "%s\n", err
);
1006 static void freeClientArgv(redisClient
*c
) {
1009 for (j
= 0; j
< c
->argc
; j
++)
1010 decrRefCount(c
->argv
[j
]);
1014 static void freeClient(redisClient
*c
) {
1017 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
1018 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1019 sdsfree(c
->querybuf
);
1020 listRelease(c
->reply
);
1023 ln
= listSearchKey(server
.clients
,c
);
1025 listDelNode(server
.clients
,ln
);
1026 if (c
->flags
& REDIS_SLAVE
) {
1027 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
1028 ln
= listSearchKey(l
,c
);
1032 if (c
->flags
& REDIS_MASTER
) {
1033 server
.master
= NULL
;
1034 server
.replstate
= REDIS_REPL_CONNECT
;
1039 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
1041 listNode
*ln
= c
->reply
->head
, *next
;
1046 totlen
+= sdslen(o
->ptr
);
1048 /* This optimization makes more sense if we don't have to copy
1050 if (totlen
> 1024) return;
1056 ln
= c
->reply
->head
;
1060 memcpy(buf
+copylen
,o
->ptr
,sdslen(o
->ptr
));
1061 copylen
+= sdslen(o
->ptr
);
1062 listDelNode(c
->reply
,ln
);
1065 /* Now the output buffer is empty, add the new single element */
1066 addReplySds(c
,sdsnewlen(buf
,totlen
));
1070 static void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1071 redisClient
*c
= privdata
;
1072 int nwritten
= 0, totwritten
= 0, objlen
;
1075 REDIS_NOTUSED(mask
);
1077 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
1078 glueReplyBuffersIfNeeded(c
);
1079 while(listLength(c
->reply
)) {
1080 o
= listNodeValue(listFirst(c
->reply
));
1081 objlen
= sdslen(o
->ptr
);
1084 listDelNode(c
->reply
,listFirst(c
->reply
));
1088 if (c
->flags
& REDIS_MASTER
) {
1089 nwritten
= objlen
- c
->sentlen
;
1091 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen
- c
->sentlen
);
1092 if (nwritten
<= 0) break;
1094 c
->sentlen
+= nwritten
;
1095 totwritten
+= nwritten
;
1096 /* If we fully sent the object on head go to the next one */
1097 if (c
->sentlen
== objlen
) {
1098 listDelNode(c
->reply
,listFirst(c
->reply
));
1102 if (nwritten
== -1) {
1103 if (errno
== EAGAIN
) {
1106 redisLog(REDIS_DEBUG
,
1107 "Error writing to client: %s", strerror(errno
));
1112 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
1113 if (listLength(c
->reply
) == 0) {
1115 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1119 static struct redisCommand
*lookupCommand(char *name
) {
1121 while(cmdTable
[j
].name
!= NULL
) {
1122 if (!strcmp(name
,cmdTable
[j
].name
)) return &cmdTable
[j
];
1128 /* resetClient prepare the client to process the next command */
1129 static void resetClient(redisClient
*c
) {
1134 /* If this function gets called we already read a whole
1135 * command, argments are in the client argv/argc fields.
1136 * processCommand() execute the command or prepare the
1137 * server for a bulk read from the client.
1139 * If 1 is returned the client is still alive and valid and
1140 * and other operations can be performed by the caller. Otherwise
1141 * if 0 is returned the client was destroied (i.e. after QUIT). */
1142 static int processCommand(redisClient
*c
) {
1143 struct redisCommand
*cmd
;
1146 sdstolower(c
->argv
[0]->ptr
);
1147 /* The QUIT command is handled as a special case. Normal command
1148 * procs are unable to close the client connection safely */
1149 if (!strcmp(c
->argv
[0]->ptr
,"quit")) {
1153 cmd
= lookupCommand(c
->argv
[0]->ptr
);
1155 addReplySds(c
,sdsnew("-ERR unknown command\r\n"));
1158 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
1159 (c
->argc
< -cmd
->arity
)) {
1160 addReplySds(c
,sdsnew("-ERR wrong number of arguments\r\n"));
1163 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
1164 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
1166 decrRefCount(c
->argv
[c
->argc
-1]);
1167 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
1169 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
1174 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
1175 /* It is possible that the bulk read is already in the
1176 * buffer. Check this condition and handle it accordingly */
1177 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
1178 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
1180 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
1185 /* Let's try to share objects on the command arguments vector */
1186 if (server
.shareobjects
) {
1188 for(j
= 1; j
< c
->argc
; j
++)
1189 c
->argv
[j
] = tryObjectSharing(c
->argv
[j
]);
1191 /* Check if the user is authenticated */
1192 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
1193 addReplySds(c
,sdsnew("-ERR operation not permitted\r\n"));
1198 /* Exec the command */
1199 dirty
= server
.dirty
;
1201 if (server
.dirty
-dirty
!= 0 && listLength(server
.slaves
))
1202 replicationFeedSlaves(server
.slaves
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1203 if (listLength(server
.monitors
))
1204 replicationFeedSlaves(server
.monitors
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1205 server
.stat_numcommands
++;
1207 /* Prepare the client for the next command */
1208 if (c
->flags
& REDIS_CLOSE
) {
1216 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
1217 listNode
*ln
= slaves
->head
;
1218 robj
*outv
[REDIS_MAX_ARGS
*4]; /* enough room for args, spaces, newlines */
1221 for (j
= 0; j
< argc
; j
++) {
1222 if (j
!= 0) outv
[outc
++] = shared
.space
;
1223 if ((cmd
->flags
& REDIS_CMD_BULK
) && j
== argc
-1) {
1226 lenobj
= createObject(REDIS_STRING
,
1227 sdscatprintf(sdsempty(),"%d\r\n",sdslen(argv
[j
]->ptr
)));
1228 lenobj
->refcount
= 0;
1229 outv
[outc
++] = lenobj
;
1231 outv
[outc
++] = argv
[j
];
1233 outv
[outc
++] = shared
.crlf
;
1236 redisClient
*slave
= ln
->value
;
1237 if (slave
->slaveseldb
!= dictid
) {
1241 case 0: selectcmd
= shared
.select0
; break;
1242 case 1: selectcmd
= shared
.select1
; break;
1243 case 2: selectcmd
= shared
.select2
; break;
1244 case 3: selectcmd
= shared
.select3
; break;
1245 case 4: selectcmd
= shared
.select4
; break;
1246 case 5: selectcmd
= shared
.select5
; break;
1247 case 6: selectcmd
= shared
.select6
; break;
1248 case 7: selectcmd
= shared
.select7
; break;
1249 case 8: selectcmd
= shared
.select8
; break;
1250 case 9: selectcmd
= shared
.select9
; break;
1252 selectcmd
= createObject(REDIS_STRING
,
1253 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
1254 selectcmd
->refcount
= 0;
1257 addReply(slave
,selectcmd
);
1258 slave
->slaveseldb
= dictid
;
1260 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
1265 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1266 redisClient
*c
= (redisClient
*) privdata
;
1267 char buf
[REDIS_QUERYBUF_LEN
];
1270 REDIS_NOTUSED(mask
);
1272 nread
= read(fd
, buf
, REDIS_QUERYBUF_LEN
);
1274 if (errno
== EAGAIN
) {
1277 redisLog(REDIS_DEBUG
, "Reading from client: %s",strerror(errno
));
1281 } else if (nread
== 0) {
1282 redisLog(REDIS_DEBUG
, "Client closed connection");
1287 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
1288 c
->lastinteraction
= time(NULL
);
1294 if (c
->bulklen
== -1) {
1295 /* Read the first line of the query */
1296 char *p
= strchr(c
->querybuf
,'\n');
1302 query
= c
->querybuf
;
1303 c
->querybuf
= sdsempty();
1304 querylen
= 1+(p
-(query
));
1305 if (sdslen(query
) > querylen
) {
1306 /* leave data after the first line of the query in the buffer */
1307 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
1309 *p
= '\0'; /* remove "\n" */
1310 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
1311 sdsupdatelen(query
);
1313 /* Now we can split the query in arguments */
1314 if (sdslen(query
) == 0) {
1315 /* Ignore empty query */
1319 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
1321 if (argv
== NULL
) oom("sdssplitlen");
1322 for (j
= 0; j
< argc
&& j
< REDIS_MAX_ARGS
; j
++) {
1323 if (sdslen(argv
[j
])) {
1324 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
1331 /* Execute the command. If the client is still valid
1332 * after processCommand() return and there is something
1333 * on the query buffer try to process the next command. */
1334 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
1336 } else if (sdslen(c
->querybuf
) >= 1024) {
1337 redisLog(REDIS_DEBUG
, "Client protocol error");
1342 /* Bulk read handling. Note that if we are at this point
1343 the client already sent a command terminated with a newline,
1344 we are reading the bulk data that is actually the last
1345 argument of the command. */
1346 int qbl
= sdslen(c
->querybuf
);
1348 if (c
->bulklen
<= qbl
) {
1349 /* Copy everything but the final CRLF as final argument */
1350 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
1352 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
1359 static int selectDb(redisClient
*c
, int id
) {
1360 if (id
< 0 || id
>= server
.dbnum
)
1362 c
->db
= &server
.db
[id
];
1366 static redisClient
*createClient(int fd
) {
1367 redisClient
*c
= zmalloc(sizeof(*c
));
1369 anetNonBlock(NULL
,fd
);
1370 anetTcpNoDelay(NULL
,fd
);
1371 if (!c
) return NULL
;
1374 c
->querybuf
= sdsempty();
1379 c
->lastinteraction
= time(NULL
);
1380 c
->authenticated
= 0;
1381 if ((c
->reply
= listCreate()) == NULL
) oom("listCreate");
1382 listSetFreeMethod(c
->reply
,decrRefCount
);
1383 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
1384 readQueryFromClient
, c
, NULL
) == AE_ERR
) {
1388 if (!listAddNodeTail(server
.clients
,c
)) oom("listAddNodeTail");
1392 static void addReply(redisClient
*c
, robj
*obj
) {
1393 if (listLength(c
->reply
) == 0 &&
1394 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
1395 sendReplyToClient
, c
, NULL
) == AE_ERR
) return;
1396 if (!listAddNodeTail(c
->reply
,obj
)) oom("listAddNodeTail");
1400 static void addReplySds(redisClient
*c
, sds s
) {
1401 robj
*o
= createObject(REDIS_STRING
,s
);
1406 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1410 REDIS_NOTUSED(mask
);
1411 REDIS_NOTUSED(privdata
);
1413 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
1414 if (cfd
== AE_ERR
) {
1415 redisLog(REDIS_DEBUG
,"Accepting client connection: %s", server
.neterr
);
1418 redisLog(REDIS_DEBUG
,"Accepted %s:%d", cip
, cport
);
1419 if (createClient(cfd
) == NULL
) {
1420 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
1421 close(cfd
); /* May be already closed, just ingore errors */
1424 server
.stat_numconnections
++;
1427 /* ======================= Redis objects implementation ===================== */
1429 static robj
*createObject(int type
, void *ptr
) {
1432 if (listLength(server
.objfreelist
)) {
1433 listNode
*head
= listFirst(server
.objfreelist
);
1434 o
= listNodeValue(head
);
1435 listDelNode(server
.objfreelist
,head
);
1437 o
= zmalloc(sizeof(*o
));
1439 if (!o
) oom("createObject");
1446 static robj
*createStringObject(char *ptr
, size_t len
) {
1447 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
1450 static robj
*createListObject(void) {
1451 list
*l
= listCreate();
1453 if (!l
) oom("listCreate");
1454 listSetFreeMethod(l
,decrRefCount
);
1455 return createObject(REDIS_LIST
,l
);
1458 static robj
*createSetObject(void) {
1459 dict
*d
= dictCreate(&setDictType
,NULL
);
1460 if (!d
) oom("dictCreate");
1461 return createObject(REDIS_SET
,d
);
1464 static void freeStringObject(robj
*o
) {
1468 static void freeListObject(robj
*o
) {
1469 listRelease((list
*) o
->ptr
);
1472 static void freeSetObject(robj
*o
) {
1473 dictRelease((dict
*) o
->ptr
);
1476 static void freeHashObject(robj
*o
) {
1477 dictRelease((dict
*) o
->ptr
);
1480 static void incrRefCount(robj
*o
) {
1482 #ifdef DEBUG_REFCOUNT
1483 if (o
->type
== REDIS_STRING
)
1484 printf("Increment '%s'(%p), now is: %d\n",o
->ptr
,o
,o
->refcount
);
1488 static void decrRefCount(void *obj
) {
1491 #ifdef DEBUG_REFCOUNT
1492 if (o
->type
== REDIS_STRING
)
1493 printf("Decrement '%s'(%p), now is: %d\n",o
->ptr
,o
,o
->refcount
-1);
1495 if (--(o
->refcount
) == 0) {
1497 case REDIS_STRING
: freeStringObject(o
); break;
1498 case REDIS_LIST
: freeListObject(o
); break;
1499 case REDIS_SET
: freeSetObject(o
); break;
1500 case REDIS_HASH
: freeHashObject(o
); break;
1501 default: assert(0 != 0); break;
1503 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
1504 !listAddNodeHead(server
.objfreelist
,o
))
1509 /* Try to share an object against the shared objects pool */
1510 static robj
*tryObjectSharing(robj
*o
) {
1511 struct dictEntry
*de
;
1514 if (o
== NULL
|| server
.shareobjects
== 0) return o
;
1516 assert(o
->type
== REDIS_STRING
);
1517 de
= dictFind(server
.sharingpool
,o
);
1519 robj
*shared
= dictGetEntryKey(de
);
1521 c
= ((unsigned long) dictGetEntryVal(de
))+1;
1522 dictGetEntryVal(de
) = (void*) c
;
1523 incrRefCount(shared
);
1527 /* Here we are using a stream algorihtm: Every time an object is
1528 * shared we increment its count, everytime there is a miss we
1529 * recrement the counter of a random object. If this object reaches
1530 * zero we remove the object and put the current object instead. */
1531 if (dictSize(server
.sharingpool
) >=
1532 server
.sharingpoolsize
) {
1533 de
= dictGetRandomKey(server
.sharingpool
);
1535 c
= ((unsigned long) dictGetEntryVal(de
))-1;
1536 dictGetEntryVal(de
) = (void*) c
;
1538 dictDelete(server
.sharingpool
,de
->key
);
1541 c
= 0; /* If the pool is empty we want to add this object */
1546 retval
= dictAdd(server
.sharingpool
,o
,(void*)1);
1547 assert(retval
== DICT_OK
);
1554 static robj
*lookupKey(redisDb
*db
, robj
*key
) {
1555 dictEntry
*de
= dictFind(db
->dict
,key
);
1556 return de
? dictGetEntryVal(de
) : NULL
;
1559 static robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
1560 expireIfNeeded(db
,key
);
1561 return lookupKey(db
,key
);
1564 static robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
1565 deleteIfVolatile(db
,key
);
1566 return lookupKey(db
,key
);
1569 static int deleteKey(redisDb
*db
, robj
*key
) {
1572 /* We need to protect key from destruction: after the first dictDelete()
1573 * it may happen that 'key' is no longer valid if we don't increment
1574 * it's count. This may happen when we get the object reference directly
1575 * from the hash table with dictRandomKey() or dict iterators */
1577 if (dictSize(db
->expires
)) dictDelete(db
->expires
,key
);
1578 retval
= dictDelete(db
->dict
,key
);
1581 return retval
== DICT_OK
;
1584 /*============================ DB saving/loading ============================ */
1586 static int rdbSaveType(FILE *fp
, unsigned char type
) {
1587 if (fwrite(&type
,1,1,fp
) == 0) return -1;
1591 static int rdbSaveTime(FILE *fp
, time_t t
) {
1592 int32_t t32
= (int32_t) t
;
1593 if (fwrite(&t32
,4,1,fp
) == 0) return -1;
1597 /* check rdbLoadLen() comments for more info */
1598 static int rdbSaveLen(FILE *fp
, uint32_t len
) {
1599 unsigned char buf
[2];
1602 /* Save a 6 bit len */
1603 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
1604 if (fwrite(buf
,1,1,fp
) == 0) return -1;
1605 } else if (len
< (1<<14)) {
1606 /* Save a 14 bit len */
1607 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
1609 if (fwrite(buf
,2,1,fp
) == 0) return -1;
1611 /* Save a 32 bit len */
1612 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
1613 if (fwrite(buf
,1,1,fp
) == 0) return -1;
1615 if (fwrite(&len
,4,1,fp
) == 0) return -1;
1620 /* String objects in the form "2391" "-100" without any space and with a
1621 * range of values that can fit in an 8, 16 or 32 bit signed value can be
1622 * encoded as integers to save space */
1623 int rdbTryIntegerEncoding(sds s
, unsigned char *enc
) {
1625 char *endptr
, buf
[32];
1627 /* Check if it's possible to encode this value as a number */
1628 value
= strtoll(s
, &endptr
, 10);
1629 if (endptr
[0] != '\0') return 0;
1630 snprintf(buf
,32,"%lld",value
);
1632 /* If the number converted back into a string is not identical
1633 * then it's not possible to encode the string as integer */
1634 if (strlen(buf
) != sdslen(s
) || memcmp(buf
,s
,sdslen(s
))) return 0;
1636 /* Finally check if it fits in our ranges */
1637 if (value
>= -(1<<7) && value
<= (1<<7)-1) {
1638 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT8
;
1639 enc
[1] = value
&0xFF;
1641 } else if (value
>= -(1<<15) && value
<= (1<<15)-1) {
1642 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
;
1643 enc
[1] = value
&0xFF;
1644 enc
[2] = (value
>>8)&0xFF;
1646 } else if (value
>= -((long long)1<<31) && value
<= ((long long)1<<31)-1) {
1647 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT32
;
1648 enc
[1] = value
&0xFF;
1649 enc
[2] = (value
>>8)&0xFF;
1650 enc
[3] = (value
>>16)&0xFF;
1651 enc
[4] = (value
>>24)&0xFF;
1658 static int rdbSaveLzfStringObject(FILE *fp
, robj
*obj
) {
1659 unsigned int comprlen
, outlen
;
1663 /* We require at least four bytes compression for this to be worth it */
1664 outlen
= sdslen(obj
->ptr
)-4;
1665 if (outlen
<= 0) return 0;
1666 if ((out
= zmalloc(outlen
)) == NULL
) return 0;
1667 comprlen
= lzf_compress(obj
->ptr
, sdslen(obj
->ptr
), out
, outlen
);
1668 if (comprlen
== 0) {
1672 /* Data compressed! Let's save it on disk */
1673 byte
= (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_LZF
;
1674 if (fwrite(&byte
,1,1,fp
) == 0) goto writeerr
;
1675 if (rdbSaveLen(fp
,comprlen
) == -1) goto writeerr
;
1676 if (rdbSaveLen(fp
,sdslen(obj
->ptr
)) == -1) goto writeerr
;
1677 if (fwrite(out
,comprlen
,1,fp
) == 0) goto writeerr
;
1686 /* Save a string objet as [len][data] on disk. If the object is a string
1687 * representation of an integer value we try to safe it in a special form */
1688 static int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
1689 size_t len
= sdslen(obj
->ptr
);
1692 /* Try integer encoding */
1694 unsigned char buf
[5];
1695 if ((enclen
= rdbTryIntegerEncoding(obj
->ptr
,buf
)) > 0) {
1696 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
1701 /* Try LZF compression - under 20 bytes it's unable to compress even
1702 * aaaaaaaaaaaaaaaaaa so skip it */
1706 retval
= rdbSaveLzfStringObject(fp
,obj
);
1707 if (retval
== -1) return -1;
1708 if (retval
> 0) return 0;
1709 /* retval == 0 means data can't be compressed, save the old way */
1712 /* Store verbatim */
1713 if (rdbSaveLen(fp
,len
) == -1) return -1;
1714 if (len
&& fwrite(obj
->ptr
,len
,1,fp
) == 0) return -1;
1718 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
1719 static int rdbSave(char *filename
) {
1720 dictIterator
*di
= NULL
;
1725 time_t now
= time(NULL
);
1727 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
1728 fp
= fopen(tmpfile
,"w");
1730 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
1733 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
1734 for (j
= 0; j
< server
.dbnum
; j
++) {
1735 redisDb
*db
= server
.db
+j
;
1737 if (dictSize(d
) == 0) continue;
1738 di
= dictGetIterator(d
);
1744 /* Write the SELECT DB opcode */
1745 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
1746 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
1748 /* Iterate this DB writing every entry */
1749 while((de
= dictNext(di
)) != NULL
) {
1750 robj
*key
= dictGetEntryKey(de
);
1751 robj
*o
= dictGetEntryVal(de
);
1752 time_t expiretime
= getExpire(db
,key
);
1754 /* Save the expire time */
1755 if (expiretime
!= -1) {
1756 /* If this key is already expired skip it */
1757 if (expiretime
< now
) continue;
1758 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
;
1759 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
;
1761 /* Save the key and associated value */
1762 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
1763 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
1764 if (o
->type
== REDIS_STRING
) {
1765 /* Save a string value */
1766 if (rdbSaveStringObject(fp
,o
) == -1) goto werr
;
1767 } else if (o
->type
== REDIS_LIST
) {
1768 /* Save a list value */
1769 list
*list
= o
->ptr
;
1770 listNode
*ln
= list
->head
;
1772 if (rdbSaveLen(fp
,listLength(list
)) == -1) goto werr
;
1774 robj
*eleobj
= listNodeValue(ln
);
1776 if (rdbSaveStringObject(fp
,eleobj
) == -1) goto werr
;
1779 } else if (o
->type
== REDIS_SET
) {
1780 /* Save a set value */
1782 dictIterator
*di
= dictGetIterator(set
);
1785 if (!set
) oom("dictGetIteraotr");
1786 if (rdbSaveLen(fp
,dictSize(set
)) == -1) goto werr
;
1787 while((de
= dictNext(di
)) != NULL
) {
1788 robj
*eleobj
= dictGetEntryKey(de
);
1790 if (rdbSaveStringObject(fp
,eleobj
) == -1) goto werr
;
1792 dictReleaseIterator(di
);
1797 dictReleaseIterator(di
);
1800 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
1802 /* Make sure data will not remain on the OS's output buffers */
1807 /* Use RENAME to make sure the DB file is changed atomically only
1808 * if the generate DB file is ok. */
1809 if (rename(tmpfile
,filename
) == -1) {
1810 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destionation: %s", strerror(errno
));
1814 redisLog(REDIS_NOTICE
,"DB saved on disk");
1816 server
.lastsave
= time(NULL
);
1822 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
1823 if (di
) dictReleaseIterator(di
);
1827 static int rdbSaveBackground(char *filename
) {
1830 if (server
.bgsaveinprogress
) return REDIS_ERR
;
1831 if ((childpid
= fork()) == 0) {
1834 if (rdbSave(filename
) == REDIS_OK
) {
1841 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
1842 server
.bgsaveinprogress
= 1;
1845 return REDIS_OK
; /* unreached */
1848 static int rdbLoadType(FILE *fp
) {
1850 if (fread(&type
,1,1,fp
) == 0) return -1;
1854 static time_t rdbLoadTime(FILE *fp
) {
1856 if (fread(&t32
,4,1,fp
) == 0) return -1;
1857 return (time_t) t32
;
1860 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
1861 * of this file for a description of how this are stored on disk.
1863 * isencoded is set to 1 if the readed length is not actually a length but
1864 * an "encoding type", check the above comments for more info */
1865 static uint32_t rdbLoadLen(FILE *fp
, int rdbver
, int *isencoded
) {
1866 unsigned char buf
[2];
1869 if (isencoded
) *isencoded
= 0;
1871 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
1876 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
1877 type
= (buf
[0]&0xC0)>>6;
1878 if (type
== REDIS_RDB_6BITLEN
) {
1879 /* Read a 6 bit len */
1881 } else if (type
== REDIS_RDB_ENCVAL
) {
1882 /* Read a 6 bit len encoding type */
1883 if (isencoded
) *isencoded
= 1;
1885 } else if (type
== REDIS_RDB_14BITLEN
) {
1886 /* Read a 14 bit len */
1887 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
1888 return ((buf
[0]&0x3F)<<8)|buf
[1];
1890 /* Read a 32 bit len */
1891 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
1897 static robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
) {
1898 unsigned char enc
[4];
1901 if (enctype
== REDIS_RDB_ENC_INT8
) {
1902 if (fread(enc
,1,1,fp
) == 0) return NULL
;
1903 val
= (signed char)enc
[0];
1904 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
1906 if (fread(enc
,2,1,fp
) == 0) return NULL
;
1907 v
= enc
[0]|(enc
[1]<<8);
1909 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
1911 if (fread(enc
,4,1,fp
) == 0) return NULL
;
1912 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
1915 val
= 0; /* anti-warning */
1918 return createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",val
));
1921 static robj
*rdbLoadLzfStringObject(FILE*fp
, int rdbver
) {
1922 unsigned int len
, clen
;
1923 unsigned char *c
= NULL
;
1926 if ((clen
= rdbLoadLen(fp
,rdbver
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
1927 if ((len
= rdbLoadLen(fp
,rdbver
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
1928 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
1929 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
1930 if (fread(c
,clen
,1,fp
) == 0) goto err
;
1931 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
1932 return createObject(REDIS_STRING
,val
);
1939 static robj
*rdbLoadStringObject(FILE*fp
, int rdbver
) {
1944 len
= rdbLoadLen(fp
,rdbver
,&isencoded
);
1947 case REDIS_RDB_ENC_INT8
:
1948 case REDIS_RDB_ENC_INT16
:
1949 case REDIS_RDB_ENC_INT32
:
1950 return tryObjectSharing(rdbLoadIntegerObject(fp
,len
));
1951 case REDIS_RDB_ENC_LZF
:
1952 return tryObjectSharing(rdbLoadLzfStringObject(fp
,rdbver
));
1958 if (len
== REDIS_RDB_LENERR
) return NULL
;
1959 val
= sdsnewlen(NULL
,len
);
1960 if (len
&& fread(val
,len
,1,fp
) == 0) {
1964 return tryObjectSharing(createObject(REDIS_STRING
,val
));
1967 static int rdbLoad(char *filename
) {
1969 robj
*keyobj
= NULL
;
1971 int type
, retval
, rdbver
;
1972 dict
*d
= server
.db
[0].dict
;
1973 redisDb
*db
= server
.db
+0;
1975 time_t expiretime
= -1, now
= time(NULL
);
1977 fp
= fopen(filename
,"r");
1978 if (!fp
) return REDIS_ERR
;
1979 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
1981 if (memcmp(buf
,"REDIS",5) != 0) {
1983 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
1986 rdbver
= atoi(buf
+5);
1989 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
1996 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
1997 if (type
== REDIS_EXPIRETIME
) {
1998 if ((expiretime
= rdbLoadTime(fp
)) == -1) goto eoferr
;
1999 /* We read the time so we need to read the object type again */
2000 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
2002 if (type
== REDIS_EOF
) break;
2003 /* Handle SELECT DB opcode as a special case */
2004 if (type
== REDIS_SELECTDB
) {
2005 if ((dbid
= rdbLoadLen(fp
,rdbver
,NULL
)) == REDIS_RDB_LENERR
)
2007 if (dbid
>= (unsigned)server
.dbnum
) {
2008 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
2011 db
= server
.db
+dbid
;
2016 if ((keyobj
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
2018 if (type
== REDIS_STRING
) {
2019 /* Read string value */
2020 if ((o
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
2021 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
2022 /* Read list/set value */
2025 if ((listlen
= rdbLoadLen(fp
,rdbver
,NULL
)) == REDIS_RDB_LENERR
)
2027 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
2028 /* Load every single element of the list/set */
2032 if ((ele
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
2033 if (type
== REDIS_LIST
) {
2034 if (!listAddNodeTail((list
*)o
->ptr
,ele
))
2035 oom("listAddNodeTail");
2037 if (dictAdd((dict
*)o
->ptr
,ele
,NULL
) == DICT_ERR
)
2044 /* Add the new object in the hash table */
2045 retval
= dictAdd(d
,keyobj
,o
);
2046 if (retval
== DICT_ERR
) {
2047 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj
->ptr
);
2050 /* Set the expire time if needed */
2051 if (expiretime
!= -1) {
2052 setExpire(db
,keyobj
,expiretime
);
2053 /* Delete this key if already expired */
2054 if (expiretime
< now
) deleteKey(db
,keyobj
);
2062 eoferr
: /* unexpected end of file is handled here with a fatal exit */
2063 if (keyobj
) decrRefCount(keyobj
);
2064 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, exiting now.");
2066 return REDIS_ERR
; /* Just to avoid warning */
2069 /*================================== Commands =============================== */
2071 static void authCommand(redisClient
*c
) {
2072 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
2073 c
->authenticated
= 1;
2074 addReply(c
,shared
.ok
);
2076 c
->authenticated
= 0;
2077 addReply(c
,shared
.err
);
2081 static void pingCommand(redisClient
*c
) {
2082 addReply(c
,shared
.pong
);
2085 static void echoCommand(redisClient
*c
) {
2086 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
2087 (int)sdslen(c
->argv
[1]->ptr
)));
2088 addReply(c
,c
->argv
[1]);
2089 addReply(c
,shared
.crlf
);
2092 /*=================================== Strings =============================== */
2094 static void setGenericCommand(redisClient
*c
, int nx
) {
2097 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
2098 if (retval
== DICT_ERR
) {
2100 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
2101 incrRefCount(c
->argv
[2]);
2103 addReply(c
,shared
.czero
);
2107 incrRefCount(c
->argv
[1]);
2108 incrRefCount(c
->argv
[2]);
2111 removeExpire(c
->db
,c
->argv
[1]);
2112 addReply(c
, nx
? shared
.cone
: shared
.ok
);
2115 static void setCommand(redisClient
*c
) {
2116 setGenericCommand(c
,0);
2119 static void setnxCommand(redisClient
*c
) {
2120 setGenericCommand(c
,1);
2123 static void getCommand(redisClient
*c
) {
2124 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[1]);
2127 addReply(c
,shared
.nullbulk
);
2129 if (o
->type
!= REDIS_STRING
) {
2130 addReply(c
,shared
.wrongtypeerr
);
2132 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(o
->ptr
)));
2134 addReply(c
,shared
.crlf
);
2139 static void mgetCommand(redisClient
*c
) {
2142 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
2143 for (j
= 1; j
< c
->argc
; j
++) {
2144 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[j
]);
2146 addReply(c
,shared
.nullbulk
);
2148 if (o
->type
!= REDIS_STRING
) {
2149 addReply(c
,shared
.nullbulk
);
2151 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(o
->ptr
)));
2153 addReply(c
,shared
.crlf
);
2159 static void incrDecrCommand(redisClient
*c
, int incr
) {
2164 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2168 if (o
->type
!= REDIS_STRING
) {
2173 value
= strtoll(o
->ptr
, &eptr
, 10);
2178 o
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
));
2179 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],o
);
2180 if (retval
== DICT_ERR
) {
2181 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
2182 removeExpire(c
->db
,c
->argv
[1]);
2184 incrRefCount(c
->argv
[1]);
2187 addReply(c
,shared
.colon
);
2189 addReply(c
,shared
.crlf
);
2192 static void incrCommand(redisClient
*c
) {
2193 incrDecrCommand(c
,1);
2196 static void decrCommand(redisClient
*c
) {
2197 incrDecrCommand(c
,-1);
2200 static void incrbyCommand(redisClient
*c
) {
2201 int incr
= atoi(c
->argv
[2]->ptr
);
2202 incrDecrCommand(c
,incr
);
2205 static void decrbyCommand(redisClient
*c
) {
2206 int incr
= atoi(c
->argv
[2]->ptr
);
2207 incrDecrCommand(c
,-incr
);
2210 /* ========================= Type agnostic commands ========================= */
2212 static void delCommand(redisClient
*c
) {
2213 if (deleteKey(c
->db
,c
->argv
[1])) {
2215 addReply(c
,shared
.cone
);
2217 addReply(c
,shared
.czero
);
2221 static void existsCommand(redisClient
*c
) {
2222 addReply(c
,lookupKeyRead(c
->db
,c
->argv
[1]) ? shared
.cone
: shared
.czero
);
2225 static void selectCommand(redisClient
*c
) {
2226 int id
= atoi(c
->argv
[1]->ptr
);
2228 if (selectDb(c
,id
) == REDIS_ERR
) {
2229 addReplySds(c
,sdsnew("-ERR invalid DB index\r\n"));
2231 addReply(c
,shared
.ok
);
2235 static void randomkeyCommand(redisClient
*c
) {
2239 de
= dictGetRandomKey(c
->db
->dict
);
2240 if (!de
|| expireIfNeeded(c
->db
,dictGetEntryKey(de
)) == 0) break;
2243 addReply(c
,shared
.plus
);
2244 addReply(c
,shared
.crlf
);
2246 addReply(c
,shared
.plus
);
2247 addReply(c
,dictGetEntryKey(de
));
2248 addReply(c
,shared
.crlf
);
2252 static void keysCommand(redisClient
*c
) {
2255 sds pattern
= c
->argv
[1]->ptr
;
2256 int plen
= sdslen(pattern
);
2257 int numkeys
= 0, keyslen
= 0;
2258 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
2260 di
= dictGetIterator(c
->db
->dict
);
2261 if (!di
) oom("dictGetIterator");
2263 decrRefCount(lenobj
);
2264 while((de
= dictNext(di
)) != NULL
) {
2265 robj
*keyobj
= dictGetEntryKey(de
);
2267 sds key
= keyobj
->ptr
;
2268 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
2269 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
2270 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
2272 addReply(c
,shared
.space
);
2275 keyslen
+= sdslen(key
);
2279 dictReleaseIterator(di
);
2280 lenobj
->ptr
= sdscatprintf(sdsempty(),"$%lu\r\n",keyslen
+(numkeys
? (numkeys
-1) : 0));
2281 addReply(c
,shared
.crlf
);
2284 static void dbsizeCommand(redisClient
*c
) {
2286 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c
->db
->dict
)));
2289 static void lastsaveCommand(redisClient
*c
) {
2291 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
2294 static void typeCommand(redisClient
*c
) {
2298 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
2303 case REDIS_STRING
: type
= "+string"; break;
2304 case REDIS_LIST
: type
= "+list"; break;
2305 case REDIS_SET
: type
= "+set"; break;
2306 default: type
= "unknown"; break;
2309 addReplySds(c
,sdsnew(type
));
2310 addReply(c
,shared
.crlf
);
2313 static void saveCommand(redisClient
*c
) {
2314 if (server
.bgsaveinprogress
) {
2315 addReplySds(c
,sdsnew("-ERR background save in progress\r\n"));
2318 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
2319 addReply(c
,shared
.ok
);
2321 addReply(c
,shared
.err
);
2325 static void bgsaveCommand(redisClient
*c
) {
2326 if (server
.bgsaveinprogress
) {
2327 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
2330 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
2331 addReply(c
,shared
.ok
);
2333 addReply(c
,shared
.err
);
2337 static void shutdownCommand(redisClient
*c
) {
2338 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
2339 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
2340 if (server
.daemonize
) {
2341 unlink(server
.pidfile
);
2343 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
2346 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
2347 addReplySds(c
,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
2351 static void renameGenericCommand(redisClient
*c
, int nx
) {
2354 /* To use the same key as src and dst is probably an error */
2355 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
2356 addReply(c
,shared
.sameobjecterr
);
2360 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2362 addReply(c
,shared
.nokeyerr
);
2366 deleteIfVolatile(c
->db
,c
->argv
[2]);
2367 if (dictAdd(c
->db
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
2370 addReply(c
,shared
.czero
);
2373 dictReplace(c
->db
->dict
,c
->argv
[2],o
);
2375 incrRefCount(c
->argv
[2]);
2377 deleteKey(c
->db
,c
->argv
[1]);
2379 addReply(c
,nx
? shared
.cone
: shared
.ok
);
2382 static void renameCommand(redisClient
*c
) {
2383 renameGenericCommand(c
,0);
2386 static void renamenxCommand(redisClient
*c
) {
2387 renameGenericCommand(c
,1);
2390 static void moveCommand(redisClient
*c
) {
2395 /* Obtain source and target DB pointers */
2398 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
2399 addReply(c
,shared
.outofrangeerr
);
2403 selectDb(c
,srcid
); /* Back to the source DB */
2405 /* If the user is moving using as target the same
2406 * DB as the source DB it is probably an error. */
2408 addReply(c
,shared
.sameobjecterr
);
2412 /* Check if the element exists and get a reference */
2413 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2415 addReply(c
,shared
.czero
);
2419 /* Try to add the element to the target DB */
2420 deleteIfVolatile(dst
,c
->argv
[1]);
2421 if (dictAdd(dst
->dict
,c
->argv
[1],o
) == DICT_ERR
) {
2422 addReply(c
,shared
.czero
);
2425 incrRefCount(c
->argv
[1]);
2428 /* OK! key moved, free the entry in the source DB */
2429 deleteKey(src
,c
->argv
[1]);
2431 addReply(c
,shared
.cone
);
2434 /* =================================== Lists ================================ */
2435 static void pushGenericCommand(redisClient
*c
, int where
) {
2439 lobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2441 lobj
= createListObject();
2443 if (where
== REDIS_HEAD
) {
2444 if (!listAddNodeHead(list
,c
->argv
[2])) oom("listAddNodeHead");
2446 if (!listAddNodeTail(list
,c
->argv
[2])) oom("listAddNodeTail");
2448 dictAdd(c
->db
->dict
,c
->argv
[1],lobj
);
2449 incrRefCount(c
->argv
[1]);
2450 incrRefCount(c
->argv
[2]);
2452 if (lobj
->type
!= REDIS_LIST
) {
2453 addReply(c
,shared
.wrongtypeerr
);
2457 if (where
== REDIS_HEAD
) {
2458 if (!listAddNodeHead(list
,c
->argv
[2])) oom("listAddNodeHead");
2460 if (!listAddNodeTail(list
,c
->argv
[2])) oom("listAddNodeTail");
2462 incrRefCount(c
->argv
[2]);
2465 addReply(c
,shared
.ok
);
2468 static void lpushCommand(redisClient
*c
) {
2469 pushGenericCommand(c
,REDIS_HEAD
);
2472 static void rpushCommand(redisClient
*c
) {
2473 pushGenericCommand(c
,REDIS_TAIL
);
2476 static void llenCommand(redisClient
*c
) {
2480 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
2482 addReply(c
,shared
.czero
);
2485 if (o
->type
!= REDIS_LIST
) {
2486 addReply(c
,shared
.wrongtypeerr
);
2489 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(l
)));
2494 static void lindexCommand(redisClient
*c
) {
2496 int index
= atoi(c
->argv
[2]->ptr
);
2498 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
2500 addReply(c
,shared
.nullbulk
);
2502 if (o
->type
!= REDIS_LIST
) {
2503 addReply(c
,shared
.wrongtypeerr
);
2505 list
*list
= o
->ptr
;
2508 ln
= listIndex(list
, index
);
2510 addReply(c
,shared
.nullbulk
);
2512 robj
*ele
= listNodeValue(ln
);
2513 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2515 addReply(c
,shared
.crlf
);
2521 static void lsetCommand(redisClient
*c
) {
2523 int index
= atoi(c
->argv
[2]->ptr
);
2525 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2527 addReply(c
,shared
.nokeyerr
);
2529 if (o
->type
!= REDIS_LIST
) {
2530 addReply(c
,shared
.wrongtypeerr
);
2532 list
*list
= o
->ptr
;
2535 ln
= listIndex(list
, index
);
2537 addReply(c
,shared
.outofrangeerr
);
2539 robj
*ele
= listNodeValue(ln
);
2542 listNodeValue(ln
) = c
->argv
[3];
2543 incrRefCount(c
->argv
[3]);
2544 addReply(c
,shared
.ok
);
2551 static void popGenericCommand(redisClient
*c
, int where
) {
2554 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2556 addReply(c
,shared
.nullbulk
);
2558 if (o
->type
!= REDIS_LIST
) {
2559 addReply(c
,shared
.wrongtypeerr
);
2561 list
*list
= o
->ptr
;
2564 if (where
== REDIS_HEAD
)
2565 ln
= listFirst(list
);
2567 ln
= listLast(list
);
2570 addReply(c
,shared
.nullbulk
);
2572 robj
*ele
= listNodeValue(ln
);
2573 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2575 addReply(c
,shared
.crlf
);
2576 listDelNode(list
,ln
);
2583 static void lpopCommand(redisClient
*c
) {
2584 popGenericCommand(c
,REDIS_HEAD
);
2587 static void rpopCommand(redisClient
*c
) {
2588 popGenericCommand(c
,REDIS_TAIL
);
2591 static void lrangeCommand(redisClient
*c
) {
2593 int start
= atoi(c
->argv
[2]->ptr
);
2594 int end
= atoi(c
->argv
[3]->ptr
);
2596 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
2598 addReply(c
,shared
.nullmultibulk
);
2600 if (o
->type
!= REDIS_LIST
) {
2601 addReply(c
,shared
.wrongtypeerr
);
2603 list
*list
= o
->ptr
;
2605 int llen
= listLength(list
);
2609 /* convert negative indexes */
2610 if (start
< 0) start
= llen
+start
;
2611 if (end
< 0) end
= llen
+end
;
2612 if (start
< 0) start
= 0;
2613 if (end
< 0) end
= 0;
2615 /* indexes sanity checks */
2616 if (start
> end
|| start
>= llen
) {
2617 /* Out of range start or start > end result in empty list */
2618 addReply(c
,shared
.emptymultibulk
);
2621 if (end
>= llen
) end
= llen
-1;
2622 rangelen
= (end
-start
)+1;
2624 /* Return the result in form of a multi-bulk reply */
2625 ln
= listIndex(list
, start
);
2626 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
2627 for (j
= 0; j
< rangelen
; j
++) {
2628 ele
= listNodeValue(ln
);
2629 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2631 addReply(c
,shared
.crlf
);
2638 static void ltrimCommand(redisClient
*c
) {
2640 int start
= atoi(c
->argv
[2]->ptr
);
2641 int end
= atoi(c
->argv
[3]->ptr
);
2643 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2645 addReply(c
,shared
.nokeyerr
);
2647 if (o
->type
!= REDIS_LIST
) {
2648 addReply(c
,shared
.wrongtypeerr
);
2650 list
*list
= o
->ptr
;
2652 int llen
= listLength(list
);
2653 int j
, ltrim
, rtrim
;
2655 /* convert negative indexes */
2656 if (start
< 0) start
= llen
+start
;
2657 if (end
< 0) end
= llen
+end
;
2658 if (start
< 0) start
= 0;
2659 if (end
< 0) end
= 0;
2661 /* indexes sanity checks */
2662 if (start
> end
|| start
>= llen
) {
2663 /* Out of range start or start > end result in empty list */
2667 if (end
>= llen
) end
= llen
-1;
2672 /* Remove list elements to perform the trim */
2673 for (j
= 0; j
< ltrim
; j
++) {
2674 ln
= listFirst(list
);
2675 listDelNode(list
,ln
);
2677 for (j
= 0; j
< rtrim
; j
++) {
2678 ln
= listLast(list
);
2679 listDelNode(list
,ln
);
2681 addReply(c
,shared
.ok
);
2687 static void lremCommand(redisClient
*c
) {
2690 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2692 addReply(c
,shared
.nokeyerr
);
2694 if (o
->type
!= REDIS_LIST
) {
2695 addReply(c
,shared
.wrongtypeerr
);
2697 list
*list
= o
->ptr
;
2698 listNode
*ln
, *next
;
2699 int toremove
= atoi(c
->argv
[2]->ptr
);
2704 toremove
= -toremove
;
2707 ln
= fromtail
? list
->tail
: list
->head
;
2709 robj
*ele
= listNodeValue(ln
);
2711 next
= fromtail
? ln
->prev
: ln
->next
;
2712 if (sdscmp(ele
->ptr
,c
->argv
[3]->ptr
) == 0) {
2713 listDelNode(list
,ln
);
2716 if (toremove
&& removed
== toremove
) break;
2720 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
2725 /* ==================================== Sets ================================ */
2727 static void saddCommand(redisClient
*c
) {
2730 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2732 set
= createSetObject();
2733 dictAdd(c
->db
->dict
,c
->argv
[1],set
);
2734 incrRefCount(c
->argv
[1]);
2736 if (set
->type
!= REDIS_SET
) {
2737 addReply(c
,shared
.wrongtypeerr
);
2741 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
2742 incrRefCount(c
->argv
[2]);
2744 addReply(c
,shared
.cone
);
2746 addReply(c
,shared
.czero
);
2750 static void sremCommand(redisClient
*c
) {
2753 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
2755 addReply(c
,shared
.czero
);
2757 if (set
->type
!= REDIS_SET
) {
2758 addReply(c
,shared
.wrongtypeerr
);
2761 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
2763 addReply(c
,shared
.cone
);
2765 addReply(c
,shared
.czero
);
2770 static void sismemberCommand(redisClient
*c
) {
2773 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
2775 addReply(c
,shared
.czero
);
2777 if (set
->type
!= REDIS_SET
) {
2778 addReply(c
,shared
.wrongtypeerr
);
2781 if (dictFind(set
->ptr
,c
->argv
[2]))
2782 addReply(c
,shared
.cone
);
2784 addReply(c
,shared
.czero
);
2788 static void scardCommand(redisClient
*c
) {
2792 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
2794 addReply(c
,shared
.czero
);
2797 if (o
->type
!= REDIS_SET
) {
2798 addReply(c
,shared
.wrongtypeerr
);
2801 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",
2807 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
2808 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
2810 return dictSize(*d1
)-dictSize(*d2
);
2813 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
) {
2814 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
2817 robj
*lenobj
= NULL
, *dstset
= NULL
;
2818 int j
, cardinality
= 0;
2820 if (!dv
) oom("sinterCommand");
2821 for (j
= 0; j
< setsnum
; j
++) {
2825 lookupKeyWrite(c
->db
,setskeys
[j
]) :
2826 lookupKeyRead(c
->db
,setskeys
[j
]);
2829 addReply(c
,shared
.nokeyerr
);
2832 if (setobj
->type
!= REDIS_SET
) {
2834 addReply(c
,shared
.wrongtypeerr
);
2837 dv
[j
] = setobj
->ptr
;
2839 /* Sort sets from the smallest to largest, this will improve our
2840 * algorithm's performace */
2841 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
2843 /* The first thing we should output is the total number of elements...
2844 * since this is a multi-bulk write, but at this stage we don't know
2845 * the intersection set size, so we use a trick, append an empty object
2846 * to the output list and save the pointer to later modify it with the
2849 lenobj
= createObject(REDIS_STRING
,NULL
);
2851 decrRefCount(lenobj
);
2853 /* If we have a target key where to store the resulting set
2854 * create this key with an empty set inside */
2855 dstset
= createSetObject();
2856 deleteKey(c
->db
,dstkey
);
2857 dictAdd(c
->db
->dict
,dstkey
,dstset
);
2858 incrRefCount(dstkey
);
2862 /* Iterate all the elements of the first (smallest) set, and test
2863 * the element against all the other sets, if at least one set does
2864 * not include the element it is discarded */
2865 di
= dictGetIterator(dv
[0]);
2866 if (!di
) oom("dictGetIterator");
2868 while((de
= dictNext(di
)) != NULL
) {
2871 for (j
= 1; j
< setsnum
; j
++)
2872 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
2874 continue; /* at least one set does not contain the member */
2875 ele
= dictGetEntryKey(de
);
2877 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",sdslen(ele
->ptr
)));
2879 addReply(c
,shared
.crlf
);
2882 dictAdd(dstset
->ptr
,ele
,NULL
);
2887 dictReleaseIterator(di
);
2890 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%d\r\n",cardinality
);
2892 addReply(c
,shared
.ok
);
2896 static void sinterCommand(redisClient
*c
) {
2897 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
2900 static void sinterstoreCommand(redisClient
*c
) {
2901 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
2904 static void flushdbCommand(redisClient
*c
) {
2905 dictEmpty(c
->db
->dict
);
2906 dictEmpty(c
->db
->expires
);
2908 addReply(c
,shared
.ok
);
2909 rdbSave(server
.dbfilename
);
2912 static void flushallCommand(redisClient
*c
) {
2915 addReply(c
,shared
.ok
);
2916 rdbSave(server
.dbfilename
);
2919 redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
2920 redisSortOperation
*so
= zmalloc(sizeof(*so
));
2921 if (!so
) oom("createSortOperation");
2923 so
->pattern
= pattern
;
2927 /* Return the value associated to the key with a name obtained
2928 * substituting the first occurence of '*' in 'pattern' with 'subst' */
2929 robj
*lookupKeyByPattern(redisDb
*db
, robj
*pattern
, robj
*subst
) {
2933 int prefixlen
, sublen
, postfixlen
;
2934 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
2938 char buf
[REDIS_SORTKEY_MAX
+1];
2941 spat
= pattern
->ptr
;
2943 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
2944 p
= strchr(spat
,'*');
2945 if (!p
) return NULL
;
2948 sublen
= sdslen(ssub
);
2949 postfixlen
= sdslen(spat
)-(prefixlen
+1);
2950 memcpy(keyname
.buf
,spat
,prefixlen
);
2951 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
2952 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
2953 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
2954 keyname
.len
= prefixlen
+sublen
+postfixlen
;
2956 keyobj
.refcount
= 1;
2957 keyobj
.type
= REDIS_STRING
;
2958 keyobj
.ptr
= ((char*)&keyname
)+(sizeof(long)*2);
2960 /* printf("lookup '%s' => %p\n", keyname.buf,de); */
2961 return lookupKeyRead(db
,&keyobj
);
2964 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
2965 * the additional parameter is not standard but a BSD-specific we have to
2966 * pass sorting parameters via the global 'server' structure */
2967 static int sortCompare(const void *s1
, const void *s2
) {
2968 const redisSortObject
*so1
= s1
, *so2
= s2
;
2971 if (!server
.sort_alpha
) {
2972 /* Numeric sorting. Here it's trivial as we precomputed scores */
2973 if (so1
->u
.score
> so2
->u
.score
) {
2975 } else if (so1
->u
.score
< so2
->u
.score
) {
2981 /* Alphanumeric sorting */
2982 if (server
.sort_bypattern
) {
2983 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
2984 /* At least one compare object is NULL */
2985 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
2987 else if (so1
->u
.cmpobj
== NULL
)
2992 /* We have both the objects, use strcoll */
2993 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
2996 /* Compare elements directly */
2997 cmp
= strcoll(so1
->obj
->ptr
,so2
->obj
->ptr
);
3000 return server
.sort_desc
? -cmp
: cmp
;
3003 /* The SORT command is the most complex command in Redis. Warning: this code
3004 * is optimized for speed and a bit less for readability */
3005 static void sortCommand(redisClient
*c
) {
3008 int desc
= 0, alpha
= 0;
3009 int limit_start
= 0, limit_count
= -1, start
, end
;
3010 int j
, dontsort
= 0, vectorlen
;
3011 int getop
= 0; /* GET operation counter */
3012 robj
*sortval
, *sortby
= NULL
;
3013 redisSortObject
*vector
; /* Resulting vector to sort */
3015 /* Lookup the key to sort. It must be of the right types */
3016 sortval
= lookupKeyRead(c
->db
,c
->argv
[1]);
3017 if (sortval
== NULL
) {
3018 addReply(c
,shared
.nokeyerr
);
3021 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
) {
3022 addReply(c
,shared
.wrongtypeerr
);
3026 /* Create a list of operations to perform for every sorted element.
3027 * Operations can be GET/DEL/INCR/DECR */
3028 operations
= listCreate();
3029 listSetFreeMethod(operations
,zfree
);
3032 /* Now we need to protect sortval incrementing its count, in the future
3033 * SORT may have options able to overwrite/delete keys during the sorting
3034 * and the sorted key itself may get destroied */
3035 incrRefCount(sortval
);
3037 /* The SORT command has an SQL-alike syntax, parse it */
3038 while(j
< c
->argc
) {
3039 int leftargs
= c
->argc
-j
-1;
3040 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
3042 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
3044 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
3046 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
3047 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
3048 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
3050 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
3051 sortby
= c
->argv
[j
+1];
3052 /* If the BY pattern does not contain '*', i.e. it is constant,
3053 * we don't need to sort nor to lookup the weight keys. */
3054 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
3056 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
3057 listAddNodeTail(operations
,createSortOperation(
3058 REDIS_SORT_GET
,c
->argv
[j
+1]));
3061 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"del") && leftargs
>= 1) {
3062 listAddNodeTail(operations
,createSortOperation(
3063 REDIS_SORT_DEL
,c
->argv
[j
+1]));
3065 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"incr") && leftargs
>= 1) {
3066 listAddNodeTail(operations
,createSortOperation(
3067 REDIS_SORT_INCR
,c
->argv
[j
+1]));
3069 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
3070 listAddNodeTail(operations
,createSortOperation(
3071 REDIS_SORT_DECR
,c
->argv
[j
+1]));
3074 decrRefCount(sortval
);
3075 listRelease(operations
);
3076 addReply(c
,shared
.syntaxerr
);
3082 /* Load the sorting vector with all the objects to sort */
3083 vectorlen
= (sortval
->type
== REDIS_LIST
) ?
3084 listLength((list
*)sortval
->ptr
) :
3085 dictSize((dict
*)sortval
->ptr
);
3086 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
3087 if (!vector
) oom("allocating objects vector for SORT");
3089 if (sortval
->type
== REDIS_LIST
) {
3090 list
*list
= sortval
->ptr
;
3091 listNode
*ln
= list
->head
;
3093 robj
*ele
= ln
->value
;
3094 vector
[j
].obj
= ele
;
3095 vector
[j
].u
.score
= 0;
3096 vector
[j
].u
.cmpobj
= NULL
;
3101 dict
*set
= sortval
->ptr
;
3105 di
= dictGetIterator(set
);
3106 if (!di
) oom("dictGetIterator");
3107 while((setele
= dictNext(di
)) != NULL
) {
3108 vector
[j
].obj
= dictGetEntryKey(setele
);
3109 vector
[j
].u
.score
= 0;
3110 vector
[j
].u
.cmpobj
= NULL
;
3113 dictReleaseIterator(di
);
3115 assert(j
== vectorlen
);
3117 /* Now it's time to load the right scores in the sorting vector */
3118 if (dontsort
== 0) {
3119 for (j
= 0; j
< vectorlen
; j
++) {
3123 byval
= lookupKeyByPattern(c
->db
,sortby
,vector
[j
].obj
);
3124 if (!byval
|| byval
->type
!= REDIS_STRING
) continue;
3126 vector
[j
].u
.cmpobj
= byval
;
3127 incrRefCount(byval
);
3129 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
3132 if (!alpha
) vector
[j
].u
.score
= strtod(vector
[j
].obj
->ptr
,NULL
);
3137 /* We are ready to sort the vector... perform a bit of sanity check
3138 * on the LIMIT option too. We'll use a partial version of quicksort. */
3139 start
= (limit_start
< 0) ? 0 : limit_start
;
3140 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
3141 if (start
>= vectorlen
) {
3142 start
= vectorlen
-1;
3145 if (end
>= vectorlen
) end
= vectorlen
-1;
3147 if (dontsort
== 0) {
3148 server
.sort_desc
= desc
;
3149 server
.sort_alpha
= alpha
;
3150 server
.sort_bypattern
= sortby
? 1 : 0;
3151 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
3154 /* Send command output to the output buffer, performing the specified
3155 * GET/DEL/INCR/DECR operations if any. */
3156 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
3157 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
3158 for (j
= start
; j
<= end
; j
++) {
3159 listNode
*ln
= operations
->head
;
3161 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
3162 sdslen(vector
[j
].obj
->ptr
)));
3163 addReply(c
,vector
[j
].obj
);
3164 addReply(c
,shared
.crlf
);
3167 redisSortOperation
*sop
= ln
->value
;
3168 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
3171 if (sop
->type
== REDIS_SORT_GET
) {
3172 if (!val
|| val
->type
!= REDIS_STRING
) {
3173 addReply(c
,shared
.nullbulk
);
3175 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
3178 addReply(c
,shared
.crlf
);
3180 } else if (sop
->type
== REDIS_SORT_DEL
) {
3188 decrRefCount(sortval
);
3189 listRelease(operations
);
3190 for (j
= 0; j
< vectorlen
; j
++) {
3191 if (sortby
&& alpha
&& vector
[j
].u
.cmpobj
)
3192 decrRefCount(vector
[j
].u
.cmpobj
);
3197 static void infoCommand(redisClient
*c
) {
3199 time_t uptime
= time(NULL
)-server
.stat_starttime
;
3201 info
= sdscatprintf(sdsempty(),
3202 "redis_version:%s\r\n"
3203 "connected_clients:%d\r\n"
3204 "connected_slaves:%d\r\n"
3205 "used_memory:%d\r\n"
3206 "changes_since_last_save:%lld\r\n"
3207 "last_save_time:%d\r\n"
3208 "total_connections_received:%lld\r\n"
3209 "total_commands_processed:%lld\r\n"
3210 "uptime_in_seconds:%d\r\n"
3211 "uptime_in_days:%d\r\n"
3213 listLength(server
.clients
)-listLength(server
.slaves
),
3214 listLength(server
.slaves
),
3218 server
.stat_numconnections
,
3219 server
.stat_numcommands
,
3223 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",sdslen(info
)));
3224 addReplySds(c
,info
);
3225 addReply(c
,shared
.crlf
);
3228 static void monitorCommand(redisClient
*c
) {
3229 /* ignore MONITOR if aleady slave or in monitor mode */
3230 if (c
->flags
& REDIS_SLAVE
) return;
3232 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
3234 if (!listAddNodeTail(server
.monitors
,c
)) oom("listAddNodeTail");
3235 addReply(c
,shared
.ok
);
3238 /* ================================= Expire ================================= */
3239 static int removeExpire(redisDb
*db
, robj
*key
) {
3240 if (dictDelete(db
->expires
,key
) == DICT_OK
) {
3247 static int setExpire(redisDb
*db
, robj
*key
, time_t when
) {
3248 if (dictAdd(db
->expires
,key
,(void*)when
) == DICT_ERR
) {
3256 /* Return the expire time of the specified key, or -1 if no expire
3257 * is associated with this key (i.e. the key is non volatile) */
3258 static time_t getExpire(redisDb
*db
, robj
*key
) {
3261 /* No expire? return ASAP */
3262 if (dictSize(db
->expires
) == 0 ||
3263 (de
= dictFind(db
->expires
,key
)) == NULL
) return -1;
3265 return (time_t) dictGetEntryVal(de
);
3268 static int expireIfNeeded(redisDb
*db
, robj
*key
) {
3272 /* No expire? return ASAP */
3273 if (dictSize(db
->expires
) == 0 ||
3274 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
3276 /* Lookup the expire */
3277 when
= (time_t) dictGetEntryVal(de
);
3278 if (time(NULL
) <= when
) return 0;
3280 /* Delete the key */
3281 dictDelete(db
->expires
,key
);
3282 return dictDelete(db
->dict
,key
) == DICT_OK
;
3285 static int deleteIfVolatile(redisDb
*db
, robj
*key
) {
3288 /* No expire? return ASAP */
3289 if (dictSize(db
->expires
) == 0 ||
3290 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
3292 /* Delete the key */
3294 dictDelete(db
->expires
,key
);
3295 return dictDelete(db
->dict
,key
) == DICT_OK
;
3298 static void expireCommand(redisClient
*c
) {
3300 int seconds
= atoi(c
->argv
[2]->ptr
);
3302 de
= dictFind(c
->db
->dict
,c
->argv
[1]);
3304 addReply(c
,shared
.czero
);
3308 addReply(c
, shared
.czero
);
3311 time_t when
= time(NULL
)+seconds
;
3312 if (setExpire(c
->db
,c
->argv
[1],when
))
3313 addReply(c
,shared
.cone
);
3315 addReply(c
,shared
.czero
);
3320 /* =============================== Replication ============================= */
3322 /* Send the whole output buffer syncronously to the slave. This a general operation in theory, but it is actually useful only for replication. */
3323 static int flushClientOutput(redisClient
*c
) {
3325 time_t start
= time(NULL
);
3327 while(listLength(c
->reply
)) {
3328 if (time(NULL
)-start
> 5) return REDIS_ERR
; /* 5 seconds timeout */
3329 retval
= aeWait(c
->fd
,AE_WRITABLE
,1000);
3332 } else if (retval
& AE_WRITABLE
) {
3333 sendReplyToClient(NULL
, c
->fd
, c
, AE_WRITABLE
);
3339 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) {
3340 ssize_t nwritten
, ret
= size
;
3341 time_t start
= time(NULL
);
3345 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
3346 nwritten
= write(fd
,ptr
,size
);
3347 if (nwritten
== -1) return -1;
3351 if ((time(NULL
)-start
) > timeout
) {
3359 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) {
3360 ssize_t nread
, totread
= 0;
3361 time_t start
= time(NULL
);
3365 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
3366 nread
= read(fd
,ptr
,size
);
3367 if (nread
== -1) return -1;
3372 if ((time(NULL
)-start
) > timeout
) {
3380 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
3387 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
3390 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
3401 static void syncCommand(redisClient
*c
) {
3404 time_t start
= time(NULL
);
3407 /* ignore SYNC if aleady slave or in monitor mode */
3408 if (c
->flags
& REDIS_SLAVE
) return;
3410 redisLog(REDIS_NOTICE
,"Slave ask for syncronization");
3411 if (flushClientOutput(c
) == REDIS_ERR
||
3412 rdbSave(server
.dbfilename
) != REDIS_OK
)
3415 fd
= open(server
.dbfilename
, O_RDONLY
);
3416 if (fd
== -1 || fstat(fd
,&sb
) == -1) goto closeconn
;
3419 snprintf(sizebuf
,32,"$%d\r\n",len
);
3420 if (syncWrite(c
->fd
,sizebuf
,strlen(sizebuf
),5) == -1) goto closeconn
;
3425 if (time(NULL
)-start
> REDIS_MAX_SYNC_TIME
) goto closeconn
;
3426 nread
= read(fd
,buf
,1024);
3427 if (nread
== -1) goto closeconn
;
3429 if (syncWrite(c
->fd
,buf
,nread
,5) == -1) goto closeconn
;
3431 if (syncWrite(c
->fd
,"\r\n",2,5) == -1) goto closeconn
;
3433 c
->flags
|= REDIS_SLAVE
;
3435 if (!listAddNodeTail(server
.slaves
,c
)) oom("listAddNodeTail");
3436 redisLog(REDIS_NOTICE
,"Syncronization with slave succeeded");
3440 if (fd
!= -1) close(fd
);
3441 c
->flags
|= REDIS_CLOSE
;
3442 redisLog(REDIS_WARNING
,"Syncronization with slave failed");
3446 static int syncWithMaster(void) {
3447 char buf
[1024], tmpfile
[256];
3449 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
3453 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
3457 /* Issue the SYNC command */
3458 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
3460 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
3464 /* Read the bulk write count */
3465 if (syncReadLine(fd
,buf
,1024,5) == -1) {
3467 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
3471 dumpsize
= atoi(buf
+1);
3472 redisLog(REDIS_NOTICE
,"Receiving %d bytes data dump from MASTER",dumpsize
);
3473 /* Read the bulk write data on a temp file */
3474 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
3475 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
,0644);
3478 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
3482 int nread
, nwritten
;
3484 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
3486 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
3492 nwritten
= write(dfd
,buf
,nread
);
3493 if (nwritten
== -1) {
3494 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
3502 if (rename(tmpfile
,server
.dbfilename
) == -1) {
3503 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
3509 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
3510 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
3514 server
.master
= createClient(fd
);
3515 server
.master
->flags
|= REDIS_MASTER
;
3516 server
.replstate
= REDIS_REPL_CONNECTED
;
3520 /* =================================== Main! ================================ */
3522 static void daemonize(void) {
3526 if (fork() != 0) exit(0); /* parent exits */
3527 setsid(); /* create a new session */
3529 /* Every output goes to /dev/null. If Redis is daemonized but
3530 * the 'logfile' is set to 'stdout' in the configuration file
3531 * it will not log at all. */
3532 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
3533 dup2(fd
, STDIN_FILENO
);
3534 dup2(fd
, STDOUT_FILENO
);
3535 dup2(fd
, STDERR_FILENO
);
3536 if (fd
> STDERR_FILENO
) close(fd
);
3538 /* Try to write the pid file */
3539 fp
= fopen(server
.pidfile
,"w");
3541 fprintf(fp
,"%d\n",getpid());
3546 int main(int argc
, char **argv
) {
3549 ResetServerSaveParams();
3550 loadServerConfig(argv
[1]);
3551 } else if (argc
> 2) {
3552 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
3556 if (server
.daemonize
) daemonize();
3557 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
3558 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
3559 redisLog(REDIS_NOTICE
,"DB loaded from disk");
3560 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
3561 acceptHandler
, NULL
, NULL
) == AE_ERR
) oom("creating file event");
3562 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
3564 aeDeleteEventLoop(server
.el
);