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