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