]> git.saurik.com Git - redis.git/blame_incremental - src/redis.c
Fix for hash table collision attack. We simply randomize hash table initialization...
[redis.git] / src / redis.c
... / ...
CommitLineData
1/*
2 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
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.
16 *
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.
28 */
29
30#include "redis.h"
31#include "slowlog.h"
32#include "bio.h"
33
34#include <time.h>
35#include <signal.h>
36#include <sys/wait.h>
37#include <errno.h>
38#include <assert.h>
39#include <ctype.h>
40#include <stdarg.h>
41#include <arpa/inet.h>
42#include <sys/stat.h>
43#include <fcntl.h>
44#include <sys/time.h>
45#include <sys/resource.h>
46#include <sys/uio.h>
47#include <limits.h>
48#include <float.h>
49#include <math.h>
50#include <sys/resource.h>
51
52/* Our shared "common" objects */
53
54struct sharedObjectsStruct shared;
55
56/* Global vars that are actually used as constants. The following double
57 * values are used for double on-disk serialization, and are initialized
58 * at runtime to avoid strange compiler optimizations. */
59
60double R_Zero, R_PosInf, R_NegInf, R_Nan;
61
62/*================================= Globals ================================= */
63
64/* Global vars */
65struct redisServer server; /* server global state */
66struct redisCommand *commandTable;
67
68/* Our command table.
69 *
70 * Every entry is composed of the following fields:
71 *
72 * name: a string representing the command name.
73 * function: pointer to the C function implementing the command.
74 * arity: number of arguments, it is possible to use -N to say >= N
75 * sflags: command flags as string. See below for a table of flags.
76 * flags: flags as bitmask. Computed by Redis using the 'sflags' field.
77 * get_keys_proc: an optional function to get key arguments from a command.
78 * This is only used when the following three fields are not
79 * enough to specify what arguments are keys.
80 * first_key_index: first argument that is a key
81 * last_key_index: last argument that is a key
82 * key_step: step to get all the keys from first to last argument. For instance
83 * in MSET the step is two since arguments are key,val,key,val,...
84 * microseconds: microseconds of total execution time for this command.
85 * calls: total number of calls of this command.
86 *
87 * The flags, microseconds and calls fields are computed by Redis and should
88 * always be set to zero.
89 *
90 * Command flags are expressed using strings where every character represents
91 * a flag. Later the populateCommandTable() function will take care of
92 * populating the real 'flags' field using this characters.
93 *
94 * This is the meaning of the flags:
95 *
96 * w: write command (may modify the key space).
97 * r: read command (will never modify the key space).
98 * m: may increase memory usage once called. Don't allow if out of memory.
99 * a: admin command, like SAVE or SHUTDOWN.
100 * p: Pub/Sub related command.
101 * f: force replication of this command, regarless of server.dirty.
102 * s: command not allowed in scripts.
103 * R: random command. Command is not deterministic, that is, the same command
104 * with the same arguments, with the same key space, may have different
105 * results. For instance SPOP and RANDOMKEY are two random commands. */
106struct redisCommand redisCommandTable[] = {
107 {"get",getCommand,2,"r",0,NULL,1,1,1,0,0},
108 {"set",setCommand,3,"wm",0,noPreloadGetKeys,1,1,1,0,0},
109 {"setnx",setnxCommand,3,"wm",0,noPreloadGetKeys,1,1,1,0,0},
110 {"setex",setexCommand,4,"wm",0,noPreloadGetKeys,1,1,1,0,0},
111 {"psetex",psetexCommand,4,"wm",0,noPreloadGetKeys,1,1,1,0,0},
112 {"append",appendCommand,3,"wm",0,NULL,1,1,1,0,0},
113 {"strlen",strlenCommand,2,"r",0,NULL,1,1,1,0,0},
114 {"del",delCommand,-2,"w",0,noPreloadGetKeys,1,-1,1,0,0},
115 {"exists",existsCommand,2,"r",0,NULL,1,1,1,0,0},
116 {"setbit",setbitCommand,4,"wm",0,NULL,1,1,1,0,0},
117 {"getbit",getbitCommand,3,"r",0,NULL,1,1,1,0,0},
118 {"setrange",setrangeCommand,4,"wm",0,NULL,1,1,1,0,0},
119 {"getrange",getrangeCommand,4,"r",0,NULL,1,1,1,0,0},
120 {"substr",getrangeCommand,4,"r",0,NULL,1,1,1,0,0},
121 {"incr",incrCommand,2,"wm",0,NULL,1,1,1,0,0},
122 {"decr",decrCommand,2,"wm",0,NULL,1,1,1,0,0},
123 {"mget",mgetCommand,-2,"r",0,NULL,1,-1,1,0,0},
124 {"rpush",rpushCommand,-3,"wm",0,NULL,1,1,1,0,0},
125 {"lpush",lpushCommand,-3,"wm",0,NULL,1,1,1,0,0},
126 {"rpushx",rpushxCommand,3,"wm",0,NULL,1,1,1,0,0},
127 {"lpushx",lpushxCommand,3,"wm",0,NULL,1,1,1,0,0},
128 {"linsert",linsertCommand,5,"wm",0,NULL,1,1,1,0,0},
129 {"rpop",rpopCommand,2,"w",0,NULL,1,1,1,0,0},
130 {"lpop",lpopCommand,2,"w",0,NULL,1,1,1,0,0},
131 {"brpop",brpopCommand,-3,"ws",0,NULL,1,1,1,0,0},
132 {"brpoplpush",brpoplpushCommand,4,"wms",0,NULL,1,2,1,0,0},
133 {"blpop",blpopCommand,-3,"ws",0,NULL,1,-2,1,0,0},
134 {"llen",llenCommand,2,"r",0,NULL,1,1,1,0,0},
135 {"lindex",lindexCommand,3,"r",0,NULL,1,1,1,0,0},
136 {"lset",lsetCommand,4,"wm",0,NULL,1,1,1,0,0},
137 {"lrange",lrangeCommand,4,"r",0,NULL,1,1,1,0,0},
138 {"ltrim",ltrimCommand,4,"w",0,NULL,1,1,1,0,0},
139 {"lrem",lremCommand,4,"w",0,NULL,1,1,1,0,0},
140 {"rpoplpush",rpoplpushCommand,3,"wm",0,NULL,1,2,1,0,0},
141 {"sadd",saddCommand,-3,"wm",0,NULL,1,1,1,0,0},
142 {"srem",sremCommand,-3,"w",0,NULL,1,1,1,0,0},
143 {"smove",smoveCommand,4,"w",0,NULL,1,2,1,0,0},
144 {"sismember",sismemberCommand,3,"r",0,NULL,1,1,1,0,0},
145 {"scard",scardCommand,2,"r",0,NULL,1,1,1,0,0},
146 {"spop",spopCommand,2,"wRs",0,NULL,1,1,1,0,0},
147 {"srandmember",srandmemberCommand,2,"rR",0,NULL,1,1,1,0,0},
148 {"sinter",sinterCommand,-2,"r",0,NULL,1,-1,1,0,0},
149 {"sinterstore",sinterstoreCommand,-3,"wm",0,NULL,1,-1,1,0,0},
150 {"sunion",sunionCommand,-2,"r",0,NULL,1,-1,1,0,0},
151 {"sunionstore",sunionstoreCommand,-3,"wm",0,NULL,1,-1,1,0,0},
152 {"sdiff",sdiffCommand,-2,"r",0,NULL,1,-1,1,0,0},
153 {"sdiffstore",sdiffstoreCommand,-3,"wm",0,NULL,1,-1,1,0,0},
154 {"smembers",sinterCommand,2,"r",0,NULL,1,1,1,0,0},
155 {"zadd",zaddCommand,-4,"wm",0,NULL,1,1,1,0,0},
156 {"zincrby",zincrbyCommand,4,"wm",0,NULL,1,1,1,0,0},
157 {"zrem",zremCommand,-3,"w",0,NULL,1,1,1,0,0},
158 {"zremrangebyscore",zremrangebyscoreCommand,4,"w",0,NULL,1,1,1,0,0},
159 {"zremrangebyrank",zremrangebyrankCommand,4,"w",0,NULL,1,1,1,0,0},
160 {"zunionstore",zunionstoreCommand,-4,"wm",0,zunionInterGetKeys,0,0,0,0,0},
161 {"zinterstore",zinterstoreCommand,-4,"wm",0,zunionInterGetKeys,0,0,0,0,0},
162 {"zrange",zrangeCommand,-4,"r",0,NULL,1,1,1,0,0},
163 {"zrangebyscore",zrangebyscoreCommand,-4,"r",0,NULL,1,1,1,0,0},
164 {"zrevrangebyscore",zrevrangebyscoreCommand,-4,"r",0,NULL,1,1,1,0,0},
165 {"zcount",zcountCommand,4,"r",0,NULL,1,1,1,0,0},
166 {"zrevrange",zrevrangeCommand,-4,"r",0,NULL,1,1,1,0,0},
167 {"zcard",zcardCommand,2,"r",0,NULL,1,1,1,0,0},
168 {"zscore",zscoreCommand,3,"r",0,NULL,1,1,1,0,0},
169 {"zrank",zrankCommand,3,"r",0,NULL,1,1,1,0,0},
170 {"zrevrank",zrevrankCommand,3,"r",0,NULL,1,1,1,0,0},
171 {"hset",hsetCommand,4,"wm",0,NULL,1,1,1,0,0},
172 {"hsetnx",hsetnxCommand,4,"wm",0,NULL,1,1,1,0,0},
173 {"hget",hgetCommand,3,"r",0,NULL,1,1,1,0,0},
174 {"hmset",hmsetCommand,-4,"wm",0,NULL,1,1,1,0,0},
175 {"hmget",hmgetCommand,-3,"r",0,NULL,1,1,1,0,0},
176 {"hincrby",hincrbyCommand,4,"wm",0,NULL,1,1,1,0,0},
177 {"hincrbyfloat",hincrbyfloatCommand,4,"wm",0,NULL,1,1,1,0,0},
178 {"hdel",hdelCommand,-3,"w",0,NULL,1,1,1,0,0},
179 {"hlen",hlenCommand,2,"r",0,NULL,1,1,1,0,0},
180 {"hkeys",hkeysCommand,2,"r",0,NULL,1,1,1,0,0},
181 {"hvals",hvalsCommand,2,"r",0,NULL,1,1,1,0,0},
182 {"hgetall",hgetallCommand,2,"r",0,NULL,1,1,1,0,0},
183 {"hexists",hexistsCommand,3,"r",0,NULL,1,1,1,0,0},
184 {"incrby",incrbyCommand,3,"wm",0,NULL,1,1,1,0,0},
185 {"decrby",decrbyCommand,3,"wm",0,NULL,1,1,1,0,0},
186 {"incrbyfloat",incrbyfloatCommand,3,"wm",0,NULL,1,1,1,0,0},
187 {"getset",getsetCommand,3,"wm",0,NULL,1,1,1,0,0},
188 {"mset",msetCommand,-3,"wm",0,NULL,1,-1,2,0,0},
189 {"msetnx",msetnxCommand,-3,"wm",0,NULL,1,-1,2,0,0},
190 {"randomkey",randomkeyCommand,1,"rR",0,NULL,0,0,0,0,0},
191 {"select",selectCommand,2,"r",0,NULL,0,0,0,0,0},
192 {"move",moveCommand,3,"w",0,NULL,1,1,1,0,0},
193 {"rename",renameCommand,3,"w",0,renameGetKeys,1,2,1,0,0},
194 {"renamenx",renamenxCommand,3,"w",0,renameGetKeys,1,2,1,0,0},
195 {"expire",expireCommand,3,"w",0,NULL,1,1,1,0,0},
196 {"expireat",expireatCommand,3,"w",0,NULL,1,1,1,0,0},
197 {"pexpire",pexpireCommand,3,"w",0,NULL,1,1,1,0,0},
198 {"pexpireat",pexpireatCommand,3,"w",0,NULL,1,1,1,0,0},
199 {"keys",keysCommand,2,"r",0,NULL,0,0,0,0,0},
200 {"dbsize",dbsizeCommand,1,"r",0,NULL,0,0,0,0,0},
201 {"auth",authCommand,2,"rs",0,NULL,0,0,0,0,0},
202 {"ping",pingCommand,1,"r",0,NULL,0,0,0,0,0},
203 {"echo",echoCommand,2,"r",0,NULL,0,0,0,0,0},
204 {"save",saveCommand,1,"ars",0,NULL,0,0,0,0,0},
205 {"bgsave",bgsaveCommand,1,"ar",0,NULL,0,0,0,0,0},
206 {"bgrewriteaof",bgrewriteaofCommand,1,"ar",0,NULL,0,0,0,0,0},
207 {"shutdown",shutdownCommand,-1,"ar",0,NULL,0,0,0,0,0},
208 {"lastsave",lastsaveCommand,1,"r",0,NULL,0,0,0,0,0},
209 {"type",typeCommand,2,"r",0,NULL,1,1,1,0,0},
210 {"multi",multiCommand,1,"rs",0,NULL,0,0,0,0,0},
211 {"exec",execCommand,1,"wms",0,NULL,0,0,0,0,0},
212 {"discard",discardCommand,1,"rs",0,NULL,0,0,0,0,0},
213 {"sync",syncCommand,1,"ars",0,NULL,0,0,0,0,0},
214 {"flushdb",flushdbCommand,1,"w",0,NULL,0,0,0,0,0},
215 {"flushall",flushallCommand,1,"w",0,NULL,0,0,0,0,0},
216 {"sort",sortCommand,-2,"wm",0,NULL,1,1,1,0,0},
217 {"info",infoCommand,-1,"r",0,NULL,0,0,0,0,0},
218 {"monitor",monitorCommand,1,"ars",0,NULL,0,0,0,0,0},
219 {"ttl",ttlCommand,2,"r",0,NULL,1,1,1,0,0},
220 {"pttl",pttlCommand,2,"r",0,NULL,1,1,1,0,0},
221 {"persist",persistCommand,2,"w",0,NULL,1,1,1,0,0},
222 {"slaveof",slaveofCommand,3,"aws",0,NULL,0,0,0,0,0},
223 {"debug",debugCommand,-2,"aws",0,NULL,0,0,0,0,0},
224 {"config",configCommand,-2,"ar",0,NULL,0,0,0,0,0},
225 {"subscribe",subscribeCommand,-2,"rps",0,NULL,0,0,0,0,0},
226 {"unsubscribe",unsubscribeCommand,-1,"rps",0,NULL,0,0,0,0,0},
227 {"psubscribe",psubscribeCommand,-2,"rps",0,NULL,0,0,0,0,0},
228 {"punsubscribe",punsubscribeCommand,-1,"rps",0,NULL,0,0,0,0,0},
229 {"publish",publishCommand,3,"rpf",0,NULL,0,0,0,0,0},
230 {"watch",watchCommand,-2,"rs",0,noPreloadGetKeys,1,-1,1,0,0},
231 {"unwatch",unwatchCommand,1,"rs",0,NULL,0,0,0,0,0},
232 {"cluster",clusterCommand,-2,"ar",0,NULL,0,0,0,0,0},
233 {"restore",restoreCommand,4,"awm",0,NULL,1,1,1,0,0},
234 {"migrate",migrateCommand,6,"aw",0,NULL,0,0,0,0,0},
235 {"asking",askingCommand,1,"r",0,NULL,0,0,0,0,0},
236 {"dump",dumpCommand,2,"ar",0,NULL,1,1,1,0,0},
237 {"object",objectCommand,-2,"r",0,NULL,2,2,2,0,0},
238 {"client",clientCommand,-2,"ar",0,NULL,0,0,0,0,0},
239 {"eval",evalCommand,-3,"wms",0,zunionInterGetKeys,0,0,0,0,0},
240 {"evalsha",evalShaCommand,-3,"wms",0,zunionInterGetKeys,0,0,0,0,0},
241 {"slowlog",slowlogCommand,-2,"r",0,NULL,0,0,0,0,0},
242 {"script",scriptCommand,-2,"ras",0,NULL,0,0,0,0,0}
243};
244
245/*============================ Utility functions ============================ */
246
247/* Low level logging. To use only for very big messages, otherwise
248 * redisLog() is to prefer. */
249void redisLogRaw(int level, const char *msg) {
250 const int syslogLevelMap[] = { LOG_DEBUG, LOG_INFO, LOG_NOTICE, LOG_WARNING };
251 const char *c = ".-*#";
252 time_t now = time(NULL);
253 FILE *fp;
254 char buf[64];
255 int rawmode = (level & REDIS_LOG_RAW);
256
257 level &= 0xff; /* clear flags */
258 if (level < server.verbosity) return;
259
260 fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a");
261 if (!fp) return;
262
263 if (rawmode) {
264 fprintf(fp,"%s",msg);
265 } else {
266 strftime(buf,sizeof(buf),"%d %b %H:%M:%S",localtime(&now));
267 fprintf(fp,"[%d] %s %c %s\n",(int)getpid(),buf,c[level],msg);
268 }
269 fflush(fp);
270
271 if (server.logfile) fclose(fp);
272
273 if (server.syslog_enabled) syslog(syslogLevelMap[level], "%s", msg);
274}
275
276/* Like redisLogRaw() but with printf-alike support. This is the funciton that
277 * is used across the code. The raw version is only used in order to dump
278 * the INFO output on crash. */
279void redisLog(int level, const char *fmt, ...) {
280 va_list ap;
281 char msg[REDIS_MAX_LOGMSG_LEN];
282
283 if ((level&0xff) < server.verbosity) return;
284
285 va_start(ap, fmt);
286 vsnprintf(msg, sizeof(msg), fmt, ap);
287 va_end(ap);
288
289 redisLogRaw(level,msg);
290}
291
292/* Redis generally does not try to recover from out of memory conditions
293 * when allocating objects or strings, it is not clear if it will be possible
294 * to report this condition to the client since the networking layer itself
295 * is based on heap allocation for send buffers, so we simply abort.
296 * At least the code will be simpler to read... */
297void oom(const char *msg) {
298 redisLog(REDIS_WARNING, "%s: Out of memory\n",msg);
299 sleep(1);
300 abort();
301}
302
303/* Return the UNIX time in microseconds */
304long long ustime(void) {
305 struct timeval tv;
306 long long ust;
307
308 gettimeofday(&tv, NULL);
309 ust = ((long long)tv.tv_sec)*1000000;
310 ust += tv.tv_usec;
311 return ust;
312}
313
314/* Return the UNIX time in milliseconds */
315long long mstime(void) {
316 return ustime()/1000;
317}
318
319/*====================== Hash table type implementation ==================== */
320
321/* This is an hash table type that uses the SDS dynamic strings libary as
322 * keys and radis objects as values (objects can hold SDS strings,
323 * lists, sets). */
324
325void dictVanillaFree(void *privdata, void *val)
326{
327 DICT_NOTUSED(privdata);
328 zfree(val);
329}
330
331void dictListDestructor(void *privdata, void *val)
332{
333 DICT_NOTUSED(privdata);
334 listRelease((list*)val);
335}
336
337int dictSdsKeyCompare(void *privdata, const void *key1,
338 const void *key2)
339{
340 int l1,l2;
341 DICT_NOTUSED(privdata);
342
343 l1 = sdslen((sds)key1);
344 l2 = sdslen((sds)key2);
345 if (l1 != l2) return 0;
346 return memcmp(key1, key2, l1) == 0;
347}
348
349/* A case insensitive version used for the command lookup table. */
350int dictSdsKeyCaseCompare(void *privdata, const void *key1,
351 const void *key2)
352{
353 DICT_NOTUSED(privdata);
354
355 return strcasecmp(key1, key2) == 0;
356}
357
358void dictRedisObjectDestructor(void *privdata, void *val)
359{
360 DICT_NOTUSED(privdata);
361
362 if (val == NULL) return; /* Values of swapped out keys as set to NULL */
363 decrRefCount(val);
364}
365
366void dictSdsDestructor(void *privdata, void *val)
367{
368 DICT_NOTUSED(privdata);
369
370 sdsfree(val);
371}
372
373int dictObjKeyCompare(void *privdata, const void *key1,
374 const void *key2)
375{
376 const robj *o1 = key1, *o2 = key2;
377 return dictSdsKeyCompare(privdata,o1->ptr,o2->ptr);
378}
379
380unsigned int dictObjHash(const void *key) {
381 const robj *o = key;
382 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
383}
384
385unsigned int dictSdsHash(const void *key) {
386 return dictGenHashFunction((unsigned char*)key, sdslen((char*)key));
387}
388
389unsigned int dictSdsCaseHash(const void *key) {
390 return dictGenCaseHashFunction((unsigned char*)key, sdslen((char*)key));
391}
392
393int dictEncObjKeyCompare(void *privdata, const void *key1,
394 const void *key2)
395{
396 robj *o1 = (robj*) key1, *o2 = (robj*) key2;
397 int cmp;
398
399 if (o1->encoding == REDIS_ENCODING_INT &&
400 o2->encoding == REDIS_ENCODING_INT)
401 return o1->ptr == o2->ptr;
402
403 o1 = getDecodedObject(o1);
404 o2 = getDecodedObject(o2);
405 cmp = dictSdsKeyCompare(privdata,o1->ptr,o2->ptr);
406 decrRefCount(o1);
407 decrRefCount(o2);
408 return cmp;
409}
410
411unsigned int dictEncObjHash(const void *key) {
412 robj *o = (robj*) key;
413
414 if (o->encoding == REDIS_ENCODING_RAW) {
415 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
416 } else {
417 if (o->encoding == REDIS_ENCODING_INT) {
418 char buf[32];
419 int len;
420
421 len = ll2string(buf,32,(long)o->ptr);
422 return dictGenHashFunction((unsigned char*)buf, len);
423 } else {
424 unsigned int hash;
425
426 o = getDecodedObject(o);
427 hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
428 decrRefCount(o);
429 return hash;
430 }
431 }
432}
433
434/* Sets type hash table */
435dictType setDictType = {
436 dictEncObjHash, /* hash function */
437 NULL, /* key dup */
438 NULL, /* val dup */
439 dictEncObjKeyCompare, /* key compare */
440 dictRedisObjectDestructor, /* key destructor */
441 NULL /* val destructor */
442};
443
444/* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
445dictType zsetDictType = {
446 dictEncObjHash, /* hash function */
447 NULL, /* key dup */
448 NULL, /* val dup */
449 dictEncObjKeyCompare, /* key compare */
450 dictRedisObjectDestructor, /* key destructor */
451 NULL /* val destructor */
452};
453
454/* Db->dict, keys are sds strings, vals are Redis objects. */
455dictType dbDictType = {
456 dictSdsHash, /* hash function */
457 NULL, /* key dup */
458 NULL, /* val dup */
459 dictSdsKeyCompare, /* key compare */
460 dictSdsDestructor, /* key destructor */
461 dictRedisObjectDestructor /* val destructor */
462};
463
464/* Db->expires */
465dictType keyptrDictType = {
466 dictSdsHash, /* hash function */
467 NULL, /* key dup */
468 NULL, /* val dup */
469 dictSdsKeyCompare, /* key compare */
470 NULL, /* key destructor */
471 NULL /* val destructor */
472};
473
474/* Command table. sds string -> command struct pointer. */
475dictType commandTableDictType = {
476 dictSdsCaseHash, /* hash function */
477 NULL, /* key dup */
478 NULL, /* val dup */
479 dictSdsKeyCaseCompare, /* key compare */
480 dictSdsDestructor, /* key destructor */
481 NULL /* val destructor */
482};
483
484/* Hash type hash table (note that small hashes are represented with zimpaps) */
485dictType hashDictType = {
486 dictEncObjHash, /* hash function */
487 NULL, /* key dup */
488 NULL, /* val dup */
489 dictEncObjKeyCompare, /* key compare */
490 dictRedisObjectDestructor, /* key destructor */
491 dictRedisObjectDestructor /* val destructor */
492};
493
494/* Keylist hash table type has unencoded redis objects as keys and
495 * lists as values. It's used for blocking operations (BLPOP) and to
496 * map swapped keys to a list of clients waiting for this keys to be loaded. */
497dictType keylistDictType = {
498 dictObjHash, /* hash function */
499 NULL, /* key dup */
500 NULL, /* val dup */
501 dictObjKeyCompare, /* key compare */
502 dictRedisObjectDestructor, /* key destructor */
503 dictListDestructor /* val destructor */
504};
505
506/* Cluster nodes hash table, mapping nodes addresses 1.2.3.4:6379 to
507 * clusterNode structures. */
508dictType clusterNodesDictType = {
509 dictSdsHash, /* hash function */
510 NULL, /* key dup */
511 NULL, /* val dup */
512 dictSdsKeyCompare, /* key compare */
513 dictSdsDestructor, /* key destructor */
514 NULL /* val destructor */
515};
516
517int htNeedsResize(dict *dict) {
518 long long size, used;
519
520 size = dictSlots(dict);
521 used = dictSize(dict);
522 return (size && used && size > DICT_HT_INITIAL_SIZE &&
523 (used*100/size < REDIS_HT_MINFILL));
524}
525
526/* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
527 * we resize the hash table to save memory */
528void tryResizeHashTables(void) {
529 int j;
530
531 for (j = 0; j < server.dbnum; j++) {
532 if (htNeedsResize(server.db[j].dict))
533 dictResize(server.db[j].dict);
534 if (htNeedsResize(server.db[j].expires))
535 dictResize(server.db[j].expires);
536 }
537}
538
539/* Our hash table implementation performs rehashing incrementally while
540 * we write/read from the hash table. Still if the server is idle, the hash
541 * table will use two tables for a long time. So we try to use 1 millisecond
542 * of CPU time at every serverCron() loop in order to rehash some key. */
543void incrementallyRehash(void) {
544 int j;
545
546 for (j = 0; j < server.dbnum; j++) {
547 if (dictIsRehashing(server.db[j].dict)) {
548 dictRehashMilliseconds(server.db[j].dict,1);
549 break; /* already used our millisecond for this loop... */
550 }
551 }
552}
553
554/* This function is called once a background process of some kind terminates,
555 * as we want to avoid resizing the hash tables when there is a child in order
556 * to play well with copy-on-write (otherwise when a resize happens lots of
557 * memory pages are copied). The goal of this function is to update the ability
558 * for dict.c to resize the hash tables accordingly to the fact we have o not
559 * running childs. */
560void updateDictResizePolicy(void) {
561 if (server.rdb_child_pid == -1 && server.aof_child_pid == -1)
562 dictEnableResize();
563 else
564 dictDisableResize();
565}
566
567/* ======================= Cron: called every 100 ms ======================== */
568
569/* Try to expire a few timed out keys. The algorithm used is adaptive and
570 * will use few CPU cycles if there are few expiring keys, otherwise
571 * it will get more aggressive to avoid that too much memory is used by
572 * keys that can be removed from the keyspace. */
573void activeExpireCycle(void) {
574 int j;
575
576 for (j = 0; j < server.dbnum; j++) {
577 int expired;
578 redisDb *db = server.db+j;
579
580 /* Continue to expire if at the end of the cycle more than 25%
581 * of the keys were expired. */
582 do {
583 long num = dictSize(db->expires);
584 long long now = mstime();
585
586 expired = 0;
587 if (num > REDIS_EXPIRELOOKUPS_PER_CRON)
588 num = REDIS_EXPIRELOOKUPS_PER_CRON;
589 while (num--) {
590 dictEntry *de;
591 long long t;
592
593 if ((de = dictGetRandomKey(db->expires)) == NULL) break;
594 t = dictGetSignedIntegerVal(de);
595 if (now > t) {
596 sds key = dictGetKey(de);
597 robj *keyobj = createStringObject(key,sdslen(key));
598
599 propagateExpire(db,keyobj);
600 dbDelete(db,keyobj);
601 decrRefCount(keyobj);
602 expired++;
603 server.stat_expiredkeys++;
604 }
605 }
606 } while (expired > REDIS_EXPIRELOOKUPS_PER_CRON/4);
607 }
608}
609
610void updateLRUClock(void) {
611 server.lruclock = (time(NULL)/REDIS_LRU_CLOCK_RESOLUTION) &
612 REDIS_LRU_CLOCK_MAX;
613}
614
615int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
616 int j, loops = server.cronloops;
617 REDIS_NOTUSED(eventLoop);
618 REDIS_NOTUSED(id);
619 REDIS_NOTUSED(clientData);
620
621 /* We take a cached value of the unix time in the global state because
622 * with virtual memory and aging there is to store the current time
623 * in objects at every object access, and accuracy is not needed.
624 * To access a global var is faster than calling time(NULL) */
625 server.unixtime = time(NULL);
626
627 /* We have just 22 bits per object for LRU information.
628 * So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
629 * 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
630 *
631 * Note that even if this will wrap after 1.5 years it's not a problem,
632 * everything will still work but just some object will appear younger
633 * to Redis. But for this to happen a given object should never be touched
634 * for 1.5 years.
635 *
636 * Note that you can change the resolution altering the
637 * REDIS_LRU_CLOCK_RESOLUTION define.
638 */
639 updateLRUClock();
640
641 /* Record the max memory used since the server was started. */
642 if (zmalloc_used_memory() > server.stat_peak_memory)
643 server.stat_peak_memory = zmalloc_used_memory();
644
645 /* We received a SIGTERM, shutting down here in a safe way, as it is
646 * not ok doing so inside the signal handler. */
647 if (server.shutdown_asap) {
648 if (prepareForShutdown(0) == REDIS_OK) exit(0);
649 redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
650 }
651
652 /* Show some info about non-empty databases */
653 for (j = 0; j < server.dbnum; j++) {
654 long long size, used, vkeys;
655
656 size = dictSlots(server.db[j].dict);
657 used = dictSize(server.db[j].dict);
658 vkeys = dictSize(server.db[j].expires);
659 if (!(loops % 50) && (used || vkeys)) {
660 redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size);
661 /* dictPrintStats(server.dict); */
662 }
663 }
664
665 /* We don't want to resize the hash tables while a bacground saving
666 * is in progress: the saving child is created using fork() that is
667 * implemented with a copy-on-write semantic in most modern systems, so
668 * if we resize the HT while there is the saving child at work actually
669 * a lot of memory movements in the parent will cause a lot of pages
670 * copied. */
671 if (server.rdb_child_pid == -1 && server.aof_child_pid == -1) {
672 if (!(loops % 10)) tryResizeHashTables();
673 if (server.activerehashing) incrementallyRehash();
674 }
675
676 /* Show information about connected clients */
677 if (!(loops % 50)) {
678 redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use",
679 listLength(server.clients)-listLength(server.slaves),
680 listLength(server.slaves),
681 zmalloc_used_memory());
682 }
683
684 /* Close connections of timedout clients */
685 if ((server.maxidletime && !(loops % 100)) || server.bpop_blocked_clients)
686 closeTimedoutClients();
687
688 /* Start a scheduled AOF rewrite if this was requested by the user while
689 * a BGSAVE was in progress. */
690 if (server.rdb_child_pid == -1 && server.aof_child_pid == -1 &&
691 server.aof_rewrite_scheduled)
692 {
693 rewriteAppendOnlyFileBackground();
694 }
695
696 /* Check if a background saving or AOF rewrite in progress terminated. */
697 if (server.rdb_child_pid != -1 || server.aof_child_pid != -1) {
698 int statloc;
699 pid_t pid;
700
701 if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) {
702 int exitcode = WEXITSTATUS(statloc);
703 int bysignal = 0;
704
705 if (WIFSIGNALED(statloc)) bysignal = WTERMSIG(statloc);
706
707 if (pid == server.rdb_child_pid) {
708 backgroundSaveDoneHandler(exitcode,bysignal);
709 } else {
710 backgroundRewriteDoneHandler(exitcode,bysignal);
711 }
712 updateDictResizePolicy();
713 }
714 } else {
715 time_t now = time(NULL);
716
717 /* If there is not a background saving/rewrite in progress check if
718 * we have to save/rewrite now */
719 for (j = 0; j < server.saveparamslen; j++) {
720 struct saveparam *sp = server.saveparams+j;
721
722 if (server.dirty >= sp->changes &&
723 now-server.lastsave > sp->seconds) {
724 redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...",
725 sp->changes, sp->seconds);
726 rdbSaveBackground(server.rdb_filename);
727 break;
728 }
729 }
730
731 /* Trigger an AOF rewrite if needed */
732 if (server.rdb_child_pid == -1 &&
733 server.aof_child_pid == -1 &&
734 server.aof_rewrite_perc &&
735 server.aof_current_size > server.aof_rewrite_min_size)
736 {
737 long long base = server.aof_rewrite_base_size ?
738 server.aof_rewrite_base_size : 1;
739 long long growth = (server.aof_current_size*100/base) - 100;
740 if (growth >= server.aof_rewrite_perc) {
741 redisLog(REDIS_NOTICE,"Starting automatic rewriting of AOF on %lld%% growth",growth);
742 rewriteAppendOnlyFileBackground();
743 }
744 }
745 }
746
747
748 /* If we postponed an AOF buffer flush, let's try to do it every time the
749 * cron function is called. */
750 if (server.aof_flush_postponed_start) flushAppendOnlyFile(0);
751
752 /* Expire a few keys per cycle, only if this is a master.
753 * On slaves we wait for DEL operations synthesized by the master
754 * in order to guarantee a strict consistency. */
755 if (server.masterhost == NULL) activeExpireCycle();
756
757 /* Replication cron function -- used to reconnect to master and
758 * to detect transfer failures. */
759 if (!(loops % 10)) replicationCron();
760
761 /* Run other sub-systems specific cron jobs */
762 if (server.cluster_enabled && !(loops % 10)) clusterCron();
763
764 server.cronloops++;
765 return 100;
766}
767
768/* This function gets called every time Redis is entering the
769 * main loop of the event driven library, that is, before to sleep
770 * for ready file descriptors. */
771void beforeSleep(struct aeEventLoop *eventLoop) {
772 REDIS_NOTUSED(eventLoop);
773 listNode *ln;
774 redisClient *c;
775
776 /* Try to process pending commands for clients that were just unblocked. */
777 while (listLength(server.unblocked_clients)) {
778 ln = listFirst(server.unblocked_clients);
779 redisAssert(ln != NULL);
780 c = ln->value;
781 listDelNode(server.unblocked_clients,ln);
782 c->flags &= ~REDIS_UNBLOCKED;
783
784 /* Process remaining data in the input buffer. */
785 if (c->querybuf && sdslen(c->querybuf) > 0) {
786 server.current_client = c;
787 processInputBuffer(c);
788 server.current_client = NULL;
789 }
790 }
791
792 /* Write the AOF buffer on disk */
793 flushAppendOnlyFile(0);
794}
795
796/* =========================== Server initialization ======================== */
797
798void createSharedObjects(void) {
799 int j;
800
801 shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n"));
802 shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n"));
803 shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n"));
804 shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n"));
805 shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n"));
806 shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n"));
807 shared.cnegone = createObject(REDIS_STRING,sdsnew(":-1\r\n"));
808 shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n"));
809 shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n"));
810 shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n"));
811 shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n"));
812 shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n"));
813 shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew(
814 "-ERR Operation against a key holding the wrong kind of value\r\n"));
815 shared.nokeyerr = createObject(REDIS_STRING,sdsnew(
816 "-ERR no such key\r\n"));
817 shared.syntaxerr = createObject(REDIS_STRING,sdsnew(
818 "-ERR syntax error\r\n"));
819 shared.sameobjecterr = createObject(REDIS_STRING,sdsnew(
820 "-ERR source and destination objects are the same\r\n"));
821 shared.outofrangeerr = createObject(REDIS_STRING,sdsnew(
822 "-ERR index out of range\r\n"));
823 shared.noscripterr = createObject(REDIS_STRING,sdsnew(
824 "-NOSCRIPT No matching script. Please use EVAL.\r\n"));
825 shared.loadingerr = createObject(REDIS_STRING,sdsnew(
826 "-LOADING Redis is loading the dataset in memory\r\n"));
827 shared.slowscripterr = createObject(REDIS_STRING,sdsnew(
828 "-BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.\r\n"));
829 shared.space = createObject(REDIS_STRING,sdsnew(" "));
830 shared.colon = createObject(REDIS_STRING,sdsnew(":"));
831 shared.plus = createObject(REDIS_STRING,sdsnew("+"));
832 shared.select0 = createStringObject("select 0\r\n",10);
833 shared.select1 = createStringObject("select 1\r\n",10);
834 shared.select2 = createStringObject("select 2\r\n",10);
835 shared.select3 = createStringObject("select 3\r\n",10);
836 shared.select4 = createStringObject("select 4\r\n",10);
837 shared.select5 = createStringObject("select 5\r\n",10);
838 shared.select6 = createStringObject("select 6\r\n",10);
839 shared.select7 = createStringObject("select 7\r\n",10);
840 shared.select8 = createStringObject("select 8\r\n",10);
841 shared.select9 = createStringObject("select 9\r\n",10);
842 shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13);
843 shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14);
844 shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15);
845 shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18);
846 shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17);
847 shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19);
848 shared.mbulk3 = createStringObject("*3\r\n",4);
849 shared.mbulk4 = createStringObject("*4\r\n",4);
850 for (j = 0; j < REDIS_SHARED_INTEGERS; j++) {
851 shared.integers[j] = createObject(REDIS_STRING,(void*)(long)j);
852 shared.integers[j]->encoding = REDIS_ENCODING_INT;
853 }
854}
855
856void initServerConfig() {
857 server.port = REDIS_SERVERPORT;
858 server.bindaddr = NULL;
859 server.unixsocket = NULL;
860 server.unixsocketperm = 0;
861 server.ipfd = -1;
862 server.sofd = -1;
863 server.dbnum = REDIS_DEFAULT_DBNUM;
864 server.verbosity = REDIS_NOTICE;
865 server.maxidletime = REDIS_MAXIDLETIME;
866 server.client_max_querybuf_len = REDIS_MAX_QUERYBUF_LEN;
867 server.saveparams = NULL;
868 server.loading = 0;
869 server.logfile = NULL; /* NULL = log on standard output */
870 server.syslog_enabled = 0;
871 server.syslog_ident = zstrdup("redis");
872 server.syslog_facility = LOG_LOCAL0;
873 server.daemonize = 0;
874 server.aof_state = REDIS_AOF_OFF;
875 server.aof_fsync = AOF_FSYNC_EVERYSEC;
876 server.aof_no_fsync_on_rewrite = 0;
877 server.aof_rewrite_perc = REDIS_AOF_REWRITE_PERC;
878 server.aof_rewrite_min_size = REDIS_AOF_REWRITE_MIN_SIZE;
879 server.aof_rewrite_base_size = 0;
880 server.aof_rewrite_scheduled = 0;
881 server.aof_last_fsync = time(NULL);
882 server.aof_fd = -1;
883 server.aof_selected_db = -1; /* Make sure the first time will not match */
884 server.aof_flush_postponed_start = 0;
885 server.pidfile = zstrdup("/var/run/redis.pid");
886 server.rdb_filename = zstrdup("dump.rdb");
887 server.aof_filename = zstrdup("appendonly.aof");
888 server.requirepass = NULL;
889 server.rdb_compression = 1;
890 server.activerehashing = 1;
891 server.maxclients = REDIS_MAX_CLIENTS;
892 server.bpop_blocked_clients = 0;
893 server.maxmemory = 0;
894 server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_LRU;
895 server.maxmemory_samples = 3;
896 server.hash_max_zipmap_entries = REDIS_HASH_MAX_ZIPMAP_ENTRIES;
897 server.hash_max_zipmap_value = REDIS_HASH_MAX_ZIPMAP_VALUE;
898 server.list_max_ziplist_entries = REDIS_LIST_MAX_ZIPLIST_ENTRIES;
899 server.list_max_ziplist_value = REDIS_LIST_MAX_ZIPLIST_VALUE;
900 server.set_max_intset_entries = REDIS_SET_MAX_INTSET_ENTRIES;
901 server.zset_max_ziplist_entries = REDIS_ZSET_MAX_ZIPLIST_ENTRIES;
902 server.zset_max_ziplist_value = REDIS_ZSET_MAX_ZIPLIST_VALUE;
903 server.shutdown_asap = 0;
904 server.repl_ping_slave_period = REDIS_REPL_PING_SLAVE_PERIOD;
905 server.repl_timeout = REDIS_REPL_TIMEOUT;
906 server.cluster_enabled = 0;
907 server.cluster.configfile = zstrdup("nodes.conf");
908 server.lua_caller = NULL;
909 server.lua_time_limit = REDIS_LUA_TIME_LIMIT;
910 server.lua_client = NULL;
911 server.lua_timedout = 0;
912
913 updateLRUClock();
914 resetServerSaveParams();
915
916 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
917 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
918 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
919 /* Replication related */
920 server.masterauth = NULL;
921 server.masterhost = NULL;
922 server.masterport = 6379;
923 server.master = NULL;
924 server.repl_state = REDIS_REPL_NONE;
925 server.repl_syncio_timeout = REDIS_REPL_SYNCIO_TIMEOUT;
926 server.repl_serve_stale_data = 1;
927 server.repl_down_since = -1;
928
929 /* Double constants initialization */
930 R_Zero = 0.0;
931 R_PosInf = 1.0/R_Zero;
932 R_NegInf = -1.0/R_Zero;
933 R_Nan = R_Zero/R_Zero;
934
935 /* Command table -- we intiialize it here as it is part of the
936 * initial configuration, since command names may be changed via
937 * redis.conf using the rename-command directive. */
938 server.commands = dictCreate(&commandTableDictType,NULL);
939 populateCommandTable();
940 server.delCommand = lookupCommandByCString("del");
941 server.multiCommand = lookupCommandByCString("multi");
942
943 /* Slow log */
944 server.slowlog_log_slower_than = REDIS_SLOWLOG_LOG_SLOWER_THAN;
945 server.slowlog_max_len = REDIS_SLOWLOG_MAX_LEN;
946
947 /* Assert */
948 server.assert_failed = "<no assertion failed>";
949 server.assert_file = "<no file>";
950 server.assert_line = 0;
951 server.bug_report_start = 0;
952}
953
954/* This function will try to raise the max number of open files accordingly to
955 * the configured max number of clients. It will also account for 32 additional
956 * file descriptors as we need a few more for persistence, listening
957 * sockets, log files and so forth.
958 *
959 * If it will not be possible to set the limit accordingly to the configured
960 * max number of clients, the function will do the reverse setting
961 * server.maxclients to the value that we can actually handle. */
962void adjustOpenFilesLimit(void) {
963 rlim_t maxfiles = server.maxclients+32;
964 struct rlimit limit;
965
966 if (maxfiles < 1024) maxfiles = 1024;
967 if (getrlimit(RLIMIT_NOFILE,&limit) == -1) {
968 redisLog(REDIS_WARNING,"Unable to obtain the current NOFILE limit (%s), assuming 1024 and setting the max clients configuration accordingly.",
969 strerror(errno));
970 server.maxclients = 1024-32;
971 } else {
972 rlim_t oldlimit = limit.rlim_cur;
973
974 /* Set the max number of files if the current limit is not enough
975 * for our needs. */
976 if (oldlimit < maxfiles) {
977 limit.rlim_cur = maxfiles;
978 limit.rlim_max = maxfiles;
979 if (setrlimit(RLIMIT_NOFILE,&limit) == -1) {
980 server.maxclients = oldlimit-32;
981 redisLog(REDIS_WARNING,"Unable to set the max number of files limit to %d (%s), setting the max clients configuration to %d.",
982 (int) maxfiles, strerror(errno), (int) server.maxclients);
983 } else {
984 redisLog(REDIS_NOTICE,"Max number of open files set to %d",
985 (int) maxfiles);
986 }
987 }
988 }
989}
990
991void initServer() {
992 int j;
993
994 signal(SIGHUP, SIG_IGN);
995 signal(SIGPIPE, SIG_IGN);
996 setupSignalHandlers();
997
998 if (server.syslog_enabled) {
999 openlog(server.syslog_ident, LOG_PID | LOG_NDELAY | LOG_NOWAIT,
1000 server.syslog_facility);
1001 }
1002
1003 server.current_client = NULL;
1004 server.clients = listCreate();
1005 server.slaves = listCreate();
1006 server.monitors = listCreate();
1007 server.unblocked_clients = listCreate();
1008
1009 createSharedObjects();
1010 adjustOpenFilesLimit();
1011 server.el = aeCreateEventLoop(server.maxclients+1024);
1012 server.db = zmalloc(sizeof(redisDb)*server.dbnum);
1013
1014 if (server.port != 0) {
1015 server.ipfd = anetTcpServer(server.neterr,server.port,server.bindaddr);
1016 if (server.ipfd == ANET_ERR) {
1017 redisLog(REDIS_WARNING, "Opening port %d: %s",
1018 server.port, server.neterr);
1019 exit(1);
1020 }
1021 }
1022 if (server.unixsocket != NULL) {
1023 unlink(server.unixsocket); /* don't care if this fails */
1024 server.sofd = anetUnixServer(server.neterr,server.unixsocket,server.unixsocketperm);
1025 if (server.sofd == ANET_ERR) {
1026 redisLog(REDIS_WARNING, "Opening socket: %s", server.neterr);
1027 exit(1);
1028 }
1029 }
1030 if (server.ipfd < 0 && server.sofd < 0) {
1031 redisLog(REDIS_WARNING, "Configured to not listen anywhere, exiting.");
1032 exit(1);
1033 }
1034 for (j = 0; j < server.dbnum; j++) {
1035 server.db[j].dict = dictCreate(&dbDictType,NULL);
1036 server.db[j].expires = dictCreate(&keyptrDictType,NULL);
1037 server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL);
1038 server.db[j].watched_keys = dictCreate(&keylistDictType,NULL);
1039 server.db[j].id = j;
1040 }
1041 server.pubsub_channels = dictCreate(&keylistDictType,NULL);
1042 server.pubsub_patterns = listCreate();
1043 listSetFreeMethod(server.pubsub_patterns,freePubsubPattern);
1044 listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern);
1045 server.cronloops = 0;
1046 server.rdb_child_pid = -1;
1047 server.aof_child_pid = -1;
1048 server.aof_rewrite_buf = sdsempty();
1049 server.aof_buf = sdsempty();
1050 server.lastsave = time(NULL);
1051 server.dirty = 0;
1052 server.stat_numcommands = 0;
1053 server.stat_numconnections = 0;
1054 server.stat_expiredkeys = 0;
1055 server.stat_evictedkeys = 0;
1056 server.stat_starttime = time(NULL);
1057 server.stat_keyspace_misses = 0;
1058 server.stat_keyspace_hits = 0;
1059 server.stat_peak_memory = 0;
1060 server.stat_fork_time = 0;
1061 server.stat_rejected_conn = 0;
1062 server.unixtime = time(NULL);
1063 aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL);
1064 if (server.ipfd > 0 && aeCreateFileEvent(server.el,server.ipfd,AE_READABLE,
1065 acceptTcpHandler,NULL) == AE_ERR) oom("creating file event");
1066 if (server.sofd > 0 && aeCreateFileEvent(server.el,server.sofd,AE_READABLE,
1067 acceptUnixHandler,NULL) == AE_ERR) oom("creating file event");
1068
1069 if (server.aof_state == REDIS_AOF_ON) {
1070 server.aof_fd = open(server.aof_filename,
1071 O_WRONLY|O_APPEND|O_CREAT,0644);
1072 if (server.aof_fd == -1) {
1073 redisLog(REDIS_WARNING, "Can't open the append-only file: %s",
1074 strerror(errno));
1075 exit(1);
1076 }
1077 }
1078
1079 if (server.cluster_enabled) clusterInit();
1080 scriptingInit();
1081 slowlogInit();
1082 bioInit();
1083}
1084
1085/* Populates the Redis Command Table starting from the hard coded list
1086 * we have on top of redis.c file. */
1087void populateCommandTable(void) {
1088 int j;
1089 int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand);
1090
1091 for (j = 0; j < numcommands; j++) {
1092 struct redisCommand *c = redisCommandTable+j;
1093 char *f = c->sflags;
1094 int retval;
1095
1096 while(*f != '\0') {
1097 switch(*f) {
1098 case 'w': c->flags |= REDIS_CMD_WRITE; break;
1099 case 'r': c->flags |= REDIS_CMD_READONLY; break;
1100 case 'm': c->flags |= REDIS_CMD_DENYOOM; break;
1101 case 'a': c->flags |= REDIS_CMD_ADMIN; break;
1102 case 'p': c->flags |= REDIS_CMD_PUBSUB; break;
1103 case 'f': c->flags |= REDIS_CMD_FORCE_REPLICATION; break;
1104 case 's': c->flags |= REDIS_CMD_NOSCRIPT; break;
1105 case 'R': c->flags |= REDIS_CMD_RANDOM; break;
1106 default: redisPanic("Unsupported command flag"); break;
1107 }
1108 f++;
1109 }
1110
1111 retval = dictAdd(server.commands, sdsnew(c->name), c);
1112 assert(retval == DICT_OK);
1113 }
1114}
1115
1116void resetCommandTableStats(void) {
1117 int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand);
1118 int j;
1119
1120 for (j = 0; j < numcommands; j++) {
1121 struct redisCommand *c = redisCommandTable+j;
1122
1123 c->microseconds = 0;
1124 c->calls = 0;
1125 }
1126}
1127
1128/* ====================== Commands lookup and execution ===================== */
1129
1130struct redisCommand *lookupCommand(sds name) {
1131 return dictFetchValue(server.commands, name);
1132}
1133
1134struct redisCommand *lookupCommandByCString(char *s) {
1135 struct redisCommand *cmd;
1136 sds name = sdsnew(s);
1137
1138 cmd = dictFetchValue(server.commands, name);
1139 sdsfree(name);
1140 return cmd;
1141}
1142
1143/* Call() is the core of Redis execution of a command */
1144void call(redisClient *c) {
1145 long long dirty, start = ustime(), duration;
1146
1147 dirty = server.dirty;
1148 c->cmd->proc(c);
1149 dirty = server.dirty-dirty;
1150 duration = ustime()-start;
1151 c->cmd->microseconds += duration;
1152 slowlogPushEntryIfNeeded(c->argv,c->argc,duration);
1153 c->cmd->calls++;
1154
1155 if (server.aof_state != REDIS_AOF_OFF && dirty > 0)
1156 feedAppendOnlyFile(c->cmd,c->db->id,c->argv,c->argc);
1157 if ((dirty > 0 || c->cmd->flags & REDIS_CMD_FORCE_REPLICATION) &&
1158 listLength(server.slaves))
1159 replicationFeedSlaves(server.slaves,c->db->id,c->argv,c->argc);
1160 if (listLength(server.monitors))
1161 replicationFeedMonitors(server.monitors,c->db->id,c->argv,c->argc);
1162 server.stat_numcommands++;
1163}
1164
1165/* If this function gets called we already read a whole
1166 * command, argments are in the client argv/argc fields.
1167 * processCommand() execute the command or prepare the
1168 * server for a bulk read from the client.
1169 *
1170 * If 1 is returned the client is still alive and valid and
1171 * and other operations can be performed by the caller. Otherwise
1172 * if 0 is returned the client was destroied (i.e. after QUIT). */
1173int processCommand(redisClient *c) {
1174 /* The QUIT command is handled separately. Normal command procs will
1175 * go through checking for replication and QUIT will cause trouble
1176 * when FORCE_REPLICATION is enabled and would be implemented in
1177 * a regular command proc. */
1178 if (!strcasecmp(c->argv[0]->ptr,"quit")) {
1179 addReply(c,shared.ok);
1180 c->flags |= REDIS_CLOSE_AFTER_REPLY;
1181 return REDIS_ERR;
1182 }
1183
1184 /* Now lookup the command and check ASAP about trivial error conditions
1185 * such as wrong arity, bad command name and so forth. */
1186 c->cmd = c->lastcmd = lookupCommand(c->argv[0]->ptr);
1187 if (!c->cmd) {
1188 addReplyErrorFormat(c,"unknown command '%s'",
1189 (char*)c->argv[0]->ptr);
1190 return REDIS_OK;
1191 } else if ((c->cmd->arity > 0 && c->cmd->arity != c->argc) ||
1192 (c->argc < -c->cmd->arity)) {
1193 addReplyErrorFormat(c,"wrong number of arguments for '%s' command",
1194 c->cmd->name);
1195 return REDIS_OK;
1196 }
1197
1198 /* Check if the user is authenticated */
1199 if (server.requirepass && !c->authenticated && c->cmd->proc != authCommand)
1200 {
1201 addReplyError(c,"operation not permitted");
1202 return REDIS_OK;
1203 }
1204
1205 /* If cluster is enabled, redirect here */
1206 if (server.cluster_enabled &&
1207 !(c->cmd->getkeys_proc == NULL && c->cmd->firstkey == 0)) {
1208 int hashslot;
1209
1210 if (server.cluster.state != REDIS_CLUSTER_OK) {
1211 addReplyError(c,"The cluster is down. Check with CLUSTER INFO for more information");
1212 return REDIS_OK;
1213 } else {
1214 int ask;
1215 clusterNode *n = getNodeByQuery(c,c->cmd,c->argv,c->argc,&hashslot,&ask);
1216 if (n == NULL) {
1217 addReplyError(c,"Multi keys request invalid in cluster");
1218 return REDIS_OK;
1219 } else if (n != server.cluster.myself) {
1220 addReplySds(c,sdscatprintf(sdsempty(),
1221 "-%s %d %s:%d\r\n", ask ? "ASK" : "MOVED",
1222 hashslot,n->ip,n->port));
1223 return REDIS_OK;
1224 }
1225 }
1226 }
1227
1228 /* Handle the maxmemory directive.
1229 *
1230 * First we try to free some memory if possible (if there are volatile
1231 * keys in the dataset). If there are not the only thing we can do
1232 * is returning an error. */
1233 if (server.maxmemory) freeMemoryIfNeeded();
1234 if (server.maxmemory && (c->cmd->flags & REDIS_CMD_DENYOOM) &&
1235 zmalloc_used_memory() > server.maxmemory)
1236 {
1237 addReplyError(c,"command not allowed when used memory > 'maxmemory'");
1238 return REDIS_OK;
1239 }
1240
1241 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
1242 if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0)
1243 &&
1244 c->cmd->proc != subscribeCommand &&
1245 c->cmd->proc != unsubscribeCommand &&
1246 c->cmd->proc != psubscribeCommand &&
1247 c->cmd->proc != punsubscribeCommand) {
1248 addReplyError(c,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
1249 return REDIS_OK;
1250 }
1251
1252 /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
1253 * we are a slave with a broken link with master. */
1254 if (server.masterhost && server.repl_state != REDIS_REPL_CONNECTED &&
1255 server.repl_serve_stale_data == 0 &&
1256 c->cmd->proc != infoCommand && c->cmd->proc != slaveofCommand)
1257 {
1258 addReplyError(c,
1259 "link with MASTER is down and slave-serve-stale-data is set to no");
1260 return REDIS_OK;
1261 }
1262
1263 /* Loading DB? Return an error if the command is not INFO */
1264 if (server.loading && c->cmd->proc != infoCommand) {
1265 addReply(c, shared.loadingerr);
1266 return REDIS_OK;
1267 }
1268
1269 /* Lua script too slow? Only allow SHUTDOWN NOSAVE and SCRIPT KILL. */
1270 if (server.lua_timedout &&
1271 !(c->cmd->proc != shutdownCommand &&
1272 c->argc == 2 &&
1273 tolower(((char*)c->argv[1]->ptr)[0]) == 'n') &&
1274 !(c->cmd->proc == scriptCommand &&
1275 c->argc == 2 &&
1276 tolower(((char*)c->argv[1]->ptr)[0]) == 'k'))
1277 {
1278 addReply(c, shared.slowscripterr);
1279 return REDIS_OK;
1280 }
1281
1282 /* Exec the command */
1283 if (c->flags & REDIS_MULTI &&
1284 c->cmd->proc != execCommand && c->cmd->proc != discardCommand &&
1285 c->cmd->proc != multiCommand && c->cmd->proc != watchCommand)
1286 {
1287 queueMultiCommand(c);
1288 addReply(c,shared.queued);
1289 } else {
1290 call(c);
1291 }
1292 return REDIS_OK;
1293}
1294
1295/*================================== Shutdown =============================== */
1296
1297int prepareForShutdown(int flags) {
1298 int save = flags & REDIS_SHUTDOWN_SAVE;
1299 int nosave = flags & REDIS_SHUTDOWN_NOSAVE;
1300
1301 redisLog(REDIS_WARNING,"User requested shutdown...");
1302 /* Kill the saving child if there is a background saving in progress.
1303 We want to avoid race conditions, for instance our saving child may
1304 overwrite the synchronous saving did by SHUTDOWN. */
1305 if (server.rdb_child_pid != -1) {
1306 redisLog(REDIS_WARNING,"There is a child saving an .rdb. Killing it!");
1307 kill(server.rdb_child_pid,SIGKILL);
1308 rdbRemoveTempFile(server.rdb_child_pid);
1309 }
1310 if (server.aof_state != REDIS_AOF_OFF) {
1311 /* Kill the AOF saving child as the AOF we already have may be longer
1312 * but contains the full dataset anyway. */
1313 if (server.aof_child_pid != -1) {
1314 redisLog(REDIS_WARNING,
1315 "There is a child rewriting the AOF. Killing it!");
1316 kill(server.aof_child_pid,SIGKILL);
1317 }
1318 /* Append only file: fsync() the AOF and exit */
1319 redisLog(REDIS_NOTICE,"Calling fsync() on the AOF file.");
1320 aof_fsync(server.aof_fd);
1321 }
1322 if ((server.saveparamslen > 0 && !nosave) || save) {
1323 redisLog(REDIS_NOTICE,"Saving the final RDB snapshot before exiting.");
1324 /* Snapshotting. Perform a SYNC SAVE and exit */
1325 if (rdbSave(server.rdb_filename) != REDIS_OK) {
1326 /* Ooops.. error saving! The best we can do is to continue
1327 * operating. Note that if there was a background saving process,
1328 * in the next cron() Redis will be notified that the background
1329 * saving aborted, handling special stuff like slaves pending for
1330 * synchronization... */
1331 redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit.");
1332 return REDIS_ERR;
1333 }
1334 }
1335 if (server.daemonize) {
1336 redisLog(REDIS_NOTICE,"Removing the pid file.");
1337 unlink(server.pidfile);
1338 }
1339 /* Close the listening sockets. Apparently this allows faster restarts. */
1340 if (server.ipfd != -1) close(server.ipfd);
1341 if (server.sofd != -1) close(server.sofd);
1342 if (server.unixsocket) {
1343 redisLog(REDIS_NOTICE,"Removing the unix socket file.");
1344 unlink(server.unixsocket); /* don't care if this fails */
1345 }
1346
1347 redisLog(REDIS_WARNING,"Redis is now ready to exit, bye bye...");
1348 return REDIS_OK;
1349}
1350
1351/*================================== Commands =============================== */
1352
1353void authCommand(redisClient *c) {
1354 if (!server.requirepass) {
1355 addReplyError(c,"Client sent AUTH, but no password is set");
1356 } else if (!strcmp(c->argv[1]->ptr, server.requirepass)) {
1357 c->authenticated = 1;
1358 addReply(c,shared.ok);
1359 } else {
1360 c->authenticated = 0;
1361 addReplyError(c,"invalid password");
1362 }
1363}
1364
1365void pingCommand(redisClient *c) {
1366 addReply(c,shared.pong);
1367}
1368
1369void echoCommand(redisClient *c) {
1370 addReplyBulk(c,c->argv[1]);
1371}
1372
1373/* Convert an amount of bytes into a human readable string in the form
1374 * of 100B, 2G, 100M, 4K, and so forth. */
1375void bytesToHuman(char *s, unsigned long long n) {
1376 double d;
1377
1378 if (n < 1024) {
1379 /* Bytes */
1380 sprintf(s,"%lluB",n);
1381 return;
1382 } else if (n < (1024*1024)) {
1383 d = (double)n/(1024);
1384 sprintf(s,"%.2fK",d);
1385 } else if (n < (1024LL*1024*1024)) {
1386 d = (double)n/(1024*1024);
1387 sprintf(s,"%.2fM",d);
1388 } else if (n < (1024LL*1024*1024*1024)) {
1389 d = (double)n/(1024LL*1024*1024);
1390 sprintf(s,"%.2fG",d);
1391 }
1392}
1393
1394/* Create the string returned by the INFO command. This is decoupled
1395 * by the INFO command itself as we need to report the same information
1396 * on memory corruption problems. */
1397sds genRedisInfoString(char *section) {
1398 sds info = sdsempty();
1399 time_t uptime = time(NULL)-server.stat_starttime;
1400 int j, numcommands;
1401 struct rusage self_ru, c_ru;
1402 unsigned long lol, bib;
1403 int allsections = 0, defsections = 0;
1404 int sections = 0;
1405
1406 if (section) {
1407 allsections = strcasecmp(section,"all") == 0;
1408 defsections = strcasecmp(section,"default") == 0;
1409 }
1410
1411 getrusage(RUSAGE_SELF, &self_ru);
1412 getrusage(RUSAGE_CHILDREN, &c_ru);
1413 getClientsMaxBuffers(&lol,&bib);
1414
1415 /* Server */
1416 if (allsections || defsections || !strcasecmp(section,"server")) {
1417 if (sections++) info = sdscat(info,"\r\n");
1418 info = sdscatprintf(info,
1419 "# Server\r\n"
1420 "redis_version:%s\r\n"
1421 "redis_git_sha1:%s\r\n"
1422 "redis_git_dirty:%d\r\n"
1423 "arch_bits:%s\r\n"
1424 "multiplexing_api:%s\r\n"
1425 "gcc_version:%d.%d.%d\r\n"
1426 "process_id:%ld\r\n"
1427 "tcp_port:%d\r\n"
1428 "uptime_in_seconds:%ld\r\n"
1429 "uptime_in_days:%ld\r\n"
1430 "lru_clock:%ld\r\n",
1431 REDIS_VERSION,
1432 redisGitSHA1(),
1433 strtol(redisGitDirty(),NULL,10) > 0,
1434 (sizeof(long) == 8) ? "64" : "32",
1435 aeGetApiName(),
1436#ifdef __GNUC__
1437 __GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__,
1438#else
1439 0,0,0,
1440#endif
1441 (long) getpid(),
1442 server.port,
1443 uptime,
1444 uptime/(3600*24),
1445 (unsigned long) server.lruclock);
1446 }
1447
1448 /* Clients */
1449 if (allsections || defsections || !strcasecmp(section,"clients")) {
1450 if (sections++) info = sdscat(info,"\r\n");
1451 info = sdscatprintf(info,
1452 "# Clients\r\n"
1453 "connected_clients:%d\r\n"
1454 "client_longest_output_list:%lu\r\n"
1455 "client_biggest_input_buf:%lu\r\n"
1456 "blocked_clients:%d\r\n",
1457 listLength(server.clients)-listLength(server.slaves),
1458 lol, bib,
1459 server.bpop_blocked_clients);
1460 }
1461
1462 /* Memory */
1463 if (allsections || defsections || !strcasecmp(section,"memory")) {
1464 char hmem[64];
1465 char peak_hmem[64];
1466
1467 bytesToHuman(hmem,zmalloc_used_memory());
1468 bytesToHuman(peak_hmem,server.stat_peak_memory);
1469 if (sections++) info = sdscat(info,"\r\n");
1470 info = sdscatprintf(info,
1471 "# Memory\r\n"
1472 "used_memory:%zu\r\n"
1473 "used_memory_human:%s\r\n"
1474 "used_memory_rss:%zu\r\n"
1475 "used_memory_peak:%zu\r\n"
1476 "used_memory_peak_human:%s\r\n"
1477 "used_memory_lua:%lld\r\n"
1478 "mem_fragmentation_ratio:%.2f\r\n"
1479 "mem_allocator:%s\r\n",
1480 zmalloc_used_memory(),
1481 hmem,
1482 zmalloc_get_rss(),
1483 server.stat_peak_memory,
1484 peak_hmem,
1485 ((long long)lua_gc(server.lua,LUA_GCCOUNT,0))*1024LL,
1486 zmalloc_get_fragmentation_ratio(),
1487 ZMALLOC_LIB
1488 );
1489 }
1490
1491 /* Persistence */
1492 if (allsections || defsections || !strcasecmp(section,"persistence")) {
1493 if (sections++) info = sdscat(info,"\r\n");
1494 info = sdscatprintf(info,
1495 "# Persistence\r\n"
1496 "loading:%d\r\n"
1497 "aof_enabled:%d\r\n"
1498 "changes_since_last_save:%lld\r\n"
1499 "bgsave_in_progress:%d\r\n"
1500 "last_save_time:%ld\r\n"
1501 "bgrewriteaof_in_progress:%d\r\n",
1502 server.loading,
1503 server.aof_state != REDIS_AOF_OFF,
1504 server.dirty,
1505 server.rdb_child_pid != -1,
1506 server.lastsave,
1507 server.aof_child_pid != -1);
1508
1509 if (server.aof_state != REDIS_AOF_OFF) {
1510 info = sdscatprintf(info,
1511 "aof_current_size:%lld\r\n"
1512 "aof_base_size:%lld\r\n"
1513 "aof_pending_rewrite:%d\r\n"
1514 "aof_buffer_length:%zu\r\n"
1515 "aof_pending_bio_fsync:%llu\r\n",
1516 (long long) server.aof_current_size,
1517 (long long) server.aof_rewrite_base_size,
1518 server.aof_rewrite_scheduled,
1519 sdslen(server.aof_buf),
1520 bioPendingJobsOfType(REDIS_BIO_AOF_FSYNC));
1521 }
1522
1523 if (server.loading) {
1524 double perc;
1525 time_t eta, elapsed;
1526 off_t remaining_bytes = server.loading_total_bytes-
1527 server.loading_loaded_bytes;
1528
1529 perc = ((double)server.loading_loaded_bytes /
1530 server.loading_total_bytes) * 100;
1531
1532 elapsed = time(NULL)-server.loading_start_time;
1533 if (elapsed == 0) {
1534 eta = 1; /* A fake 1 second figure if we don't have
1535 enough info */
1536 } else {
1537 eta = (elapsed*remaining_bytes)/server.loading_loaded_bytes;
1538 }
1539
1540 info = sdscatprintf(info,
1541 "loading_start_time:%ld\r\n"
1542 "loading_total_bytes:%llu\r\n"
1543 "loading_loaded_bytes:%llu\r\n"
1544 "loading_loaded_perc:%.2f\r\n"
1545 "loading_eta_seconds:%ld\r\n"
1546 ,(unsigned long) server.loading_start_time,
1547 (unsigned long long) server.loading_total_bytes,
1548 (unsigned long long) server.loading_loaded_bytes,
1549 perc,
1550 eta
1551 );
1552 }
1553 }
1554
1555 /* Stats */
1556 if (allsections || defsections || !strcasecmp(section,"stats")) {
1557 if (sections++) info = sdscat(info,"\r\n");
1558 info = sdscatprintf(info,
1559 "# Stats\r\n"
1560 "total_connections_received:%lld\r\n"
1561 "total_commands_processed:%lld\r\n"
1562 "rejected_connections:%lld\r\n"
1563 "expired_keys:%lld\r\n"
1564 "evicted_keys:%lld\r\n"
1565 "keyspace_hits:%lld\r\n"
1566 "keyspace_misses:%lld\r\n"
1567 "pubsub_channels:%ld\r\n"
1568 "pubsub_patterns:%u\r\n"
1569 "latest_fork_usec:%lld\r\n",
1570 server.stat_numconnections,
1571 server.stat_numcommands,
1572 server.stat_rejected_conn,
1573 server.stat_expiredkeys,
1574 server.stat_evictedkeys,
1575 server.stat_keyspace_hits,
1576 server.stat_keyspace_misses,
1577 dictSize(server.pubsub_channels),
1578 listLength(server.pubsub_patterns),
1579 server.stat_fork_time);
1580 }
1581
1582 /* Replication */
1583 if (allsections || defsections || !strcasecmp(section,"replication")) {
1584 if (sections++) info = sdscat(info,"\r\n");
1585 info = sdscatprintf(info,
1586 "# Replication\r\n"
1587 "role:%s\r\n",
1588 server.masterhost == NULL ? "master" : "slave");
1589 if (server.masterhost) {
1590 info = sdscatprintf(info,
1591 "master_host:%s\r\n"
1592 "master_port:%d\r\n"
1593 "master_link_status:%s\r\n"
1594 "master_last_io_seconds_ago:%d\r\n"
1595 "master_sync_in_progress:%d\r\n"
1596 ,server.masterhost,
1597 server.masterport,
1598 (server.repl_state == REDIS_REPL_CONNECTED) ?
1599 "up" : "down",
1600 server.master ?
1601 ((int)(time(NULL)-server.master->lastinteraction)) : -1,
1602 server.repl_state == REDIS_REPL_TRANSFER
1603 );
1604
1605 if (server.repl_state == REDIS_REPL_TRANSFER) {
1606 info = sdscatprintf(info,
1607 "master_sync_left_bytes:%ld\r\n"
1608 "master_sync_last_io_seconds_ago:%d\r\n"
1609 ,(long)server.repl_transfer_left,
1610 (int)(time(NULL)-server.repl_transfer_lastio)
1611 );
1612 }
1613
1614 if (server.repl_state != REDIS_REPL_CONNECTED) {
1615 info = sdscatprintf(info,
1616 "master_link_down_since_seconds:%ld\r\n",
1617 (long)time(NULL)-server.repl_down_since);
1618 }
1619 }
1620 info = sdscatprintf(info,
1621 "connected_slaves:%d\r\n",
1622 listLength(server.slaves));
1623 if (listLength(server.slaves)) {
1624 int slaveid = 0;
1625 listNode *ln;
1626 listIter li;
1627
1628 listRewind(server.slaves,&li);
1629 while((ln = listNext(&li))) {
1630 redisClient *slave = listNodeValue(ln);
1631 char *state = NULL;
1632 char ip[32];
1633 int port;
1634
1635 if (anetPeerToString(slave->fd,ip,&port) == -1) continue;
1636 switch(slave->replstate) {
1637 case REDIS_REPL_WAIT_BGSAVE_START:
1638 case REDIS_REPL_WAIT_BGSAVE_END:
1639 state = "wait_bgsave";
1640 break;
1641 case REDIS_REPL_SEND_BULK:
1642 state = "send_bulk";
1643 break;
1644 case REDIS_REPL_ONLINE:
1645 state = "online";
1646 break;
1647 }
1648 if (state == NULL) continue;
1649 info = sdscatprintf(info,"slave%d:%s,%d,%s\r\n",
1650 slaveid,ip,port,state);
1651 slaveid++;
1652 }
1653 }
1654 }
1655
1656 /* CPU */
1657 if (allsections || defsections || !strcasecmp(section,"cpu")) {
1658 if (sections++) info = sdscat(info,"\r\n");
1659 info = sdscatprintf(info,
1660 "# CPU\r\n"
1661 "used_cpu_sys:%.2f\r\n"
1662 "used_cpu_user:%.2f\r\n"
1663 "used_cpu_sys_children:%.2f\r\n"
1664 "used_cpu_user_children:%.2f\r\n",
1665 (float)self_ru.ru_stime.tv_sec+(float)self_ru.ru_stime.tv_usec/1000000,
1666 (float)self_ru.ru_utime.tv_sec+(float)self_ru.ru_utime.tv_usec/1000000,
1667 (float)c_ru.ru_stime.tv_sec+(float)c_ru.ru_stime.tv_usec/1000000,
1668 (float)c_ru.ru_utime.tv_sec+(float)c_ru.ru_utime.tv_usec/1000000);
1669 }
1670
1671 /* cmdtime */
1672 if (allsections || !strcasecmp(section,"commandstats")) {
1673 if (sections++) info = sdscat(info,"\r\n");
1674 info = sdscatprintf(info, "# Commandstats\r\n");
1675 numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand);
1676 for (j = 0; j < numcommands; j++) {
1677 struct redisCommand *c = redisCommandTable+j;
1678
1679 if (!c->calls) continue;
1680 info = sdscatprintf(info,
1681 "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n",
1682 c->name, c->calls, c->microseconds,
1683 (c->calls == 0) ? 0 : ((float)c->microseconds/c->calls));
1684 }
1685 }
1686
1687 /* Clusetr */
1688 if (allsections || defsections || !strcasecmp(section,"cluster")) {
1689 if (sections++) info = sdscat(info,"\r\n");
1690 info = sdscatprintf(info,
1691 "# Cluster\r\n"
1692 "cluster_enabled:%d\r\n",
1693 server.cluster_enabled);
1694 }
1695
1696 /* Key space */
1697 if (allsections || defsections || !strcasecmp(section,"keyspace")) {
1698 if (sections++) info = sdscat(info,"\r\n");
1699 info = sdscatprintf(info, "# Keyspace\r\n");
1700 for (j = 0; j < server.dbnum; j++) {
1701 long long keys, vkeys;
1702
1703 keys = dictSize(server.db[j].dict);
1704 vkeys = dictSize(server.db[j].expires);
1705 if (keys || vkeys) {
1706 info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n",
1707 j, keys, vkeys);
1708 }
1709 }
1710 }
1711 return info;
1712}
1713
1714void infoCommand(redisClient *c) {
1715 char *section = c->argc == 2 ? c->argv[1]->ptr : "default";
1716
1717 if (c->argc > 2) {
1718 addReply(c,shared.syntaxerr);
1719 return;
1720 }
1721 sds info = genRedisInfoString(section);
1722 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
1723 (unsigned long)sdslen(info)));
1724 addReplySds(c,info);
1725 addReply(c,shared.crlf);
1726}
1727
1728void monitorCommand(redisClient *c) {
1729 /* ignore MONITOR if aleady slave or in monitor mode */
1730 if (c->flags & REDIS_SLAVE) return;
1731
1732 c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
1733 c->slaveseldb = 0;
1734 listAddNodeTail(server.monitors,c);
1735 addReply(c,shared.ok);
1736}
1737
1738/* ============================ Maxmemory directive ======================== */
1739
1740/* This function gets called when 'maxmemory' is set on the config file to limit
1741 * the max memory used by the server, and we are out of memory.
1742 * This function will try to, in order:
1743 *
1744 * - Free objects from the free list
1745 * - Try to remove keys with an EXPIRE set
1746 *
1747 * It is not possible to free enough memory to reach used-memory < maxmemory
1748 * the server will start refusing commands that will enlarge even more the
1749 * memory usage.
1750 */
1751void freeMemoryIfNeeded(void) {
1752 /* Remove keys accordingly to the active policy as long as we are
1753 * over the memory limit. */
1754 if (server.maxmemory_policy == REDIS_MAXMEMORY_NO_EVICTION) return;
1755
1756 while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) {
1757 int j, k, freed = 0;
1758
1759 for (j = 0; j < server.dbnum; j++) {
1760 long bestval = 0; /* just to prevent warning */
1761 sds bestkey = NULL;
1762 struct dictEntry *de;
1763 redisDb *db = server.db+j;
1764 dict *dict;
1765
1766 if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
1767 server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM)
1768 {
1769 dict = server.db[j].dict;
1770 } else {
1771 dict = server.db[j].expires;
1772 }
1773 if (dictSize(dict) == 0) continue;
1774
1775 /* volatile-random and allkeys-random policy */
1776 if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM ||
1777 server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_RANDOM)
1778 {
1779 de = dictGetRandomKey(dict);
1780 bestkey = dictGetKey(de);
1781 }
1782
1783 /* volatile-lru and allkeys-lru policy */
1784 else if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
1785 server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU)
1786 {
1787 for (k = 0; k < server.maxmemory_samples; k++) {
1788 sds thiskey;
1789 long thisval;
1790 robj *o;
1791
1792 de = dictGetRandomKey(dict);
1793 thiskey = dictGetKey(de);
1794 /* When policy is volatile-lru we need an additonal lookup
1795 * to locate the real key, as dict is set to db->expires. */
1796 if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU)
1797 de = dictFind(db->dict, thiskey);
1798 o = dictGetVal(de);
1799 thisval = estimateObjectIdleTime(o);
1800
1801 /* Higher idle time is better candidate for deletion */
1802 if (bestkey == NULL || thisval > bestval) {
1803 bestkey = thiskey;
1804 bestval = thisval;
1805 }
1806 }
1807 }
1808
1809 /* volatile-ttl */
1810 else if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_TTL) {
1811 for (k = 0; k < server.maxmemory_samples; k++) {
1812 sds thiskey;
1813 long thisval;
1814
1815 de = dictGetRandomKey(dict);
1816 thiskey = dictGetKey(de);
1817 thisval = (long) dictGetVal(de);
1818
1819 /* Expire sooner (minor expire unix timestamp) is better
1820 * candidate for deletion */
1821 if (bestkey == NULL || thisval < bestval) {
1822 bestkey = thiskey;
1823 bestval = thisval;
1824 }
1825 }
1826 }
1827
1828 /* Finally remove the selected key. */
1829 if (bestkey) {
1830 robj *keyobj = createStringObject(bestkey,sdslen(bestkey));
1831 propagateExpire(db,keyobj);
1832 dbDelete(db,keyobj);
1833 server.stat_evictedkeys++;
1834 decrRefCount(keyobj);
1835 freed++;
1836 }
1837 }
1838 if (!freed) return; /* nothing to free... */
1839 }
1840}
1841
1842/* =================================== Main! ================================ */
1843
1844#ifdef __linux__
1845int linuxOvercommitMemoryValue(void) {
1846 FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r");
1847 char buf[64];
1848
1849 if (!fp) return -1;
1850 if (fgets(buf,64,fp) == NULL) {
1851 fclose(fp);
1852 return -1;
1853 }
1854 fclose(fp);
1855
1856 return atoi(buf);
1857}
1858
1859void linuxOvercommitMemoryWarning(void) {
1860 if (linuxOvercommitMemoryValue() == 0) {
1861 redisLog(REDIS_WARNING,"WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.");
1862 }
1863}
1864#endif /* __linux__ */
1865
1866void createPidFile(void) {
1867 /* Try to write the pid file in a best-effort way. */
1868 FILE *fp = fopen(server.pidfile,"w");
1869 if (fp) {
1870 fprintf(fp,"%d\n",(int)getpid());
1871 fclose(fp);
1872 }
1873}
1874
1875void daemonize(void) {
1876 int fd;
1877
1878 if (fork() != 0) exit(0); /* parent exits */
1879 setsid(); /* create a new session */
1880
1881 /* Every output goes to /dev/null. If Redis is daemonized but
1882 * the 'logfile' is set to 'stdout' in the configuration file
1883 * it will not log at all. */
1884 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
1885 dup2(fd, STDIN_FILENO);
1886 dup2(fd, STDOUT_FILENO);
1887 dup2(fd, STDERR_FILENO);
1888 if (fd > STDERR_FILENO) close(fd);
1889 }
1890}
1891
1892void version() {
1893 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION,
1894 redisGitSHA1(), atoi(redisGitDirty()) > 0);
1895 exit(0);
1896}
1897
1898void usage() {
1899 fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf] [options]\n");
1900 fprintf(stderr," ./redis-server - (read config from stdin)\n");
1901 fprintf(stderr," ./redis-server -v or --version\n");
1902 fprintf(stderr," ./redis-server -h or --help\n\n");
1903 fprintf(stderr,"Examples:\n");
1904 fprintf(stderr," ./redis-server (run the server with default conf)\n");
1905 fprintf(stderr," ./redis-server /etc/redis/6379.conf\n");
1906 fprintf(stderr," ./redis-server --port 7777\n");
1907 fprintf(stderr," ./redis-server --port 7777 --slaveof 127.0.0.1 8888\n");
1908 fprintf(stderr," ./redis-server /etc/myredis.conf --loglevel verbose\n");
1909 exit(1);
1910}
1911
1912void redisAsciiArt(void) {
1913#include "asciilogo.h"
1914 char *buf = zmalloc(1024*16);
1915
1916 snprintf(buf,1024*16,ascii_logo,
1917 REDIS_VERSION,
1918 redisGitSHA1(),
1919 strtol(redisGitDirty(),NULL,10) > 0,
1920 (sizeof(long) == 8) ? "64" : "32",
1921 server.cluster_enabled ? "cluster" : "stand alone",
1922 server.port,
1923 (long) getpid()
1924 );
1925 redisLogRaw(REDIS_NOTICE|REDIS_LOG_RAW,buf);
1926 zfree(buf);
1927}
1928
1929static void sigtermHandler(int sig) {
1930 REDIS_NOTUSED(sig);
1931
1932 redisLog(REDIS_WARNING,"Received SIGTERM, scheduling shutdown...");
1933 server.shutdown_asap = 1;
1934}
1935
1936void setupSignalHandlers(void) {
1937 struct sigaction act;
1938
1939 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used.
1940 * Otherwise, sa_handler is used. */
1941 sigemptyset(&act.sa_mask);
1942 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
1943 act.sa_handler = sigtermHandler;
1944 sigaction(SIGTERM, &act, NULL);
1945
1946#ifdef HAVE_BACKTRACE
1947 sigemptyset(&act.sa_mask);
1948 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
1949 act.sa_sigaction = sigsegvHandler;
1950 sigaction(SIGSEGV, &act, NULL);
1951 sigaction(SIGBUS, &act, NULL);
1952 sigaction(SIGFPE, &act, NULL);
1953 sigaction(SIGILL, &act, NULL);
1954#endif
1955 return;
1956}
1957
1958int main(int argc, char **argv) {
1959 long long start;
1960 struct timeval tv;
1961
1962 /* We need to initialize our libraries, and the server. */
1963 zmalloc_enable_thread_safeness();
1964 srand(time(NULL)^getpid());
1965 gettimeofday(&tv,NULL);
1966 dictSetHashFunctionSeed(tv.tv_sec^tv.tv_usec^getpid());
1967 initServerConfig();
1968
1969 if (argc >= 2) {
1970 int j = 1; /* First option to parse in argv[] */
1971 sds options = sdsempty();
1972 char *configfile = NULL;
1973
1974 /* Handle special options --help and --version */
1975 if (strcmp(argv[1], "-v") == 0 ||
1976 strcmp(argv[1], "--version") == 0) version();
1977 if (strcmp(argv[1], "--help") == 0 ||
1978 strcmp(argv[1], "-h") == 0) usage();
1979 /* First argument is the config file name? */
1980 if (argv[j][0] != '-' || argv[j][1] != '-')
1981 configfile = argv[j++];
1982 /* All the other options are parsed and conceptually appended to the
1983 * configuration file. For instance --port 6380 will generate the
1984 * string "port 6380\n" to be parsed after the actual file name
1985 * is parsed, if any. */
1986 while(j != argc) {
1987 if (argv[j][0] == '-' && argv[j][1] == '-') {
1988 /* Option name */
1989 if (sdslen(options)) options = sdscat(options,"\n");
1990 options = sdscat(options,argv[j]+2);
1991 options = sdscat(options," ");
1992 } else {
1993 /* Option argument */
1994 options = sdscatrepr(options,argv[j],strlen(argv[j]));
1995 options = sdscat(options," ");
1996 }
1997 j++;
1998 }
1999 resetServerSaveParams();
2000 loadServerConfig(configfile,options);
2001 sdsfree(options);
2002 } else {
2003 redisLog(REDIS_WARNING,"Warning: no config file specified, using the default config. In order to specify a config file use 'redis-server /path/to/redis.conf'");
2004 }
2005 if (server.daemonize) daemonize();
2006 initServer();
2007 if (server.daemonize) createPidFile();
2008 redisAsciiArt();
2009 redisLog(REDIS_WARNING,"Server started, Redis version " REDIS_VERSION);
2010#ifdef __linux__
2011 linuxOvercommitMemoryWarning();
2012#endif
2013 start = ustime();
2014 if (server.aof_state == REDIS_AOF_ON) {
2015 if (loadAppendOnlyFile(server.aof_filename) == REDIS_OK)
2016 redisLog(REDIS_NOTICE,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start)/1000000);
2017 } else {
2018 if (rdbLoad(server.rdb_filename) == REDIS_OK) {
2019 redisLog(REDIS_NOTICE,"DB loaded from disk: %.3f seconds",
2020 (float)(ustime()-start)/1000000);
2021 } else if (errno != ENOENT) {
2022 redisLog(REDIS_WARNING,"Fatal error loading the DB. Exiting.");
2023 exit(1);
2024 }
2025 }
2026 if (server.ipfd > 0)
2027 redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
2028 if (server.sofd > 0)
2029 redisLog(REDIS_NOTICE,"The server is now ready to accept connections at %s", server.unixsocket);
2030 aeSetBeforeSleepProc(server.el,beforeSleep);
2031 aeMain(server.el);
2032 aeDeleteEventLoop(server.el);
2033 return 0;
2034}
2035
2036/* The End */