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