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