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 argv
= zmalloc(sizeof(robj
*)*argc
);
330 for (j
= 0; j
< argc
; j
++) {
331 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
332 if (buf
[0] != '$') goto fmterr
;
333 len
= strtol(buf
+1,NULL
,10);
334 argsds
= sdsnewlen(NULL
,len
);
335 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
336 argv
[j
] = createObject(REDIS_STRING
,argsds
);
337 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
341 cmd
= lookupCommand(argv
[0]->ptr
);
343 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
346 /* Run the command in the context of a fake client */
347 fakeClient
->argc
= argc
;
348 fakeClient
->argv
= argv
;
349 cmd
->proc(fakeClient
);
351 /* The fake client should not have a reply */
352 redisAssert(fakeClient
->bufpos
== 0 && listLength(fakeClient
->reply
) == 0);
353 /* The fake client should never get blocked */
354 redisAssert((fakeClient
->flags
& REDIS_BLOCKED
) == 0);
356 /* Clean up. Command code may have changed argv/argc so we use the
357 * argv/argc of the client instead of the local variables. */
358 for (j
= 0; j
< fakeClient
->argc
; j
++)
359 decrRefCount(fakeClient
->argv
[j
]);
360 zfree(fakeClient
->argv
);
363 /* This point can only be reached when EOF is reached without errors.
364 * If the client is in the middle of a MULTI/EXEC, log error and quit. */
365 if (fakeClient
->flags
& REDIS_MULTI
) goto readerr
;
368 freeFakeClient(fakeClient
);
369 server
.appendonly
= appendonly
;
371 aofUpdateCurrentSize();
372 server
.auto_aofrewrite_base_size
= server
.appendonly_current_size
;
377 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
379 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
383 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>");
387 /* Write a sequence of commands able to fully rebuild the dataset into
388 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
389 int rewriteAppendOnlyFile(char *filename
) {
390 dictIterator
*di
= NULL
;
395 time_t now
= time(NULL
);
397 /* Note that we have to use a different temp name here compared to the
398 * one used by rewriteAppendOnlyFileBackground() function. */
399 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
400 fp
= fopen(tmpfile
,"w");
402 redisLog(REDIS_WARNING
, "Failed rewriting the append only file: %s", strerror(errno
));
405 for (j
= 0; j
< server
.dbnum
; j
++) {
406 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
407 redisDb
*db
= server
.db
+j
;
409 if (dictSize(d
) == 0) continue;
410 di
= dictGetSafeIterator(d
);
416 /* SELECT the new DB */
417 if (fwrite(selectcmd
,sizeof(selectcmd
)-1,1,fp
) == 0) goto werr
;
418 if (fwriteBulkLongLong(fp
,j
) == 0) goto werr
;
420 /* Iterate this DB writing every entry */
421 while((de
= dictNext(di
)) != NULL
) {
426 keystr
= dictGetEntryKey(de
);
427 o
= dictGetEntryVal(de
);
428 initStaticStringObject(key
,keystr
);
430 expiretime
= getExpire(db
,&key
);
432 /* Save the key and associated value */
433 if (o
->type
== REDIS_STRING
) {
434 /* Emit a SET command */
435 char cmd
[]="*3\r\n$3\r\nSET\r\n";
436 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
438 if (fwriteBulkObject(fp
,&key
) == 0) goto werr
;
439 if (fwriteBulkObject(fp
,o
) == 0) goto werr
;
440 } else if (o
->type
== REDIS_LIST
) {
441 /* Emit the RPUSHes needed to rebuild the list */
442 char cmd
[]="*3\r\n$5\r\nRPUSH\r\n";
443 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
444 unsigned char *zl
= o
->ptr
;
445 unsigned char *p
= ziplistIndex(zl
,0);
450 while(ziplistGet(p
,&vstr
,&vlen
,&vlong
)) {
451 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
452 if (fwriteBulkObject(fp
,&key
) == 0) goto werr
;
454 if (fwriteBulkString(fp
,(char*)vstr
,vlen
) == 0)
457 if (fwriteBulkLongLong(fp
,vlong
) == 0)
460 p
= ziplistNext(zl
,p
);
462 } else if (o
->encoding
== REDIS_ENCODING_LINKEDLIST
) {
467 listRewind(list
,&li
);
468 while((ln
= listNext(&li
))) {
469 robj
*eleobj
= listNodeValue(ln
);
471 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
472 if (fwriteBulkObject(fp
,&key
) == 0) goto werr
;
473 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
476 redisPanic("Unknown list encoding");
478 } else if (o
->type
== REDIS_SET
) {
479 char cmd
[]="*3\r\n$4\r\nSADD\r\n";
481 /* Emit the SADDs needed to rebuild the set */
482 if (o
->encoding
== REDIS_ENCODING_INTSET
) {
485 while(intsetGet(o
->ptr
,ii
++,&llval
)) {
486 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
487 if (fwriteBulkObject(fp
,&key
) == 0) goto werr
;
488 if (fwriteBulkLongLong(fp
,llval
) == 0) goto werr
;
490 } else if (o
->encoding
== REDIS_ENCODING_HT
) {
491 dictIterator
*di
= dictGetIterator(o
->ptr
);
493 while((de
= dictNext(di
)) != NULL
) {
494 robj
*eleobj
= dictGetEntryKey(de
);
495 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
496 if (fwriteBulkObject(fp
,&key
) == 0) goto werr
;
497 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
499 dictReleaseIterator(di
);
501 redisPanic("Unknown set encoding");
503 } else if (o
->type
== REDIS_ZSET
) {
504 /* Emit the ZADDs needed to rebuild the sorted set */
505 char cmd
[]="*4\r\n$4\r\nZADD\r\n";
507 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
508 unsigned char *zl
= o
->ptr
;
509 unsigned char *eptr
, *sptr
;
515 eptr
= ziplistIndex(zl
,0);
516 redisAssert(eptr
!= NULL
);
517 sptr
= ziplistNext(zl
,eptr
);
518 redisAssert(sptr
!= NULL
);
520 while (eptr
!= NULL
) {
521 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vll
));
522 score
= zzlGetScore(sptr
);
524 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
525 if (fwriteBulkObject(fp
,&key
) == 0) goto werr
;
526 if (fwriteBulkDouble(fp
,score
) == 0) goto werr
;
528 if (fwriteBulkString(fp
,(char*)vstr
,vlen
) == 0)
531 if (fwriteBulkLongLong(fp
,vll
) == 0)
534 zzlNext(zl
,&eptr
,&sptr
);
536 } else if (o
->encoding
== REDIS_ENCODING_SKIPLIST
) {
538 dictIterator
*di
= dictGetIterator(zs
->dict
);
541 while((de
= dictNext(di
)) != NULL
) {
542 robj
*eleobj
= dictGetEntryKey(de
);
543 double *score
= dictGetEntryVal(de
);
545 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
546 if (fwriteBulkObject(fp
,&key
) == 0) goto werr
;
547 if (fwriteBulkDouble(fp
,*score
) == 0) goto werr
;
548 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
550 dictReleaseIterator(di
);
552 redisPanic("Unknown sorted set encoding");
554 } else if (o
->type
== REDIS_HASH
) {
555 char cmd
[]="*4\r\n$4\r\nHSET\r\n";
557 /* Emit the HSETs needed to rebuild the hash */
558 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
559 unsigned char *p
= zipmapRewind(o
->ptr
);
560 unsigned char *field
, *val
;
561 unsigned int flen
, vlen
;
563 while((p
= zipmapNext(p
,&field
,&flen
,&val
,&vlen
)) != NULL
) {
564 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
565 if (fwriteBulkObject(fp
,&key
) == 0) goto werr
;
566 if (fwriteBulkString(fp
,(char*)field
,flen
) == 0)
568 if (fwriteBulkString(fp
,(char*)val
,vlen
) == 0)
572 dictIterator
*di
= dictGetIterator(o
->ptr
);
575 while((de
= dictNext(di
)) != NULL
) {
576 robj
*field
= dictGetEntryKey(de
);
577 robj
*val
= dictGetEntryVal(de
);
579 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
580 if (fwriteBulkObject(fp
,&key
) == 0) goto werr
;
581 if (fwriteBulkObject(fp
,field
) == 0) goto werr
;
582 if (fwriteBulkObject(fp
,val
) == 0) goto werr
;
584 dictReleaseIterator(di
);
587 redisPanic("Unknown object type");
589 /* Save the expire time */
590 if (expiretime
!= -1) {
591 char cmd
[]="*3\r\n$8\r\nEXPIREAT\r\n";
592 /* If this key is already expired skip it */
593 if (expiretime
< now
) continue;
594 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
595 if (fwriteBulkObject(fp
,&key
) == 0) goto werr
;
596 if (fwriteBulkLongLong(fp
,expiretime
) == 0) goto werr
;
599 dictReleaseIterator(di
);
602 /* Make sure data will not remain on the OS's output buffers */
604 aof_fsync(fileno(fp
));
607 /* Use RENAME to make sure the DB file is changed atomically only
608 * if the generate DB file is ok. */
609 if (rename(tmpfile
,filename
) == -1) {
610 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
614 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
620 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
621 if (di
) dictReleaseIterator(di
);
625 /* This is how rewriting of the append only file in background works:
627 * 1) The user calls BGREWRITEAOF
628 * 2) Redis calls this function, that forks():
629 * 2a) the child rewrite the append only file in a temp file.
630 * 2b) the parent accumulates differences in server.bgrewritebuf.
631 * 3) When the child finished '2a' exists.
632 * 4) The parent will trap the exit code, if it's OK, will append the
633 * data accumulated into server.bgrewritebuf into the temp file, and
634 * finally will rename(2) the temp file in the actual file name.
635 * The the new file is reopened as the new append only file. Profit!
637 int rewriteAppendOnlyFileBackground(void) {
641 if (server
.bgrewritechildpid
!= -1) return REDIS_ERR
;
643 if ((childpid
= fork()) == 0) {
647 if (server
.ipfd
> 0) close(server
.ipfd
);
648 if (server
.sofd
> 0) close(server
.sofd
);
649 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
650 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
657 server
.stat_fork_time
= ustime()-start
;
658 if (childpid
== -1) {
659 redisLog(REDIS_WARNING
,
660 "Can't rewrite append only file in background: fork: %s",
664 redisLog(REDIS_NOTICE
,
665 "Background append only file rewriting started by pid %d",childpid
);
666 server
.bgrewritechildpid
= childpid
;
667 updateDictResizePolicy();
668 /* We set appendseldb to -1 in order to force the next call to the
669 * feedAppendOnlyFile() to issue a SELECT command, so the differences
670 * accumulated by the parent into server.bgrewritebuf will start
671 * with a SELECT statement and it will be safe to merge. */
672 server
.appendseldb
= -1;
675 return REDIS_OK
; /* unreached */
678 void bgrewriteaofCommand(redisClient
*c
) {
679 if (server
.bgrewritechildpid
!= -1) {
680 addReplyError(c
,"Background append only file rewriting already in progress");
681 } else if (server
.bgsavechildpid
!= -1) {
682 server
.aofrewrite_scheduled
= 1;
683 addReplyStatus(c
,"Background append only file rewriting scheduled");
684 } else if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
685 addReplyStatus(c
,"Background append only file rewriting started");
687 addReply(c
,shared
.err
);
691 void aofRemoveTempFile(pid_t childpid
) {
694 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
698 /* Update the server.appendonly_current_size filed explicitly using stat(2)
699 * to check the size of the file. This is useful after a rewrite or after
700 * a restart, normally the size is updated just adding the write length
701 * to the current lenght, that is much faster. */
702 void aofUpdateCurrentSize(void) {
703 struct redis_stat sb
;
705 if (redis_fstat(server
.appendfd
,&sb
) == -1) {
706 redisLog(REDIS_WARNING
,"Unable to check the AOF length: %s",
709 server
.appendonly_current_size
= sb
.st_size
;
713 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
715 void backgroundRewriteDoneHandler(int exitcode
, int bysignal
) {
716 if (!bysignal
&& exitcode
== 0) {
720 long long now
= ustime();
722 redisLog(REDIS_NOTICE
,
723 "Background AOF rewrite terminated with success");
725 /* Flush the differences accumulated by the parent to the
727 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof",
728 (int)server
.bgrewritechildpid
);
729 newfd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
731 redisLog(REDIS_WARNING
,
732 "Unable to open the temporary AOF produced by the child: %s", strerror(errno
));
736 nwritten
= write(newfd
,server
.bgrewritebuf
,sdslen(server
.bgrewritebuf
));
737 if (nwritten
!= (signed)sdslen(server
.bgrewritebuf
)) {
738 if (nwritten
== -1) {
739 redisLog(REDIS_WARNING
,
740 "Error trying to flush the parent diff to the rewritten AOF: %s", strerror(errno
));
742 redisLog(REDIS_WARNING
,
743 "Short write trying to flush the parent diff to the rewritten AOF: %s", strerror(errno
));
749 redisLog(REDIS_NOTICE
,
750 "Parent diff successfully flushed to the rewritten AOF (%lu bytes)", nwritten
);
752 /* The only remaining thing to do is to rename the temporary file to
753 * the configured file and switch the file descriptor used to do AOF
754 * writes. We don't want close(2) or rename(2) calls to block the
755 * server on old file deletion.
757 * There are two possible scenarios:
759 * 1) AOF is DISABLED and this was a one time rewrite. The temporary
760 * file will be renamed to the configured file. When this file already
761 * exists, it will be unlinked, which may block the server.
763 * 2) AOF is ENABLED and the rewritten AOF will immediately start
764 * receiving writes. After the temporary file is renamed to the
765 * configured file, the original AOF file descriptor will be closed.
766 * Since this will be the last reference to that file, closing it
767 * causes the underlying file to be unlinked, which may block the
770 * To mitigate the blocking effect of the unlink operation (either
771 * caused by rename(2) in scenario 1, or by close(2) in scenario 2), we
772 * use a background thread to take care of this. First, we
773 * make scenario 1 identical to scenario 2 by opening the target file
774 * when it exists. The unlink operation after the rename(2) will then
775 * be executed upon calling close(2) for its descriptor. Everything to
776 * guarantee atomicity for this switch has already happened by then, so
777 * we don't care what the outcome or duration of that close operation
778 * is, as long as the file descriptor is released again. */
779 if (server
.appendfd
== -1) {
782 /* Don't care if this fails: oldfd will be -1 and we handle that.
783 * One notable case of -1 return is if the old file does
785 oldfd
= open(server
.appendfilename
,O_RDONLY
|O_NONBLOCK
);
788 oldfd
= -1; /* We'll set this to the current AOF filedes later. */
791 /* Rename the temporary file. This will not unlink the target file if
792 * it exists, because we reference it with "oldfd". */
793 if (rename(tmpfile
,server
.appendfilename
) == -1) {
794 redisLog(REDIS_WARNING
,
795 "Error trying to rename the temporary AOF: %s", strerror(errno
));
797 if (oldfd
!= -1) close(oldfd
);
801 if (server
.appendfd
== -1) {
802 /* AOF disabled, we don't need to set the AOF file descriptor
803 * to this new file, so we can close it. */
806 /* AOF enabled, replace the old fd with the new one. */
807 oldfd
= server
.appendfd
;
808 server
.appendfd
= newfd
;
809 if (server
.appendfsync
== APPENDFSYNC_ALWAYS
)
811 else if (server
.appendfsync
== APPENDFSYNC_EVERYSEC
)
812 aof_background_fsync(newfd
);
813 server
.appendseldb
= -1; /* Make sure SELECT is re-issued */
814 aofUpdateCurrentSize();
815 server
.auto_aofrewrite_base_size
= server
.appendonly_current_size
;
817 /* Clear regular AOF buffer since its contents was just written to
818 * the new AOF from the background rewrite buffer. */
819 sdsfree(server
.aofbuf
);
820 server
.aofbuf
= sdsempty();
823 redisLog(REDIS_NOTICE
, "Background AOF rewrite successful");
825 /* Asynchronously close the overwritten AOF. */
826 if (oldfd
!= -1) bioCreateBackgroundJob(REDIS_BIO_CLOSE_FILE
,(void*)(long)oldfd
,NULL
,NULL
);
828 redisLog(REDIS_VERBOSE
,
829 "Background AOF rewrite signal handler took %lldus", ustime()-now
);
830 } else if (!bysignal
&& exitcode
!= 0) {
831 redisLog(REDIS_WARNING
,
832 "Background AOF rewrite terminated with error");
834 redisLog(REDIS_WARNING
,
835 "Background AOF rewrite terminated by signal %d", bysignal
);
839 sdsfree(server
.bgrewritebuf
);
840 server
.bgrewritebuf
= sdsempty();
841 aofRemoveTempFile(server
.bgrewritechildpid
);
842 server
.bgrewritechildpid
= -1;