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