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