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