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