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