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