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