9 #include <sys/resource.h>
12 void aofUpdateCurrentSize(void);
14 void aof_background_fsync(int fd
) {
15 bioCreateBackgroundJob(REDIS_BIO_AOF_FSYNC
,(void*)(long)fd
,NULL
,NULL
);
18 /* Called when the user switches from "appendonly yes" to "appendonly no"
19 * at runtime using the CONFIG command. */
20 void stopAppendOnly(void) {
21 flushAppendOnlyFile(1);
22 aof_fsync(server
.appendfd
);
23 close(server
.appendfd
);
26 server
.appendseldb
= -1;
27 server
.appendonly
= 0;
28 /* rewrite operation in progress? kill it, wait child exit */
29 if (server
.bgrewritechildpid
!= -1) {
32 if (kill(server
.bgrewritechildpid
,SIGKILL
) != -1)
33 wait3(&statloc
,0,NULL
);
34 /* reset the buffer accumulating changes while the child saves */
35 sdsfree(server
.bgrewritebuf
);
36 server
.bgrewritebuf
= sdsempty();
37 server
.bgrewritechildpid
= -1;
41 /* Called when the user switches from "appendonly no" to "appendonly yes"
42 * at runtime using the CONFIG command. */
43 int startAppendOnly(void) {
44 server
.appendonly
= 1;
45 server
.lastfsync
= time(NULL
);
46 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
47 if (server
.appendfd
== -1) {
48 redisLog(REDIS_WARNING
,"Used tried to switch on AOF via CONFIG, but I can't open the AOF file: %s",strerror(errno
));
51 if (rewriteAppendOnlyFileBackground() == REDIS_ERR
) {
52 server
.appendonly
= 0;
53 close(server
.appendfd
);
54 redisLog(REDIS_WARNING
,"Used tried to switch on AOF via CONFIG, I can't trigger a background AOF rewrite operation. Check the above logs for more info about the error.",strerror(errno
));
60 /* Write the append only file buffer on disk.
62 * Since we are required to write the AOF before replying to the client,
63 * and the only way the client socket can get a write is entering when the
64 * the event loop, we accumulate all the AOF writes in a memory
65 * buffer and write it on disk using this function just before entering
66 * the event loop again.
68 * About the 'force' argument:
70 * When the fsync policy is set to 'everysec' we may delay the flush if there
71 * is still an fsync() going on in the background thread, since for instance
72 * on Linux write(2) will be blocked by the background fsync anyway.
73 * When this happens we remember that there is some aof buffer to be
74 * flushed ASAP, and will try to do that in the serverCron() function.
76 * However if force is set to 1 we'll write regardless of the background
78 void flushAppendOnlyFile(int force
) {
80 int sync_in_progress
= 0;
82 if (sdslen(server
.aofbuf
) == 0) return;
84 if (server
.appendfsync
== APPENDFSYNC_EVERYSEC
)
85 sync_in_progress
= bioPendingJobsOfType(REDIS_BIO_AOF_FSYNC
) != 0;
87 if (server
.appendfsync
== APPENDFSYNC_EVERYSEC
&& !force
) {
88 /* With this append fsync policy we do background fsyncing.
89 * If the fsync is still in progress we can try to delay
90 * the write for a couple of seconds. */
91 if (sync_in_progress
) {
92 if (server
.aof_flush_postponed_start
== 0) {
93 /* No previous write postponinig, remember that we are
94 * postponing the flush and return. */
95 server
.aof_flush_postponed_start
= server
.unixtime
;
97 } else if (server
.unixtime
- server
.aof_flush_postponed_start
< 2) {
98 /* We were already waiting for fsync to finish, but for less
99 * than two seconds this is still ok. Postpone again. */
102 /* Otherwise fall trough, and go write since we can't wait
103 * over two seconds. */
104 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.");
107 /* If you are following this code path, then we are going to write so
108 * set reset the postponed flush sentinel to zero. */
109 server
.aof_flush_postponed_start
= 0;
111 /* We want to perform a single write. This should be guaranteed atomic
112 * at least if the filesystem we are writing is a real physical one.
113 * While this will save us against the server being killed I don't think
114 * there is much to do about the whole server stopping for power problems
116 nwritten
= write(server
.appendfd
,server
.aofbuf
,sdslen(server
.aofbuf
));
117 if (nwritten
!= (signed)sdslen(server
.aofbuf
)) {
118 /* Ooops, we are in troubles. The best thing to do for now is
119 * aborting instead of giving the illusion that everything is
120 * working as expected. */
121 if (nwritten
== -1) {
122 redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
));
124 redisLog(REDIS_WARNING
,"Exiting on short write while writing to the append-only file: %s",strerror(errno
));
128 server
.appendonly_current_size
+= nwritten
;
130 /* Re-use AOF buffer when it is small enough. The maximum comes from the
131 * arena size of 4k minus some overhead (but is otherwise arbitrary). */
132 if ((sdslen(server
.aofbuf
)+sdsavail(server
.aofbuf
)) < 4000) {
133 sdsclear(server
.aofbuf
);
135 sdsfree(server
.aofbuf
);
136 server
.aofbuf
= sdsempty();
139 /* Don't fsync if no-appendfsync-on-rewrite is set to yes and there are
140 * children doing I/O in the background. */
141 if (server
.no_appendfsync_on_rewrite
&&
142 (server
.bgrewritechildpid
!= -1 || server
.bgsavechildpid
!= -1))
145 /* Perform the fsync if needed. */
146 if (server
.appendfsync
== APPENDFSYNC_ALWAYS
) {
147 /* aof_fsync is defined as fdatasync() for Linux in order to avoid
148 * flushing metadata. */
149 aof_fsync(server
.appendfd
); /* Let's try to get this data on the disk */
150 server
.lastfsync
= server
.unixtime
;
151 } else if ((server
.appendfsync
== APPENDFSYNC_EVERYSEC
&&
152 server
.unixtime
> server
.lastfsync
)) {
153 if (!sync_in_progress
) aof_background_fsync(server
.appendfd
);
154 server
.lastfsync
= server
.unixtime
;
158 sds
catAppendOnlyGenericCommand(sds dst
, int argc
, robj
**argv
) {
164 len
= 1+ll2string(buf
+1,sizeof(buf
)-1,argc
);
167 dst
= sdscatlen(dst
,buf
,len
);
169 for (j
= 0; j
< argc
; j
++) {
170 o
= getDecodedObject(argv
[j
]);
172 len
= 1+ll2string(buf
+1,sizeof(buf
)-1,sdslen(o
->ptr
));
175 dst
= sdscatlen(dst
,buf
,len
);
176 dst
= sdscatlen(dst
,o
->ptr
,sdslen(o
->ptr
));
177 dst
= sdscatlen(dst
,"\r\n",2);
183 sds
catAppendOnlyExpireAtCommand(sds buf
, robj
*key
, robj
*seconds
) {
188 /* Make sure we can use strtol */
189 seconds
= getDecodedObject(seconds
);
190 when
= time(NULL
)+strtol(seconds
->ptr
,NULL
,10);
191 decrRefCount(seconds
);
193 argv
[0] = createStringObject("EXPIREAT",8);
195 argv
[2] = createObject(REDIS_STRING
,
196 sdscatprintf(sdsempty(),"%ld",when
));
197 buf
= catAppendOnlyGenericCommand(buf
, argc
, argv
);
198 decrRefCount(argv
[0]);
199 decrRefCount(argv
[2]);
203 void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
204 sds buf
= sdsempty();
207 /* The DB this command was targetting is not the same as the last command
208 * we appendend. To issue a SELECT command is needed. */
209 if (dictid
!= server
.appendseldb
) {
212 snprintf(seldb
,sizeof(seldb
),"%d",dictid
);
213 buf
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
214 (unsigned long)strlen(seldb
),seldb
);
215 server
.appendseldb
= dictid
;
218 if (cmd
->proc
== expireCommand
) {
219 /* Translate EXPIRE into EXPIREAT */
220 buf
= catAppendOnlyExpireAtCommand(buf
,argv
[1],argv
[2]);
221 } else if (cmd
->proc
== setexCommand
) {
222 /* Translate SETEX to SET and EXPIREAT */
223 tmpargv
[0] = createStringObject("SET",3);
224 tmpargv
[1] = argv
[1];
225 tmpargv
[2] = argv
[3];
226 buf
= catAppendOnlyGenericCommand(buf
,3,tmpargv
);
227 decrRefCount(tmpargv
[0]);
228 buf
= catAppendOnlyExpireAtCommand(buf
,argv
[1],argv
[2]);
230 buf
= catAppendOnlyGenericCommand(buf
,argc
,argv
);
233 /* Append to the AOF buffer. This will be flushed on disk just before
234 * of re-entering the event loop, so before the client will get a
235 * positive reply about the operation performed. */
236 server
.aofbuf
= sdscatlen(server
.aofbuf
,buf
,sdslen(buf
));
238 /* If a background append only file rewriting is in progress we want to
239 * accumulate the differences between the child DB and the current one
240 * in a buffer, so that when the child process will do its work we
241 * can append the differences to the new append only file. */
242 if (server
.bgrewritechildpid
!= -1)
243 server
.bgrewritebuf
= sdscatlen(server
.bgrewritebuf
,buf
,sdslen(buf
));
248 /* In Redis commands are always executed in the context of a client, so in
249 * order to load the append only file we need to create a fake client. */
250 struct redisClient
*createFakeClient(void) {
251 struct redisClient
*c
= zmalloc(sizeof(*c
));
255 c
->querybuf
= sdsempty();
260 /* We set the fake client as a slave waiting for the synchronization
261 * so that Redis will not try to send replies to this client. */
262 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
263 c
->reply
= listCreate();
264 c
->watched_keys
= listCreate();
265 listSetFreeMethod(c
->reply
,decrRefCount
);
266 listSetDupMethod(c
->reply
,dupClientReplyValue
);
267 initClientMultiState(c
);
271 void freeFakeClient(struct redisClient
*c
) {
272 sdsfree(c
->querybuf
);
273 listRelease(c
->reply
);
274 listRelease(c
->watched_keys
);
275 freeClientMultiState(c
);
279 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
280 * error (the append only file is zero-length) REDIS_ERR is returned. On
281 * fatal error an error message is logged and the program exists. */
282 int loadAppendOnlyFile(char *filename
) {
283 struct redisClient
*fakeClient
;
284 FILE *fp
= fopen(filename
,"r");
285 struct redis_stat sb
;
286 int appendonly
= server
.appendonly
;
289 if (fp
&& redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0) {
290 server
.appendonly_current_size
= 0;
296 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
300 /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
301 * to the same file we're about to read. */
302 server
.appendonly
= 0;
304 fakeClient
= createFakeClient();
313 struct redisCommand
*cmd
;
315 /* Serve the clients from time to time */
316 if (!(loops
++ % 1000)) {
317 loadingProgress(ftello(fp
));
318 aeProcessEvents(server
.el
, AE_FILE_EVENTS
|AE_DONT_WAIT
);
321 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
327 if (buf
[0] != '*') goto fmterr
;
329 if (argc
< 1) goto fmterr
;
331 argv
= zmalloc(sizeof(robj
*)*argc
);
332 for (j
= 0; j
< argc
; j
++) {
333 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
334 if (buf
[0] != '$') goto fmterr
;
335 len
= strtol(buf
+1,NULL
,10);
336 argsds
= sdsnewlen(NULL
,len
);
337 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
338 argv
[j
] = createObject(REDIS_STRING
,argsds
);
339 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
343 cmd
= lookupCommand(argv
[0]->ptr
);
345 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
348 /* Run the command in the context of a fake client */
349 fakeClient
->argc
= argc
;
350 fakeClient
->argv
= argv
;
351 cmd
->proc(fakeClient
);
353 /* The fake client should not have a reply */
354 redisAssert(fakeClient
->bufpos
== 0 && listLength(fakeClient
->reply
) == 0);
355 /* The fake client should never get blocked */
356 redisAssert((fakeClient
->flags
& REDIS_BLOCKED
) == 0);
358 /* Clean up. Command code may have changed argv/argc so we use the
359 * argv/argc of the client instead of the local variables. */
360 for (j
= 0; j
< fakeClient
->argc
; j
++)
361 decrRefCount(fakeClient
->argv
[j
]);
362 zfree(fakeClient
->argv
);
365 /* This point can only be reached when EOF is reached without errors.
366 * If the client is in the middle of a MULTI/EXEC, log error and quit. */
367 if (fakeClient
->flags
& REDIS_MULTI
) goto readerr
;
370 freeFakeClient(fakeClient
);
371 server
.appendonly
= appendonly
;
373 aofUpdateCurrentSize();
374 server
.auto_aofrewrite_base_size
= server
.appendonly_current_size
;
379 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
381 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
385 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>");
389 /* Write a sequence of commands able to fully rebuild the dataset into
390 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
391 int rewriteAppendOnlyFile(char *filename
) {
392 dictIterator
*di
= NULL
;
397 time_t now
= time(NULL
);
399 /* Note that we have to use a different temp name here compared to the
400 * one used by rewriteAppendOnlyFileBackground() function. */
401 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
402 fp
= fopen(tmpfile
,"w");
404 redisLog(REDIS_WARNING
, "Failed rewriting the append only file: %s", strerror(errno
));
407 for (j
= 0; j
< server
.dbnum
; j
++) {
408 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
409 redisDb
*db
= server
.db
+j
;
411 if (dictSize(d
) == 0) continue;
412 di
= dictGetSafeIterator(d
);
418 /* SELECT the new DB */
419 if (fwrite(selectcmd
,sizeof(selectcmd
)-1,1,fp
) == 0) goto werr
;
420 if (fwriteBulkLongLong(fp
,j
) == 0) goto werr
;
422 /* Iterate this DB writing every entry */
423 while((de
= dictNext(di
)) != NULL
) {
428 keystr
= dictGetEntryKey(de
);
429 o
= dictGetEntryVal(de
);
430 initStaticStringObject(key
,keystr
);
432 expiretime
= getExpire(db
,&key
);
434 /* Save the key and associated value */
435 if (o
->type
== REDIS_STRING
) {
436 /* Emit a SET command */
437 char cmd
[]="*3\r\n$3\r\nSET\r\n";
438 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
440 if (fwriteBulkObject(fp
,&key
) == 0) goto werr
;
441 if (fwriteBulkObject(fp
,o
) == 0) goto werr
;
442 } else if (o
->type
== REDIS_LIST
) {
443 /* Emit the RPUSHes needed to rebuild the list */
444 char cmd
[]="*3\r\n$5\r\nRPUSH\r\n";
445 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
446 unsigned char *zl
= o
->ptr
;
447 unsigned char *p
= ziplistIndex(zl
,0);
452 while(ziplistGet(p
,&vstr
,&vlen
,&vlong
)) {
453 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
454 if (fwriteBulkObject(fp
,&key
) == 0) goto werr
;
456 if (fwriteBulkString(fp
,(char*)vstr
,vlen
) == 0)
459 if (fwriteBulkLongLong(fp
,vlong
) == 0)
462 p
= ziplistNext(zl
,p
);
464 } else if (o
->encoding
== REDIS_ENCODING_LINKEDLIST
) {
469 listRewind(list
,&li
);
470 while((ln
= listNext(&li
))) {
471 robj
*eleobj
= listNodeValue(ln
);
473 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
474 if (fwriteBulkObject(fp
,&key
) == 0) goto werr
;
475 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
478 redisPanic("Unknown list encoding");
480 } else if (o
->type
== REDIS_SET
) {
481 char cmd
[]="*3\r\n$4\r\nSADD\r\n";
483 /* Emit the SADDs needed to rebuild the set */
484 if (o
->encoding
== REDIS_ENCODING_INTSET
) {
487 while(intsetGet(o
->ptr
,ii
++,&llval
)) {
488 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
489 if (fwriteBulkObject(fp
,&key
) == 0) goto werr
;
490 if (fwriteBulkLongLong(fp
,llval
) == 0) goto werr
;
492 } else if (o
->encoding
== REDIS_ENCODING_HT
) {
493 dictIterator
*di
= dictGetIterator(o
->ptr
);
495 while((de
= dictNext(di
)) != NULL
) {
496 robj
*eleobj
= dictGetEntryKey(de
);
497 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
498 if (fwriteBulkObject(fp
,&key
) == 0) goto werr
;
499 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
501 dictReleaseIterator(di
);
503 redisPanic("Unknown set encoding");
505 } else if (o
->type
== REDIS_ZSET
) {
506 /* Emit the ZADDs needed to rebuild the sorted set */
507 char cmd
[]="*4\r\n$4\r\nZADD\r\n";
509 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
510 unsigned char *zl
= o
->ptr
;
511 unsigned char *eptr
, *sptr
;
517 eptr
= ziplistIndex(zl
,0);
518 redisAssert(eptr
!= NULL
);
519 sptr
= ziplistNext(zl
,eptr
);
520 redisAssert(sptr
!= NULL
);
522 while (eptr
!= NULL
) {
523 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vll
));
524 score
= zzlGetScore(sptr
);
526 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
527 if (fwriteBulkObject(fp
,&key
) == 0) goto werr
;
528 if (fwriteBulkDouble(fp
,score
) == 0) goto werr
;
530 if (fwriteBulkString(fp
,(char*)vstr
,vlen
) == 0)
533 if (fwriteBulkLongLong(fp
,vll
) == 0)
536 zzlNext(zl
,&eptr
,&sptr
);
538 } else if (o
->encoding
== REDIS_ENCODING_SKIPLIST
) {
540 dictIterator
*di
= dictGetIterator(zs
->dict
);
543 while((de
= dictNext(di
)) != NULL
) {
544 robj
*eleobj
= dictGetEntryKey(de
);
545 double *score
= dictGetEntryVal(de
);
547 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
548 if (fwriteBulkObject(fp
,&key
) == 0) goto werr
;
549 if (fwriteBulkDouble(fp
,*score
) == 0) goto werr
;
550 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
552 dictReleaseIterator(di
);
554 redisPanic("Unknown sorted set encoding");
556 } else if (o
->type
== REDIS_HASH
) {
557 char cmd
[]="*4\r\n$4\r\nHSET\r\n";
559 /* Emit the HSETs needed to rebuild the hash */
560 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
561 unsigned char *p
= zipmapRewind(o
->ptr
);
562 unsigned char *field
, *val
;
563 unsigned int flen
, vlen
;
565 while((p
= zipmapNext(p
,&field
,&flen
,&val
,&vlen
)) != NULL
) {
566 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
567 if (fwriteBulkObject(fp
,&key
) == 0) goto werr
;
568 if (fwriteBulkString(fp
,(char*)field
,flen
) == 0)
570 if (fwriteBulkString(fp
,(char*)val
,vlen
) == 0)
574 dictIterator
*di
= dictGetIterator(o
->ptr
);
577 while((de
= dictNext(di
)) != NULL
) {
578 robj
*field
= dictGetEntryKey(de
);
579 robj
*val
= dictGetEntryVal(de
);
581 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
582 if (fwriteBulkObject(fp
,&key
) == 0) goto werr
;
583 if (fwriteBulkObject(fp
,field
) == 0) goto werr
;
584 if (fwriteBulkObject(fp
,val
) == 0) goto werr
;
586 dictReleaseIterator(di
);
589 redisPanic("Unknown object type");
591 /* Save the expire time */
592 if (expiretime
!= -1) {
593 char cmd
[]="*3\r\n$8\r\nEXPIREAT\r\n";
594 /* If this key is already expired skip it */
595 if (expiretime
< now
) continue;
596 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
597 if (fwriteBulkObject(fp
,&key
) == 0) goto werr
;
598 if (fwriteBulkLongLong(fp
,expiretime
) == 0) goto werr
;
601 dictReleaseIterator(di
);
604 /* Make sure data will not remain on the OS's output buffers */
606 aof_fsync(fileno(fp
));
609 /* Use RENAME to make sure the DB file is changed atomically only
610 * if the generate DB file is ok. */
611 if (rename(tmpfile
,filename
) == -1) {
612 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
616 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
622 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
623 if (di
) dictReleaseIterator(di
);
627 /* This is how rewriting of the append only file in background works:
629 * 1) The user calls BGREWRITEAOF
630 * 2) Redis calls this function, that forks():
631 * 2a) the child rewrite the append only file in a temp file.
632 * 2b) the parent accumulates differences in server.bgrewritebuf.
633 * 3) When the child finished '2a' exists.
634 * 4) The parent will trap the exit code, if it's OK, will append the
635 * data accumulated into server.bgrewritebuf into the temp file, and
636 * finally will rename(2) the temp file in the actual file name.
637 * The the new file is reopened as the new append only file. Profit!
639 int rewriteAppendOnlyFileBackground(void) {
643 if (server
.bgrewritechildpid
!= -1) return REDIS_ERR
;
645 if ((childpid
= fork()) == 0) {
649 if (server
.ipfd
> 0) close(server
.ipfd
);
650 if (server
.sofd
> 0) close(server
.sofd
);
651 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
652 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
659 server
.stat_fork_time
= ustime()-start
;
660 if (childpid
== -1) {
661 redisLog(REDIS_WARNING
,
662 "Can't rewrite append only file in background: fork: %s",
666 redisLog(REDIS_NOTICE
,
667 "Background append only file rewriting started by pid %d",childpid
);
668 server
.bgrewritechildpid
= childpid
;
669 updateDictResizePolicy();
670 /* We set appendseldb to -1 in order to force the next call to the
671 * feedAppendOnlyFile() to issue a SELECT command, so the differences
672 * accumulated by the parent into server.bgrewritebuf will start
673 * with a SELECT statement and it will be safe to merge. */
674 server
.appendseldb
= -1;
677 return REDIS_OK
; /* unreached */
680 void bgrewriteaofCommand(redisClient
*c
) {
681 if (server
.bgrewritechildpid
!= -1) {
682 addReplyError(c
,"Background append only file rewriting already in progress");
683 } else if (server
.bgsavechildpid
!= -1) {
684 server
.aofrewrite_scheduled
= 1;
685 addReplyStatus(c
,"Background append only file rewriting scheduled");
686 } else if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
687 addReplyStatus(c
,"Background append only file rewriting started");
689 addReply(c
,shared
.err
);
693 void aofRemoveTempFile(pid_t childpid
) {
696 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
700 /* Update the server.appendonly_current_size filed explicitly using stat(2)
701 * to check the size of the file. This is useful after a rewrite or after
702 * a restart, normally the size is updated just adding the write length
703 * to the current lenght, that is much faster. */
704 void aofUpdateCurrentSize(void) {
705 struct redis_stat sb
;
707 if (redis_fstat(server
.appendfd
,&sb
) == -1) {
708 redisLog(REDIS_WARNING
,"Unable to check the AOF length: %s",
711 server
.appendonly_current_size
= sb
.st_size
;
715 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
717 void backgroundRewriteDoneHandler(int exitcode
, int bysignal
) {
718 if (!bysignal
&& exitcode
== 0) {
722 long long now
= ustime();
724 redisLog(REDIS_NOTICE
,
725 "Background AOF rewrite terminated with success");
727 /* Flush the differences accumulated by the parent to the
729 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof",
730 (int)server
.bgrewritechildpid
);
731 newfd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
733 redisLog(REDIS_WARNING
,
734 "Unable to open the temporary AOF produced by the child: %s", strerror(errno
));
738 nwritten
= write(newfd
,server
.bgrewritebuf
,sdslen(server
.bgrewritebuf
));
739 if (nwritten
!= (signed)sdslen(server
.bgrewritebuf
)) {
740 if (nwritten
== -1) {
741 redisLog(REDIS_WARNING
,
742 "Error trying to flush the parent diff to the rewritten AOF: %s", strerror(errno
));
744 redisLog(REDIS_WARNING
,
745 "Short write trying to flush the parent diff to the rewritten AOF: %s", strerror(errno
));
751 redisLog(REDIS_NOTICE
,
752 "Parent diff successfully flushed to the rewritten AOF (%lu bytes)", nwritten
);
754 /* The only remaining thing to do is to rename the temporary file to
755 * the configured file and switch the file descriptor used to do AOF
756 * writes. We don't want close(2) or rename(2) calls to block the
757 * server on old file deletion.
759 * There are two possible scenarios:
761 * 1) AOF is DISABLED and this was a one time rewrite. The temporary
762 * file will be renamed to the configured file. When this file already
763 * exists, it will be unlinked, which may block the server.
765 * 2) AOF is ENABLED and the rewritten AOF will immediately start
766 * receiving writes. After the temporary file is renamed to the
767 * configured file, the original AOF file descriptor will be closed.
768 * Since this will be the last reference to that file, closing it
769 * causes the underlying file to be unlinked, which may block the
772 * To mitigate the blocking effect of the unlink operation (either
773 * caused by rename(2) in scenario 1, or by close(2) in scenario 2), we
774 * use a background thread to take care of this. First, we
775 * make scenario 1 identical to scenario 2 by opening the target file
776 * when it exists. The unlink operation after the rename(2) will then
777 * be executed upon calling close(2) for its descriptor. Everything to
778 * guarantee atomicity for this switch has already happened by then, so
779 * we don't care what the outcome or duration of that close operation
780 * is, as long as the file descriptor is released again. */
781 if (server
.appendfd
== -1) {
784 /* Don't care if this fails: oldfd will be -1 and we handle that.
785 * One notable case of -1 return is if the old file does
787 oldfd
= open(server
.appendfilename
,O_RDONLY
|O_NONBLOCK
);
790 oldfd
= -1; /* We'll set this to the current AOF filedes later. */
793 /* Rename the temporary file. This will not unlink the target file if
794 * it exists, because we reference it with "oldfd". */
795 if (rename(tmpfile
,server
.appendfilename
) == -1) {
796 redisLog(REDIS_WARNING
,
797 "Error trying to rename the temporary AOF: %s", strerror(errno
));
799 if (oldfd
!= -1) close(oldfd
);
803 if (server
.appendfd
== -1) {
804 /* AOF disabled, we don't need to set the AOF file descriptor
805 * to this new file, so we can close it. */
808 /* AOF enabled, replace the old fd with the new one. */
809 oldfd
= server
.appendfd
;
810 server
.appendfd
= newfd
;
811 if (server
.appendfsync
== APPENDFSYNC_ALWAYS
)
813 else if (server
.appendfsync
== APPENDFSYNC_EVERYSEC
)
814 aof_background_fsync(newfd
);
815 server
.appendseldb
= -1; /* Make sure SELECT is re-issued */
816 aofUpdateCurrentSize();
817 server
.auto_aofrewrite_base_size
= server
.appendonly_current_size
;
819 /* Clear regular AOF buffer since its contents was just written to
820 * the new AOF from the background rewrite buffer. */
821 sdsfree(server
.aofbuf
);
822 server
.aofbuf
= sdsempty();
825 redisLog(REDIS_NOTICE
, "Background AOF rewrite successful");
827 /* Asynchronously close the overwritten AOF. */
828 if (oldfd
!= -1) bioCreateBackgroundJob(REDIS_BIO_CLOSE_FILE
,(void*)(long)oldfd
,NULL
,NULL
);
830 redisLog(REDIS_VERBOSE
,
831 "Background AOF rewrite signal handler took %lldus", ustime()-now
);
832 } else if (!bysignal
&& exitcode
!= 0) {
833 redisLog(REDIS_WARNING
,
834 "Background AOF rewrite terminated with error");
836 redisLog(REDIS_WARNING
,
837 "Background AOF rewrite terminated by signal %d", bysignal
);
841 sdsfree(server
.bgrewritebuf
);
842 server
.bgrewritebuf
= sdsempty();
843 aofRemoveTempFile(server
.bgrewritechildpid
);
844 server
.bgrewritechildpid
= -1;