+
+ redisLog(REDIS_NOTICE,
+ "Parent diff successfully flushed to the rewritten AOF (%lu bytes)", nwritten);
+
+ /* The only remaining thing to do is to rename the temporary file to
+ * the configured file and switch the file descriptor used to do AOF
+ * writes. There are two possible scenarios:
+ *
+ * 1) AOF is DISABLED and this was a one time rewrite. The temporary
+ * file will be renamed to the configured file. When this file already
+ * exists, it will be unlinked, which may block the server.
+ *
+ * 2) AOF is ENABLED and the rewritten AOF will immediately start
+ * receiving writes. After the temporary file is renamed to the
+ * configured file, the original AOF file descriptor will be closed.
+ * Since this will be the last reference to that file, closing it
+ * causes the underlying file to be unlinked, which may block the
+ * server.
+ *
+ * To mitigate the blocking effect of the unlink operation (either
+ * caused by rename(2) in scenario 1, or by close(2) in scenario 2), we
+ * use a background thread in libeio to take care of this. First, we
+ * make scenario 1 identical to scenario 2 by opening the target file
+ * when it exists. The unlink operation after the rename(2) will then
+ * be executed upon calling close(2) for its descriptor. Everything to
+ * guarantee atomicity for this switch has already happened by then, so
+ * we don't care what the outcome or duration of that close operation
+ * is, as long as the file descriptor is released again. */
+ if (server.appendfd == -1) {
+ /* AOF disabled */
+ struct stat st;
+
+ /* Check if the configured filename exists. If so, we need to open
+ * it to prevent rename(2) from unlinking it. */
+ if (stat(server.appendfilename, &st) == ENOENT) {
+ oldfd = -1;
+ } else {
+ /* Don't care if this fails: oldfd will be -1. */
+ oldfd = open(server.appendfilename,O_RDONLY|O_NONBLOCK);
+ }
+ } else {
+ /* AOF enabled */
+ oldfd = -1;
+ }
+
+ /* Rename the temporary file. This will not unlink the target file if
+ * it exists, because we reference it with "oldfd". */