]> git.saurik.com Git - redis.git/blame - src/aof.c
Introduced three client limit classes: normal, slave, pubsub
[redis.git] / src / aof.c
CommitLineData
e2641e09 1#include "redis.h"
986630af 2#include "bio.h"
f9c6f39b 3#include "rio.h"
e2641e09 4
5#include <signal.h>
6#include <fcntl.h>
7#include <sys/stat.h>
3688d7f3 8#include <sys/types.h>
9#include <sys/time.h>
10#include <sys/resource.h>
11#include <sys/wait.h>
e2641e09 12
b333e239 13void aofUpdateCurrentSize(void);
14
4b77700a 15void aof_background_fsync(int fd) {
9a35eb22 16 bioCreateBackgroundJob(REDIS_BIO_AOF_FSYNC,(void*)(long)fd,NULL,NULL);
4b77700a 17}
18
e2641e09 19/* Called when the user switches from "appendonly yes" to "appendonly no"
20 * at runtime using the CONFIG command. */
21void stopAppendOnly(void) {
e394114d 22 redisAssert(server.aof_state != REDIS_AOF_OFF);
db3c2a4f 23 flushAppendOnlyFile(1);
ff2145ad 24 aof_fsync(server.aof_fd);
25 close(server.aof_fd);
e2641e09 26
ff2145ad 27 server.aof_fd = -1;
28 server.aof_selected_db = -1;
e394114d 29 server.aof_state = REDIS_AOF_OFF;
e2641e09 30 /* rewrite operation in progress? kill it, wait child exit */
ff2145ad 31 if (server.aof_child_pid != -1) {
e2641e09 32 int statloc;
33
b941417c 34 redisLog(REDIS_NOTICE,"Killing running AOF rewrite child: %ld",
35 (long) server.aof_child_pid);
ff2145ad 36 if (kill(server.aof_child_pid,SIGKILL) != -1)
e2641e09 37 wait3(&statloc,0,NULL);
38 /* reset the buffer accumulating changes while the child saves */
ff2145ad 39 sdsfree(server.aof_rewrite_buf);
40 server.aof_rewrite_buf = sdsempty();
41 aofRemoveTempFile(server.aof_child_pid);
42 server.aof_child_pid = -1;
e2641e09 43 }
44}
45
46/* Called when the user switches from "appendonly no" to "appendonly yes"
47 * at runtime using the CONFIG command. */
48int startAppendOnly(void) {
ff2145ad 49 server.aof_last_fsync = time(NULL);
50 server.aof_fd = open(server.aof_filename,O_WRONLY|O_APPEND|O_CREAT,0644);
e394114d 51 redisAssert(server.aof_state == REDIS_AOF_OFF);
ff2145ad 52 if (server.aof_fd == -1) {
e7a2e7c1 53 redisLog(REDIS_WARNING,"Redis needs to enable the AOF but can't open the append only file: %s",strerror(errno));
e2641e09 54 return REDIS_ERR;
55 }
56 if (rewriteAppendOnlyFileBackground() == REDIS_ERR) {
ff2145ad 57 close(server.aof_fd);
e7a2e7c1 58 redisLog(REDIS_WARNING,"Redis needs to enable the AOF but can't trigger a background AOF rewrite operation. Check the above logs for more info about the error.");
e2641e09 59 return REDIS_ERR;
60 }
e7a2e7c1 61 /* We correctly switched on AOF, now wait for the rerwite to be complete
62 * in order to append data on disk. */
e394114d 63 server.aof_state = REDIS_AOF_WAIT_REWRITE;
e2641e09 64 return REDIS_OK;
65}
66
67/* Write the append only file buffer on disk.
68 *
69 * Since we are required to write the AOF before replying to the client,
70 * and the only way the client socket can get a write is entering when the
71 * the event loop, we accumulate all the AOF writes in a memory
72 * buffer and write it on disk using this function just before entering
db3c2a4f 73 * the event loop again.
74 *
75 * About the 'force' argument:
76 *
77 * When the fsync policy is set to 'everysec' we may delay the flush if there
78 * is still an fsync() going on in the background thread, since for instance
79 * on Linux write(2) will be blocked by the background fsync anyway.
80 * When this happens we remember that there is some aof buffer to be
81 * flushed ASAP, and will try to do that in the serverCron() function.
82 *
83 * However if force is set to 1 we'll write regardless of the background
84 * fsync. */
85void flushAppendOnlyFile(int force) {
e2641e09 86 ssize_t nwritten;
db3c2a4f 87 int sync_in_progress = 0;
e2641e09 88
ff2145ad 89 if (sdslen(server.aof_buf) == 0) return;
e2641e09 90
2c915bcf 91 if (server.aof_fsync == AOF_FSYNC_EVERYSEC)
db3c2a4f 92 sync_in_progress = bioPendingJobsOfType(REDIS_BIO_AOF_FSYNC) != 0;
93
2c915bcf 94 if (server.aof_fsync == AOF_FSYNC_EVERYSEC && !force) {
db3c2a4f 95 /* With this append fsync policy we do background fsyncing.
96 * If the fsync is still in progress we can try to delay
97 * the write for a couple of seconds. */
98 if (sync_in_progress) {
99 if (server.aof_flush_postponed_start == 0) {
100 /* No previous write postponinig, remember that we are
101 * postponing the flush and return. */
102 server.aof_flush_postponed_start = server.unixtime;
103 return;
104 } else if (server.unixtime - server.aof_flush_postponed_start < 2) {
e7aec180 105 /* We were already waiting for fsync to finish, but for less
db3c2a4f 106 * than two seconds this is still ok. Postpone again. */
107 return;
108 }
109 /* Otherwise fall trough, and go write since we can't wait
110 * over two seconds. */
77ca5fcb 111 redisLog(REDIS_NOTICE,"Asynchronous AOF fsync is taking too long (disk is busy?). Writing the AOF buffer without waiting for fsync to complete, this may slow down Redis.");
db3c2a4f 112 }
113 }
114 /* If you are following this code path, then we are going to write so
115 * set reset the postponed flush sentinel to zero. */
116 server.aof_flush_postponed_start = 0;
117
e2641e09 118 /* We want to perform a single write. This should be guaranteed atomic
119 * at least if the filesystem we are writing is a real physical one.
120 * While this will save us against the server being killed I don't think
121 * there is much to do about the whole server stopping for power problems
122 * or alike */
ff2145ad 123 nwritten = write(server.aof_fd,server.aof_buf,sdslen(server.aof_buf));
124 if (nwritten != (signed)sdslen(server.aof_buf)) {
e2641e09 125 /* Ooops, we are in troubles. The best thing to do for now is
126 * aborting instead of giving the illusion that everything is
127 * working as expected. */
a57225c2 128 if (nwritten == -1) {
e2641e09 129 redisLog(REDIS_WARNING,"Exiting on error writing to the append-only file: %s",strerror(errno));
a57225c2 130 } else {
e51b79f3 131 redisLog(REDIS_WARNING,"Exiting on short write while writing to "
132 "the append-only file: %s (nwritten=%ld, "
133 "expected=%ld)",
134 strerror(errno),
135 (long)nwritten,
136 (long)sdslen(server.aof_buf));
a57225c2
PN
137 }
138 exit(1);
e2641e09 139 }
2c915bcf 140 server.aof_current_size += nwritten;
e2641e09 141
f990782f
PN
142 /* Re-use AOF buffer when it is small enough. The maximum comes from the
143 * arena size of 4k minus some overhead (but is otherwise arbitrary). */
ff2145ad 144 if ((sdslen(server.aof_buf)+sdsavail(server.aof_buf)) < 4000) {
145 sdsclear(server.aof_buf);
f990782f 146 } else {
ff2145ad 147 sdsfree(server.aof_buf);
148 server.aof_buf = sdsempty();
f990782f
PN
149 }
150
29732248
PN
151 /* Don't fsync if no-appendfsync-on-rewrite is set to yes and there are
152 * children doing I/O in the background. */
2c915bcf 153 if (server.aof_no_fsync_on_rewrite &&
f48cd4b9 154 (server.aof_child_pid != -1 || server.rdb_child_pid != -1))
e2641e09 155 return;
29732248
PN
156
157 /* Perform the fsync if needed. */
2c915bcf 158 if (server.aof_fsync == AOF_FSYNC_ALWAYS) {
e2641e09 159 /* aof_fsync is defined as fdatasync() for Linux in order to avoid
160 * flushing metadata. */
ff2145ad 161 aof_fsync(server.aof_fd); /* Let's try to get this data on the disk */
162 server.aof_last_fsync = server.unixtime;
2c915bcf 163 } else if ((server.aof_fsync == AOF_FSYNC_EVERYSEC &&
ff2145ad 164 server.unixtime > server.aof_last_fsync)) {
165 if (!sync_in_progress) aof_background_fsync(server.aof_fd);
166 server.aof_last_fsync = server.unixtime;
e2641e09 167 }
168}
169
d1ec6c8b
PN
170sds catAppendOnlyGenericCommand(sds dst, int argc, robj **argv) {
171 char buf[32];
172 int len, j;
173 robj *o;
174
175 buf[0] = '*';
176 len = 1+ll2string(buf+1,sizeof(buf)-1,argc);
177 buf[len++] = '\r';
178 buf[len++] = '\n';
179 dst = sdscatlen(dst,buf,len);
180
e2641e09 181 for (j = 0; j < argc; j++) {
d1ec6c8b
PN
182 o = getDecodedObject(argv[j]);
183 buf[0] = '$';
184 len = 1+ll2string(buf+1,sizeof(buf)-1,sdslen(o->ptr));
185 buf[len++] = '\r';
186 buf[len++] = '\n';
187 dst = sdscatlen(dst,buf,len);
188 dst = sdscatlen(dst,o->ptr,sdslen(o->ptr));
189 dst = sdscatlen(dst,"\r\n",2);
e2641e09 190 decrRefCount(o);
191 }
d1ec6c8b 192 return dst;
e2641e09 193}
194
12d293ca 195/* Create the sds representation of an PEXPIREAT command, using
196 * 'seconds' as time to live and 'cmd' to understand what command
197 * we are translating into a PEXPIREAT.
198 *
199 * This command is used in order to translate EXPIRE and PEXPIRE commands
200 * into PEXPIREAT command so that we retain precision in the append only
201 * file, and the time is always absolute and not relative. */
202sds catAppendOnlyExpireAtCommand(sds buf, struct redisCommand *cmd, robj *key, robj *seconds) {
203 long long when;
e2641e09 204 robj *argv[3];
205
206 /* Make sure we can use strtol */
207 seconds = getDecodedObject(seconds);
12d293ca 208 when = strtoll(seconds->ptr,NULL,10);
209 /* Convert argument into milliseconds for EXPIRE, SETEX, EXPIREAT */
210 if (cmd->proc == expireCommand || cmd->proc == setexCommand ||
211 cmd->proc == expireatCommand)
212 {
213 when *= 1000;
214 }
215 /* Convert into absolute time for EXPIRE, PEXPIRE, SETEX, PSETEX */
216 if (cmd->proc == expireCommand || cmd->proc == pexpireCommand ||
217 cmd->proc == setexCommand || cmd->proc == psetexCommand)
218 {
219 when += mstime();
220 }
e2641e09 221 decrRefCount(seconds);
222
12d293ca 223 argv[0] = createStringObject("PEXPIREAT",9);
e2641e09 224 argv[1] = key;
12d293ca 225 argv[2] = createStringObjectFromLongLong(when);
226 buf = catAppendOnlyGenericCommand(buf, 3, argv);
e2641e09 227 decrRefCount(argv[0]);
228 decrRefCount(argv[2]);
229 return buf;
230}
231
232void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) {
087f4140 233 sds buf = sdsempty();
e2641e09 234 robj *tmpargv[3];
235
236 /* The DB this command was targetting is not the same as the last command
237 * we appendend. To issue a SELECT command is needed. */
ff2145ad 238 if (dictid != server.aof_selected_db) {
e2641e09 239 char seldb[64];
240
241 snprintf(seldb,sizeof(seldb),"%d",dictid);
242 buf = sdscatprintf(buf,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
243 (unsigned long)strlen(seldb),seldb);
ff2145ad 244 server.aof_selected_db = dictid;
e2641e09 245 }
246
12d293ca 247 if (cmd->proc == expireCommand || cmd->proc == pexpireCommand ||
248 cmd->proc == expireatCommand) {
249 /* Translate EXPIRE/PEXPIRE/EXPIREAT into PEXPIREAT */
250 buf = catAppendOnlyExpireAtCommand(buf,cmd,argv[1],argv[2]);
251 } else if (cmd->proc == setexCommand || cmd->proc == psetexCommand) {
252 /* Translate SETEX/PSETEX to SET and PEXPIREAT */
e2641e09 253 tmpargv[0] = createStringObject("SET",3);
254 tmpargv[1] = argv[1];
255 tmpargv[2] = argv[3];
256 buf = catAppendOnlyGenericCommand(buf,3,tmpargv);
257 decrRefCount(tmpargv[0]);
12d293ca 258 buf = catAppendOnlyExpireAtCommand(buf,cmd,argv[1],argv[2]);
e2641e09 259 } else {
12d293ca 260 /* All the other commands don't need translation or need the
261 * same translation already operated in the command vector
262 * for the replication itself. */
e2641e09 263 buf = catAppendOnlyGenericCommand(buf,argc,argv);
264 }
265
266 /* Append to the AOF buffer. This will be flushed on disk just before
267 * of re-entering the event loop, so before the client will get a
e394114d 268 * positive reply about the operation performed. */
269 if (server.aof_state == REDIS_AOF_ON)
ff2145ad 270 server.aof_buf = sdscatlen(server.aof_buf,buf,sdslen(buf));
e2641e09 271
272 /* If a background append only file rewriting is in progress we want to
273 * accumulate the differences between the child DB and the current one
274 * in a buffer, so that when the child process will do its work we
275 * can append the differences to the new append only file. */
ff2145ad 276 if (server.aof_child_pid != -1)
277 server.aof_rewrite_buf = sdscatlen(server.aof_rewrite_buf,buf,sdslen(buf));
e2641e09 278
279 sdsfree(buf);
280}
281
282/* In Redis commands are always executed in the context of a client, so in
283 * order to load the append only file we need to create a fake client. */
284struct redisClient *createFakeClient(void) {
285 struct redisClient *c = zmalloc(sizeof(*c));
286
287 selectDb(c,0);
288 c->fd = -1;
289 c->querybuf = sdsempty();
290 c->argc = 0;
291 c->argv = NULL;
2403fc9f 292 c->bufpos = 0;
e2641e09 293 c->flags = 0;
294 /* We set the fake client as a slave waiting for the synchronization
295 * so that Redis will not try to send replies to this client. */
296 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
297 c->reply = listCreate();
3853c168 298 c->reply_bytes = 0;
b67d2345 299 c->watched_keys = listCreate();
e2641e09 300 listSetFreeMethod(c->reply,decrRefCount);
301 listSetDupMethod(c->reply,dupClientReplyValue);
302 initClientMultiState(c);
303 return c;
304}
305
306void freeFakeClient(struct redisClient *c) {
307 sdsfree(c->querybuf);
308 listRelease(c->reply);
b67d2345 309 listRelease(c->watched_keys);
e2641e09 310 freeClientMultiState(c);
311 zfree(c);
312}
313
314/* Replay the append log file. On error REDIS_OK is returned. On non fatal
315 * error (the append only file is zero-length) REDIS_ERR is returned. On
316 * fatal error an error message is logged and the program exists. */
317int loadAppendOnlyFile(char *filename) {
318 struct redisClient *fakeClient;
319 FILE *fp = fopen(filename,"r");
320 struct redis_stat sb;
e394114d 321 int old_aof_state = server.aof_state;
97e7f8ae 322 long loops = 0;
e2641e09 323
4aec2ec8 324 if (fp && redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0) {
2c915bcf 325 server.aof_current_size = 0;
4aec2ec8 326 fclose(fp);
e2641e09 327 return REDIS_ERR;
4aec2ec8 328 }
e2641e09 329
330 if (fp == NULL) {
331 redisLog(REDIS_WARNING,"Fatal error: can't open the append log file for reading: %s",strerror(errno));
332 exit(1);
333 }
334
335 /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
336 * to the same file we're about to read. */
e394114d 337 server.aof_state = REDIS_AOF_OFF;
e2641e09 338
339 fakeClient = createFakeClient();
97e7f8ae 340 startLoading(fp);
341
e2641e09 342 while(1) {
343 int argc, j;
344 unsigned long len;
345 robj **argv;
346 char buf[128];
347 sds argsds;
348 struct redisCommand *cmd;
e2641e09 349
97e7f8ae 350 /* Serve the clients from time to time */
351 if (!(loops++ % 1000)) {
352 loadingProgress(ftello(fp));
353 aeProcessEvents(server.el, AE_FILE_EVENTS|AE_DONT_WAIT);
354 }
355
e2641e09 356 if (fgets(buf,sizeof(buf),fp) == NULL) {
357 if (feof(fp))
358 break;
359 else
360 goto readerr;
361 }
362 if (buf[0] != '*') goto fmterr;
363 argc = atoi(buf+1);
be6f6395
KM
364 if (argc < 1) goto fmterr;
365
e2641e09 366 argv = zmalloc(sizeof(robj*)*argc);
367 for (j = 0; j < argc; j++) {
368 if (fgets(buf,sizeof(buf),fp) == NULL) goto readerr;
369 if (buf[0] != '$') goto fmterr;
370 len = strtol(buf+1,NULL,10);
371 argsds = sdsnewlen(NULL,len);
372 if (len && fread(argsds,len,1,fp) == 0) goto fmterr;
373 argv[j] = createObject(REDIS_STRING,argsds);
374 if (fread(buf,2,1,fp) == 0) goto fmterr; /* discard CRLF */
375 }
376
377 /* Command lookup */
378 cmd = lookupCommand(argv[0]->ptr);
379 if (!cmd) {
380 redisLog(REDIS_WARNING,"Unknown command '%s' reading the append only file", argv[0]->ptr);
381 exit(1);
382 }
e2641e09 383 /* Run the command in the context of a fake client */
384 fakeClient->argc = argc;
385 fakeClient->argv = argv;
386 cmd->proc(fakeClient);
57b07380
PN
387
388 /* The fake client should not have a reply */
389 redisAssert(fakeClient->bufpos == 0 && listLength(fakeClient->reply) == 0);
ef67a2fc 390 /* The fake client should never get blocked */
391 redisAssert((fakeClient->flags & REDIS_BLOCKED) == 0);
57b07380 392
45b0f6fb
PN
393 /* Clean up. Command code may have changed argv/argc so we use the
394 * argv/argc of the client instead of the local variables. */
395 for (j = 0; j < fakeClient->argc; j++)
396 decrRefCount(fakeClient->argv[j]);
397 zfree(fakeClient->argv);
e2641e09 398 }
399
400 /* This point can only be reached when EOF is reached without errors.
401 * If the client is in the middle of a MULTI/EXEC, log error and quit. */
402 if (fakeClient->flags & REDIS_MULTI) goto readerr;
403
404 fclose(fp);
405 freeFakeClient(fakeClient);
e394114d 406 server.aof_state = old_aof_state;
97e7f8ae 407 stopLoading();
b333e239 408 aofUpdateCurrentSize();
2c915bcf 409 server.aof_rewrite_base_size = server.aof_current_size;
e2641e09 410 return REDIS_OK;
411
412readerr:
413 if (feof(fp)) {
414 redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file");
415 } else {
416 redisLog(REDIS_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno));
417 }
418 exit(1);
419fmterr:
412e457c 420 redisLog(REDIS_WARNING,"Bad file format reading the append only file: make a backup of your AOF file, then use ./redis-check-aof --fix <filename>");
e2641e09 421 exit(1);
422}
423
7271198c
PN
424/* Delegate writing an object to writing a bulk string or bulk long long.
425 * This is not placed in rio.c since that adds the redis.h dependency. */
426int rioWriteBulkObject(rio *r, robj *obj) {
427 /* Avoid using getDecodedObject to help copy-on-write (we are often
428 * in a child process when this function is called). */
429 if (obj->encoding == REDIS_ENCODING_INT) {
430 return rioWriteBulkLongLong(r,(long)obj->ptr);
431 } else if (obj->encoding == REDIS_ENCODING_RAW) {
432 return rioWriteBulkString(r,obj->ptr,sdslen(obj->ptr));
433 } else {
434 redisPanic("Unknown string encoding");
435 }
436}
437
5b250096 438/* Emit the commands needed to rebuild a list object.
439 * The function returns 0 on error, 1 on success. */
440int rewriteListObject(rio *r, robj *key, robj *o) {
441 long long count = 0, items = listTypeLength(o);
442
443 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
444 unsigned char *zl = o->ptr;
445 unsigned char *p = ziplistIndex(zl,0);
446 unsigned char *vstr;
447 unsigned int vlen;
448 long long vlong;
449
450 while(ziplistGet(p,&vstr,&vlen,&vlong)) {
451 if (count == 0) {
2c915bcf 452 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
453 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
8d875ccb 454
5b250096 455 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
456 if (rioWriteBulkString(r,"RPUSH",5) == 0) return 0;
457 if (rioWriteBulkObject(r,key) == 0) return 0;
458 }
459 if (vstr) {
460 if (rioWriteBulkString(r,(char*)vstr,vlen) == 0) return 0;
461 } else {
462 if (rioWriteBulkLongLong(r,vlong) == 0) return 0;
463 }
464 p = ziplistNext(zl,p);
2c915bcf 465 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
5b250096 466 items--;
467 }
468 } else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
469 list *list = o->ptr;
470 listNode *ln;
471 listIter li;
472
473 listRewind(list,&li);
474 while((ln = listNext(&li))) {
475 robj *eleobj = listNodeValue(ln);
476
38c06fa0 477 if (count == 0) {
2c915bcf 478 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
479 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
8d875ccb 480
38c06fa0 481 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
482 if (rioWriteBulkString(r,"RPUSH",5) == 0) return 0;
483 if (rioWriteBulkObject(r,key) == 0) return 0;
484 }
5b250096 485 if (rioWriteBulkObject(r,eleobj) == 0) return 0;
2c915bcf 486 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
38c06fa0 487 items--;
5b250096 488 }
489 } else {
490 redisPanic("Unknown list encoding");
491 }
492 return 1;
493}
494
8d875ccb 495/* Emit the commands needed to rebuild a set object.
496 * The function returns 0 on error, 1 on success. */
497int rewriteSetObject(rio *r, robj *key, robj *o) {
498 long long count = 0, items = setTypeSize(o);
499
500 if (o->encoding == REDIS_ENCODING_INTSET) {
501 int ii = 0;
502 int64_t llval;
503
504 while(intsetGet(o->ptr,ii++,&llval)) {
505 if (count == 0) {
2c915bcf 506 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
507 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
8d875ccb 508
509 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
510 if (rioWriteBulkString(r,"SADD",4) == 0) return 0;
511 if (rioWriteBulkObject(r,key) == 0) return 0;
512 }
513 if (rioWriteBulkLongLong(r,llval) == 0) return 0;
2c915bcf 514 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
8d875ccb 515 items--;
516 }
517 } else if (o->encoding == REDIS_ENCODING_HT) {
518 dictIterator *di = dictGetIterator(o->ptr);
519 dictEntry *de;
520
521 while((de = dictNext(di)) != NULL) {
522 robj *eleobj = dictGetKey(de);
523 if (count == 0) {
2c915bcf 524 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
525 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
8d875ccb 526
527 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
528 if (rioWriteBulkString(r,"SADD",4) == 0) return 0;
529 if (rioWriteBulkObject(r,key) == 0) return 0;
530 }
531 if (rioWriteBulkObject(r,eleobj) == 0) return 0;
2c915bcf 532 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
8d875ccb 533 items--;
534 }
535 dictReleaseIterator(di);
536 } else {
537 redisPanic("Unknown set encoding");
538 }
539 return 1;
540}
541
7df9b141 542/* Emit the commands needed to rebuild a sorted set object.
543 * The function returns 0 on error, 1 on success. */
544int rewriteSortedSetObject(rio *r, robj *key, robj *o) {
545 long long count = 0, items = zsetLength(o);
546
547 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
548 unsigned char *zl = o->ptr;
549 unsigned char *eptr, *sptr;
550 unsigned char *vstr;
551 unsigned int vlen;
552 long long vll;
553 double score;
554
555 eptr = ziplistIndex(zl,0);
556 redisAssert(eptr != NULL);
557 sptr = ziplistNext(zl,eptr);
558 redisAssert(sptr != NULL);
559
560 while (eptr != NULL) {
561 redisAssert(ziplistGet(eptr,&vstr,&vlen,&vll));
562 score = zzlGetScore(sptr);
563
564 if (count == 0) {
2c915bcf 565 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
566 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
7df9b141 567
568 if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0;
569 if (rioWriteBulkString(r,"ZADD",4) == 0) return 0;
570 if (rioWriteBulkObject(r,key) == 0) return 0;
571 }
572 if (rioWriteBulkDouble(r,score) == 0) return 0;
573 if (vstr != NULL) {
574 if (rioWriteBulkString(r,(char*)vstr,vlen) == 0) return 0;
575 } else {
576 if (rioWriteBulkLongLong(r,vll) == 0) return 0;
577 }
578 zzlNext(zl,&eptr,&sptr);
2c915bcf 579 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
7df9b141 580 items--;
581 }
582 } else if (o->encoding == REDIS_ENCODING_SKIPLIST) {
583 zset *zs = o->ptr;
584 dictIterator *di = dictGetIterator(zs->dict);
585 dictEntry *de;
586
587 while((de = dictNext(di)) != NULL) {
588 robj *eleobj = dictGetKey(de);
589 double *score = dictGetVal(de);
590
591 if (count == 0) {
2c915bcf 592 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
593 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
7df9b141 594
595 if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0;
596 if (rioWriteBulkString(r,"ZADD",4) == 0) return 0;
597 if (rioWriteBulkObject(r,key) == 0) return 0;
598 }
599 if (rioWriteBulkDouble(r,*score) == 0) return 0;
600 if (rioWriteBulkObject(r,eleobj) == 0) return 0;
2c915bcf 601 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
7df9b141 602 items--;
603 }
604 dictReleaseIterator(di);
605 } else {
606 redisPanic("Unknown sorted zset encoding");
607 }
608 return 1;
609}
610
54ecc0e7 611/* Emit the commands needed to rebuild a hash object.
612 * The function returns 0 on error, 1 on success. */
613int rewriteHashObject(rio *r, robj *key, robj *o) {
614 long long count = 0, items = hashTypeLength(o);
615
616 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
617 unsigned char *p = zipmapRewind(o->ptr);
618 unsigned char *field, *val;
619 unsigned int flen, vlen;
620
621 while((p = zipmapNext(p,&field,&flen,&val,&vlen)) != NULL) {
622 if (count == 0) {
2c915bcf 623 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
624 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
54ecc0e7 625
626 if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0;
627 if (rioWriteBulkString(r,"HMSET",5) == 0) return 0;
628 if (rioWriteBulkObject(r,key) == 0) return 0;
629 }
630 if (rioWriteBulkString(r,(char*)field,flen) == 0) return 0;
631 if (rioWriteBulkString(r,(char*)val,vlen) == 0) return 0;
2c915bcf 632 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
54ecc0e7 633 items--;
634 }
635 } else {
636 dictIterator *di = dictGetIterator(o->ptr);
637 dictEntry *de;
638
639 while((de = dictNext(di)) != NULL) {
640 robj *field = dictGetKey(de);
641 robj *val = dictGetVal(de);
642
643 if (count == 0) {
2c915bcf 644 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
645 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
54ecc0e7 646
647 if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0;
648 if (rioWriteBulkString(r,"HMSET",5) == 0) return 0;
649 if (rioWriteBulkObject(r,key) == 0) return 0;
650 }
651 if (rioWriteBulkObject(r,field) == 0) return 0;
652 if (rioWriteBulkObject(r,val) == 0) return 0;
2c915bcf 653 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
54ecc0e7 654 items--;
655 }
656 dictReleaseIterator(di);
657 }
658 return 1;
659}
660
e2641e09 661/* Write a sequence of commands able to fully rebuild the dataset into
5b250096 662 * "filename". Used both by REWRITEAOF and BGREWRITEAOF.
663 *
664 * In order to minimize the number of commands needed in the rewritten
665 * log Redis uses variadic commands when possible, such as RPUSH, SADD
2c915bcf 666 * and ZADD. However at max REDIS_AOF_REWRITE_ITEMS_PER_CMD items per time
5b250096 667 * are inserted using a single command. */
e2641e09 668int rewriteAppendOnlyFile(char *filename) {
669 dictIterator *di = NULL;
670 dictEntry *de;
7271198c 671 rio aof;
e2641e09 672 FILE *fp;
673 char tmpfile[256];
674 int j;
4be855e7 675 long long now = mstime();
e2641e09 676
677 /* Note that we have to use a different temp name here compared to the
678 * one used by rewriteAppendOnlyFileBackground() function. */
679 snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
680 fp = fopen(tmpfile,"w");
681 if (!fp) {
e51b79f3 682 redisLog(REDIS_WARNING, "Opening the temp file for AOF rewrite in rewriteAppendOnlyFile(): %s", strerror(errno));
e2641e09 683 return REDIS_ERR;
684 }
7271198c 685
f96a8a80 686 rioInitWithFile(&aof,fp);
e2641e09 687 for (j = 0; j < server.dbnum; j++) {
688 char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
689 redisDb *db = server.db+j;
690 dict *d = db->dict;
691 if (dictSize(d) == 0) continue;
591f29e0 692 di = dictGetSafeIterator(d);
e2641e09 693 if (!di) {
694 fclose(fp);
695 return REDIS_ERR;
696 }
697
698 /* SELECT the new DB */
7271198c
PN
699 if (rioWrite(&aof,selectcmd,sizeof(selectcmd)-1) == 0) goto werr;
700 if (rioWriteBulkLongLong(&aof,j) == 0) goto werr;
e2641e09 701
702 /* Iterate this DB writing every entry */
703 while((de = dictNext(di)) != NULL) {
6901fe77 704 sds keystr;
e2641e09 705 robj key, *o;
4be855e7 706 long long expiretime;
e2641e09 707
c0ba9ebe 708 keystr = dictGetKey(de);
709 o = dictGetVal(de);
e2641e09 710 initStaticStringObject(key,keystr);
16d77878 711
e2641e09 712 expiretime = getExpire(db,&key);
713
714 /* Save the key and associated value */
715 if (o->type == REDIS_STRING) {
716 /* Emit a SET command */
717 char cmd[]="*3\r\n$3\r\nSET\r\n";
7271198c 718 if (rioWrite(&aof,cmd,sizeof(cmd)-1) == 0) goto werr;
e2641e09 719 /* Key and value */
7271198c
PN
720 if (rioWriteBulkObject(&aof,&key) == 0) goto werr;
721 if (rioWriteBulkObject(&aof,o) == 0) goto werr;
e2641e09 722 } else if (o->type == REDIS_LIST) {
5b250096 723 if (rewriteListObject(&aof,&key,o) == 0) goto werr;
e2641e09 724 } else if (o->type == REDIS_SET) {
8d875ccb 725 if (rewriteSetObject(&aof,&key,o) == 0) goto werr;
e2641e09 726 } else if (o->type == REDIS_ZSET) {
7df9b141 727 if (rewriteSortedSetObject(&aof,&key,o) == 0) goto werr;
e2641e09 728 } else if (o->type == REDIS_HASH) {
54ecc0e7 729 if (rewriteHashObject(&aof,&key,o) == 0) goto werr;
e2641e09 730 } else {
731 redisPanic("Unknown object type");
732 }
733 /* Save the expire time */
734 if (expiretime != -1) {
12d293ca 735 char cmd[]="*3\r\n$9\r\nPEXPIREAT\r\n";
e2641e09 736 /* If this key is already expired skip it */
737 if (expiretime < now) continue;
7271198c
PN
738 if (rioWrite(&aof,cmd,sizeof(cmd)-1) == 0) goto werr;
739 if (rioWriteBulkObject(&aof,&key) == 0) goto werr;
b0b74486 740 if (rioWriteBulkLongLong(&aof,expiretime) == 0) goto werr;
e2641e09 741 }
e2641e09 742 }
743 dictReleaseIterator(di);
744 }
745
746 /* Make sure data will not remain on the OS's output buffers */
747 fflush(fp);
748 aof_fsync(fileno(fp));
749 fclose(fp);
750
751 /* Use RENAME to make sure the DB file is changed atomically only
752 * if the generate DB file is ok. */
753 if (rename(tmpfile,filename) == -1) {
754 redisLog(REDIS_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno));
755 unlink(tmpfile);
756 return REDIS_ERR;
757 }
758 redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");
759 return REDIS_OK;
760
761werr:
762 fclose(fp);
763 unlink(tmpfile);
764 redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));
765 if (di) dictReleaseIterator(di);
766 return REDIS_ERR;
767}
768
769/* This is how rewriting of the append only file in background works:
770 *
771 * 1) The user calls BGREWRITEAOF
772 * 2) Redis calls this function, that forks():
773 * 2a) the child rewrite the append only file in a temp file.
ff2145ad 774 * 2b) the parent accumulates differences in server.aof_rewrite_buf.
e2641e09 775 * 3) When the child finished '2a' exists.
776 * 4) The parent will trap the exit code, if it's OK, will append the
ff2145ad 777 * data accumulated into server.aof_rewrite_buf into the temp file, and
e2641e09 778 * finally will rename(2) the temp file in the actual file name.
779 * The the new file is reopened as the new append only file. Profit!
780 */
781int rewriteAppendOnlyFileBackground(void) {
782 pid_t childpid;
615e414c 783 long long start;
e2641e09 784
ff2145ad 785 if (server.aof_child_pid != -1) return REDIS_ERR;
615e414c 786 start = ustime();
e2641e09 787 if ((childpid = fork()) == 0) {
e2641e09 788 char tmpfile[256];
789
615e414c 790 /* Child */
a5639e7d
PN
791 if (server.ipfd > 0) close(server.ipfd);
792 if (server.sofd > 0) close(server.sofd);
e2641e09 793 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
794 if (rewriteAppendOnlyFile(tmpfile) == REDIS_OK) {
795 _exit(0);
796 } else {
797 _exit(1);
798 }
799 } else {
800 /* Parent */
615e414c 801 server.stat_fork_time = ustime()-start;
e2641e09 802 if (childpid == -1) {
803 redisLog(REDIS_WARNING,
804 "Can't rewrite append only file in background: fork: %s",
805 strerror(errno));
806 return REDIS_ERR;
807 }
808 redisLog(REDIS_NOTICE,
809 "Background append only file rewriting started by pid %d",childpid);
2c915bcf 810 server.aof_rewrite_scheduled = 0;
ff2145ad 811 server.aof_child_pid = childpid;
e2641e09 812 updateDictResizePolicy();
813 /* We set appendseldb to -1 in order to force the next call to the
814 * feedAppendOnlyFile() to issue a SELECT command, so the differences
ff2145ad 815 * accumulated by the parent into server.aof_rewrite_buf will start
e2641e09 816 * with a SELECT statement and it will be safe to merge. */
ff2145ad 817 server.aof_selected_db = -1;
e2641e09 818 return REDIS_OK;
819 }
820 return REDIS_OK; /* unreached */
821}
822
823void bgrewriteaofCommand(redisClient *c) {
ff2145ad 824 if (server.aof_child_pid != -1) {
3ab20376 825 addReplyError(c,"Background append only file rewriting already in progress");
f48cd4b9 826 } else if (server.rdb_child_pid != -1) {
2c915bcf 827 server.aof_rewrite_scheduled = 1;
9e40bce3 828 addReplyStatus(c,"Background append only file rewriting scheduled");
b333e239 829 } else if (rewriteAppendOnlyFileBackground() == REDIS_OK) {
3ab20376 830 addReplyStatus(c,"Background append only file rewriting started");
e2641e09 831 } else {
832 addReply(c,shared.err);
833 }
834}
835
836void aofRemoveTempFile(pid_t childpid) {
837 char tmpfile[256];
838
839 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid);
840 unlink(tmpfile);
841}
842
2c915bcf 843/* Update the server.aof_current_size filed explicitly using stat(2)
b333e239 844 * to check the size of the file. This is useful after a rewrite or after
845 * a restart, normally the size is updated just adding the write length
846 * to the current lenght, that is much faster. */
847void aofUpdateCurrentSize(void) {
848 struct redis_stat sb;
849
ff2145ad 850 if (redis_fstat(server.aof_fd,&sb) == -1) {
e51b79f3 851 redisLog(REDIS_WARNING,"Unable to obtain the AOF file length. stat: %s",
b333e239 852 strerror(errno));
853 } else {
2c915bcf 854 server.aof_current_size = sb.st_size;
b333e239 855 }
856}
857
e2641e09 858/* A background append only file rewriting (BGREWRITEAOF) terminated its work.
859 * Handle this. */
36c17a53 860void backgroundRewriteDoneHandler(int exitcode, int bysignal) {
e2641e09 861 if (!bysignal && exitcode == 0) {
b454056d
PN
862 int newfd, oldfd;
863 int nwritten;
e2641e09 864 char tmpfile[256];
b454056d 865 long long now = ustime();
e2641e09 866
867 redisLog(REDIS_NOTICE,
b454056d
PN
868 "Background AOF rewrite terminated with success");
869
986630af 870 /* Flush the differences accumulated by the parent to the
871 * rewritten AOF. */
872 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof",
ff2145ad 873 (int)server.aof_child_pid);
b454056d
PN
874 newfd = open(tmpfile,O_WRONLY|O_APPEND);
875 if (newfd == -1) {
876 redisLog(REDIS_WARNING,
877 "Unable to open the temporary AOF produced by the child: %s", strerror(errno));
e2641e09 878 goto cleanup;
879 }
b454056d 880
ff2145ad 881 nwritten = write(newfd,server.aof_rewrite_buf,sdslen(server.aof_rewrite_buf));
882 if (nwritten != (signed)sdslen(server.aof_rewrite_buf)) {
b454056d
PN
883 if (nwritten == -1) {
884 redisLog(REDIS_WARNING,
885 "Error trying to flush the parent diff to the rewritten AOF: %s", strerror(errno));
886 } else {
887 redisLog(REDIS_WARNING,
888 "Short write trying to flush the parent diff to the rewritten AOF: %s", strerror(errno));
889 }
890 close(newfd);
e2641e09 891 goto cleanup;
892 }
b454056d
PN
893
894 redisLog(REDIS_NOTICE,
895 "Parent diff successfully flushed to the rewritten AOF (%lu bytes)", nwritten);
896
897 /* The only remaining thing to do is to rename the temporary file to
898 * the configured file and switch the file descriptor used to do AOF
986630af 899 * writes. We don't want close(2) or rename(2) calls to block the
900 * server on old file deletion.
901 *
902 * There are two possible scenarios:
b454056d
PN
903 *
904 * 1) AOF is DISABLED and this was a one time rewrite. The temporary
905 * file will be renamed to the configured file. When this file already
906 * exists, it will be unlinked, which may block the server.
907 *
908 * 2) AOF is ENABLED and the rewritten AOF will immediately start
909 * receiving writes. After the temporary file is renamed to the
910 * configured file, the original AOF file descriptor will be closed.
911 * Since this will be the last reference to that file, closing it
912 * causes the underlying file to be unlinked, which may block the
913 * server.
914 *
915 * To mitigate the blocking effect of the unlink operation (either
916 * caused by rename(2) in scenario 1, or by close(2) in scenario 2), we
986630af 917 * use a background thread to take care of this. First, we
b454056d
PN
918 * make scenario 1 identical to scenario 2 by opening the target file
919 * when it exists. The unlink operation after the rename(2) will then
920 * be executed upon calling close(2) for its descriptor. Everything to
921 * guarantee atomicity for this switch has already happened by then, so
922 * we don't care what the outcome or duration of that close operation
923 * is, as long as the file descriptor is released again. */
ff2145ad 924 if (server.aof_fd == -1) {
b454056d 925 /* AOF disabled */
b454056d 926
986630af 927 /* Don't care if this fails: oldfd will be -1 and we handle that.
928 * One notable case of -1 return is if the old file does
929 * not exist. */
2c915bcf 930 oldfd = open(server.aof_filename,O_RDONLY|O_NONBLOCK);
b454056d
PN
931 } else {
932 /* AOF enabled */
986630af 933 oldfd = -1; /* We'll set this to the current AOF filedes later. */
b454056d
PN
934 }
935
936 /* Rename the temporary file. This will not unlink the target file if
937 * it exists, because we reference it with "oldfd". */
2c915bcf 938 if (rename(tmpfile,server.aof_filename) == -1) {
b454056d 939 redisLog(REDIS_WARNING,
e51b79f3 940 "Error trying to rename the temporary AOF file: %s", strerror(errno));
b454056d 941 close(newfd);
986630af 942 if (oldfd != -1) close(oldfd);
e2641e09 943 goto cleanup;
944 }
b454056d 945
ff2145ad 946 if (server.aof_fd == -1) {
986630af 947 /* AOF disabled, we don't need to set the AOF file descriptor
948 * to this new file, so we can close it. */
b454056d
PN
949 close(newfd);
950 } else {
986630af 951 /* AOF enabled, replace the old fd with the new one. */
ff2145ad 952 oldfd = server.aof_fd;
953 server.aof_fd = newfd;
2c915bcf 954 if (server.aof_fsync == AOF_FSYNC_ALWAYS)
4b77700a 955 aof_fsync(newfd);
2c915bcf 956 else if (server.aof_fsync == AOF_FSYNC_EVERYSEC)
4b77700a 957 aof_background_fsync(newfd);
ff2145ad 958 server.aof_selected_db = -1; /* Make sure SELECT is re-issued */
b333e239 959 aofUpdateCurrentSize();
2c915bcf 960 server.aof_rewrite_base_size = server.aof_current_size;
5f54a5e6
PN
961
962 /* Clear regular AOF buffer since its contents was just written to
963 * the new AOF from the background rewrite buffer. */
ff2145ad 964 sdsfree(server.aof_buf);
965 server.aof_buf = sdsempty();
e2641e09 966 }
b454056d 967
e51b79f3 968 redisLog(REDIS_NOTICE, "Background AOF rewrite finished successfully");
e394114d 969 /* Change state from WAIT_REWRITE to ON if needed */
970 if (server.aof_state == REDIS_AOF_WAIT_REWRITE)
971 server.aof_state = REDIS_AOF_ON;
b454056d
PN
972
973 /* Asynchronously close the overwritten AOF. */
50be9b97 974 if (oldfd != -1) bioCreateBackgroundJob(REDIS_BIO_CLOSE_FILE,(void*)(long)oldfd,NULL,NULL);
b454056d
PN
975
976 redisLog(REDIS_VERBOSE,
977 "Background AOF rewrite signal handler took %lldus", ustime()-now);
e2641e09 978 } else if (!bysignal && exitcode != 0) {
b454056d
PN
979 redisLog(REDIS_WARNING,
980 "Background AOF rewrite terminated with error");
e2641e09 981 } else {
982 redisLog(REDIS_WARNING,
b454056d 983 "Background AOF rewrite terminated by signal %d", bysignal);
e2641e09 984 }
b454056d 985
e2641e09 986cleanup:
ff2145ad 987 sdsfree(server.aof_rewrite_buf);
988 server.aof_rewrite_buf = sdsempty();
989 aofRemoveTempFile(server.aof_child_pid);
990 server.aof_child_pid = -1;
e394114d 991 /* Schedule a new rewrite if we are waiting for it to switch the AOF ON. */
992 if (server.aof_state == REDIS_AOF_WAIT_REWRITE)
2c915bcf 993 server.aof_rewrite_scheduled = 1;
e2641e09 994}