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