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