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