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