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