xref: /redis-3.2.3/src/aof.c (revision 6972f18c)
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     listSetFreeMethod(c->reply,decrRefCountVoid);
511     listSetDupMethod(c->reply,dupClientReplyValue);
512     initClientMultiState(c);
513     return c;
514 }
515 
516 void freeFakeClient(struct redisClient *c) {
517     sdsfree(c->querybuf);
518     listRelease(c->reply);
519     listRelease(c->watched_keys);
520     freeClientMultiState(c);
521     zfree(c);
522 }
523 
524 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
525  * error (the append only file is zero-length) REDIS_ERR is returned. On
526  * fatal error an error message is logged and the program exists. */
527 int loadAppendOnlyFile(char *filename) {
528     struct redisClient *fakeClient;
529     FILE *fp = fopen(filename,"r");
530     struct redis_stat sb;
531     int old_aof_state = server.aof_state;
532     long loops = 0;
533 
534     if (fp && redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0) {
535         server.aof_current_size = 0;
536         fclose(fp);
537         return REDIS_ERR;
538     }
539 
540     if (fp == NULL) {
541         redisLog(REDIS_WARNING,"Fatal error: can't open the append log file for reading: %s",strerror(errno));
542         exit(1);
543     }
544 
545     /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
546      * to the same file we're about to read. */
547     server.aof_state = REDIS_AOF_OFF;
548 
549     fakeClient = createFakeClient();
550     startLoading(fp);
551 
552     while(1) {
553         int argc, j;
554         unsigned long len;
555         robj **argv;
556         char buf[128];
557         sds argsds;
558         struct redisCommand *cmd;
559 
560         /* Serve the clients from time to time */
561         if (!(loops++ % 1000)) {
562             loadingProgress(ftello(fp));
563             aeProcessEvents(server.el, AE_FILE_EVENTS|AE_DONT_WAIT);
564         }
565 
566         if (fgets(buf,sizeof(buf),fp) == NULL) {
567             if (feof(fp))
568                 break;
569             else
570                 goto readerr;
571         }
572         if (buf[0] != '*') goto fmterr;
573         argc = atoi(buf+1);
574         if (argc < 1) goto fmterr;
575 
576         argv = zmalloc(sizeof(robj*)*argc);
577         for (j = 0; j < argc; j++) {
578             if (fgets(buf,sizeof(buf),fp) == NULL) goto readerr;
579             if (buf[0] != '$') goto fmterr;
580             len = strtol(buf+1,NULL,10);
581             argsds = sdsnewlen(NULL,len);
582             if (len && fread(argsds,len,1,fp) == 0) goto fmterr;
583             argv[j] = createObject(REDIS_STRING,argsds);
584             if (fread(buf,2,1,fp) == 0) goto fmterr; /* discard CRLF */
585         }
586 
587         /* Command lookup */
588         cmd = lookupCommand(argv[0]->ptr);
589         if (!cmd) {
590             redisLog(REDIS_WARNING,"Unknown command '%s' reading the append only file", (char*)argv[0]->ptr);
591             exit(1);
592         }
593         /* Run the command in the context of a fake client */
594         fakeClient->argc = argc;
595         fakeClient->argv = argv;
596         cmd->proc(fakeClient);
597 
598         /* The fake client should not have a reply */
599         redisAssert(fakeClient->bufpos == 0 && listLength(fakeClient->reply) == 0);
600         /* The fake client should never get blocked */
601         redisAssert((fakeClient->flags & REDIS_BLOCKED) == 0);
602 
603         /* Clean up. Command code may have changed argv/argc so we use the
604          * argv/argc of the client instead of the local variables. */
605         for (j = 0; j < fakeClient->argc; j++)
606             decrRefCount(fakeClient->argv[j]);
607         zfree(fakeClient->argv);
608     }
609 
610     /* This point can only be reached when EOF is reached without errors.
611      * If the client is in the middle of a MULTI/EXEC, log error and quit. */
612     if (fakeClient->flags & REDIS_MULTI) goto readerr;
613 
614     fclose(fp);
615     freeFakeClient(fakeClient);
616     server.aof_state = old_aof_state;
617     stopLoading();
618     aofUpdateCurrentSize();
619     server.aof_rewrite_base_size = server.aof_current_size;
620     return REDIS_OK;
621 
622 readerr:
623     if (feof(fp)) {
624         redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file");
625     } else {
626         redisLog(REDIS_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno));
627     }
628     exit(1);
629 fmterr:
630     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>");
631     exit(1);
632 }
633 
634 /* ----------------------------------------------------------------------------
635  * AOF rewrite
636  * ------------------------------------------------------------------------- */
637 
638 /* Delegate writing an object to writing a bulk string or bulk long long.
639  * This is not placed in rio.c since that adds the redis.h dependency. */
640 int rioWriteBulkObject(rio *r, robj *obj) {
641     /* Avoid using getDecodedObject to help copy-on-write (we are often
642      * in a child process when this function is called). */
643     if (obj->encoding == REDIS_ENCODING_INT) {
644         return rioWriteBulkLongLong(r,(long)obj->ptr);
645     } else if (sdsEncodedObject(obj)) {
646         return rioWriteBulkString(r,obj->ptr,sdslen(obj->ptr));
647     } else {
648         redisPanic("Unknown string encoding");
649     }
650 }
651 
652 /* Emit the commands needed to rebuild a list object.
653  * The function returns 0 on error, 1 on success. */
654 int rewriteListObject(rio *r, robj *key, robj *o) {
655     long long count = 0, items = listTypeLength(o);
656 
657     if (o->encoding == REDIS_ENCODING_ZIPLIST) {
658         unsigned char *zl = o->ptr;
659         unsigned char *p = ziplistIndex(zl,0);
660         unsigned char *vstr;
661         unsigned int vlen;
662         long long vlong;
663 
664         while(ziplistGet(p,&vstr,&vlen,&vlong)) {
665             if (count == 0) {
666                 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
667                     REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
668 
669                 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
670                 if (rioWriteBulkString(r,"RPUSH",5) == 0) return 0;
671                 if (rioWriteBulkObject(r,key) == 0) return 0;
672             }
673             if (vstr) {
674                 if (rioWriteBulkString(r,(char*)vstr,vlen) == 0) return 0;
675             } else {
676                 if (rioWriteBulkLongLong(r,vlong) == 0) return 0;
677             }
678             p = ziplistNext(zl,p);
679             if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
680             items--;
681         }
682     } else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
683         list *list = o->ptr;
684         listNode *ln;
685         listIter li;
686 
687         listRewind(list,&li);
688         while((ln = listNext(&li))) {
689             robj *eleobj = listNodeValue(ln);
690 
691             if (count == 0) {
692                 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
693                     REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
694 
695                 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
696                 if (rioWriteBulkString(r,"RPUSH",5) == 0) return 0;
697                 if (rioWriteBulkObject(r,key) == 0) return 0;
698             }
699             if (rioWriteBulkObject(r,eleobj) == 0) return 0;
700             if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
701             items--;
702         }
703     } else {
704         redisPanic("Unknown list encoding");
705     }
706     return 1;
707 }
708 
709 /* Emit the commands needed to rebuild a set object.
710  * The function returns 0 on error, 1 on success. */
711 int rewriteSetObject(rio *r, robj *key, robj *o) {
712     long long count = 0, items = setTypeSize(o);
713 
714     if (o->encoding == REDIS_ENCODING_INTSET) {
715         int ii = 0;
716         int64_t llval;
717 
718         while(intsetGet(o->ptr,ii++,&llval)) {
719             if (count == 0) {
720                 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
721                     REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
722 
723                 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
724                 if (rioWriteBulkString(r,"SADD",4) == 0) return 0;
725                 if (rioWriteBulkObject(r,key) == 0) return 0;
726             }
727             if (rioWriteBulkLongLong(r,llval) == 0) return 0;
728             if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
729             items--;
730         }
731     } else if (o->encoding == REDIS_ENCODING_HT) {
732         dictIterator *di = dictGetIterator(o->ptr);
733         dictEntry *de;
734 
735         while((de = dictNext(di)) != NULL) {
736             robj *eleobj = dictGetKey(de);
737             if (count == 0) {
738                 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
739                     REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
740 
741                 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
742                 if (rioWriteBulkString(r,"SADD",4) == 0) return 0;
743                 if (rioWriteBulkObject(r,key) == 0) return 0;
744             }
745             if (rioWriteBulkObject(r,eleobj) == 0) return 0;
746             if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
747             items--;
748         }
749         dictReleaseIterator(di);
750     } else {
751         redisPanic("Unknown set encoding");
752     }
753     return 1;
754 }
755 
756 /* Emit the commands needed to rebuild a sorted set object.
757  * The function returns 0 on error, 1 on success. */
758 int rewriteSortedSetObject(rio *r, robj *key, robj *o) {
759     long long count = 0, items = zsetLength(o);
760 
761     if (o->encoding == REDIS_ENCODING_ZIPLIST) {
762         unsigned char *zl = o->ptr;
763         unsigned char *eptr, *sptr;
764         unsigned char *vstr;
765         unsigned int vlen;
766         long long vll;
767         double score;
768 
769         eptr = ziplistIndex(zl,0);
770         redisAssert(eptr != NULL);
771         sptr = ziplistNext(zl,eptr);
772         redisAssert(sptr != NULL);
773 
774         while (eptr != NULL) {
775             redisAssert(ziplistGet(eptr,&vstr,&vlen,&vll));
776             score = zzlGetScore(sptr);
777 
778             if (count == 0) {
779                 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
780                     REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
781 
782                 if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0;
783                 if (rioWriteBulkString(r,"ZADD",4) == 0) return 0;
784                 if (rioWriteBulkObject(r,key) == 0) return 0;
785             }
786             if (rioWriteBulkDouble(r,score) == 0) return 0;
787             if (vstr != NULL) {
788                 if (rioWriteBulkString(r,(char*)vstr,vlen) == 0) return 0;
789             } else {
790                 if (rioWriteBulkLongLong(r,vll) == 0) return 0;
791             }
792             zzlNext(zl,&eptr,&sptr);
793             if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
794             items--;
795         }
796     } else if (o->encoding == REDIS_ENCODING_SKIPLIST) {
797         zset *zs = o->ptr;
798         dictIterator *di = dictGetIterator(zs->dict);
799         dictEntry *de;
800 
801         while((de = dictNext(di)) != NULL) {
802             robj *eleobj = dictGetKey(de);
803             double *score = dictGetVal(de);
804 
805             if (count == 0) {
806                 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
807                     REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
808 
809                 if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0;
810                 if (rioWriteBulkString(r,"ZADD",4) == 0) return 0;
811                 if (rioWriteBulkObject(r,key) == 0) return 0;
812             }
813             if (rioWriteBulkDouble(r,*score) == 0) return 0;
814             if (rioWriteBulkObject(r,eleobj) == 0) return 0;
815             if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
816             items--;
817         }
818         dictReleaseIterator(di);
819     } else {
820         redisPanic("Unknown sorted zset encoding");
821     }
822     return 1;
823 }
824 
825 /* Write either the key or the value of the currently selected item of a hash.
826  * The 'hi' argument passes a valid Redis hash iterator.
827  * The 'what' filed specifies if to write a key or a value and can be
828  * either REDIS_HASH_KEY or REDIS_HASH_VALUE.
829  *
830  * The function returns 0 on error, non-zero on success. */
831 static int rioWriteHashIteratorCursor(rio *r, hashTypeIterator *hi, int what) {
832     if (hi->encoding == REDIS_ENCODING_ZIPLIST) {
833         unsigned char *vstr = NULL;
834         unsigned int vlen = UINT_MAX;
835         long long vll = LLONG_MAX;
836 
837         hashTypeCurrentFromZiplist(hi, what, &vstr, &vlen, &vll);
838         if (vstr) {
839             return rioWriteBulkString(r, (char*)vstr, vlen);
840         } else {
841             return rioWriteBulkLongLong(r, vll);
842         }
843 
844     } else if (hi->encoding == REDIS_ENCODING_HT) {
845         robj *value;
846 
847         hashTypeCurrentFromHashTable(hi, what, &value);
848         return rioWriteBulkObject(r, value);
849     }
850 
851     redisPanic("Unknown hash encoding");
852     return 0;
853 }
854 
855 /* Emit the commands needed to rebuild a hash object.
856  * The function returns 0 on error, 1 on success. */
857 int rewriteHashObject(rio *r, robj *key, robj *o) {
858     hashTypeIterator *hi;
859     long long count = 0, items = hashTypeLength(o);
860 
861     hi = hashTypeInitIterator(o);
862     while (hashTypeNext(hi) != REDIS_ERR) {
863         if (count == 0) {
864             int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
865                 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
866 
867             if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0;
868             if (rioWriteBulkString(r,"HMSET",5) == 0) return 0;
869             if (rioWriteBulkObject(r,key) == 0) return 0;
870         }
871 
872         if (rioWriteHashIteratorCursor(r, hi, REDIS_HASH_KEY) == 0) return 0;
873         if (rioWriteHashIteratorCursor(r, hi, REDIS_HASH_VALUE) == 0) return 0;
874         if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
875         items--;
876     }
877 
878     hashTypeReleaseIterator(hi);
879 
880     return 1;
881 }
882 
883 /* Write a sequence of commands able to fully rebuild the dataset into
884  * "filename". Used both by REWRITEAOF and BGREWRITEAOF.
885  *
886  * In order to minimize the number of commands needed in the rewritten
887  * log Redis uses variadic commands when possible, such as RPUSH, SADD
888  * and ZADD. However at max REDIS_AOF_REWRITE_ITEMS_PER_CMD items per time
889  * are inserted using a single command. */
890 int rewriteAppendOnlyFile(char *filename) {
891     dictIterator *di = NULL;
892     dictEntry *de;
893     rio aof;
894     FILE *fp;
895     char tmpfile[256];
896     int j;
897     long long now = mstime();
898 
899     /* Note that we have to use a different temp name here compared to the
900      * one used by rewriteAppendOnlyFileBackground() function. */
901     snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
902     fp = fopen(tmpfile,"w");
903     if (!fp) {
904         redisLog(REDIS_WARNING, "Opening the temp file for AOF rewrite in rewriteAppendOnlyFile(): %s", strerror(errno));
905         return REDIS_ERR;
906     }
907 
908     rioInitWithFile(&aof,fp);
909     if (server.aof_rewrite_incremental_fsync)
910         rioSetAutoSync(&aof,REDIS_AOF_AUTOSYNC_BYTES);
911     for (j = 0; j < server.dbnum; j++) {
912         char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
913         redisDb *db = server.db+j;
914         dict *d = db->dict;
915         if (dictSize(d) == 0) continue;
916         di = dictGetSafeIterator(d);
917         if (!di) {
918             fclose(fp);
919             return REDIS_ERR;
920         }
921 
922         /* SELECT the new DB */
923         if (rioWrite(&aof,selectcmd,sizeof(selectcmd)-1) == 0) goto werr;
924         if (rioWriteBulkLongLong(&aof,j) == 0) goto werr;
925 
926         /* Iterate this DB writing every entry */
927         while((de = dictNext(di)) != NULL) {
928             sds keystr;
929             robj key, *o;
930             long long expiretime;
931 
932             keystr = dictGetKey(de);
933             o = dictGetVal(de);
934             initStaticStringObject(key,keystr);
935 
936             expiretime = getExpire(db,&key);
937 
938             /* If this key is already expired skip it */
939             if (expiretime != -1 && expiretime < now) continue;
940 
941             /* Save the key and associated value */
942             if (o->type == REDIS_STRING) {
943                 /* Emit a SET command */
944                 char cmd[]="*3\r\n$3\r\nSET\r\n";
945                 if (rioWrite(&aof,cmd,sizeof(cmd)-1) == 0) goto werr;
946                 /* Key and value */
947                 if (rioWriteBulkObject(&aof,&key) == 0) goto werr;
948                 if (rioWriteBulkObject(&aof,o) == 0) goto werr;
949             } else if (o->type == REDIS_LIST) {
950                 if (rewriteListObject(&aof,&key,o) == 0) goto werr;
951             } else if (o->type == REDIS_SET) {
952                 if (rewriteSetObject(&aof,&key,o) == 0) goto werr;
953             } else if (o->type == REDIS_ZSET) {
954                 if (rewriteSortedSetObject(&aof,&key,o) == 0) goto werr;
955             } else if (o->type == REDIS_HASH) {
956                 if (rewriteHashObject(&aof,&key,o) == 0) goto werr;
957             } else {
958                 redisPanic("Unknown object type");
959             }
960             /* Save the expire time */
961             if (expiretime != -1) {
962                 char cmd[]="*3\r\n$9\r\nPEXPIREAT\r\n";
963                 if (rioWrite(&aof,cmd,sizeof(cmd)-1) == 0) goto werr;
964                 if (rioWriteBulkObject(&aof,&key) == 0) goto werr;
965                 if (rioWriteBulkLongLong(&aof,expiretime) == 0) goto werr;
966             }
967         }
968         dictReleaseIterator(di);
969     }
970 
971     /* Make sure data will not remain on the OS's output buffers */
972     fflush(fp);
973     aof_fsync(fileno(fp));
974     fclose(fp);
975 
976     /* Use RENAME to make sure the DB file is changed atomically only
977      * if the generate DB file is ok. */
978     if (rename(tmpfile,filename) == -1) {
979         redisLog(REDIS_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno));
980         unlink(tmpfile);
981         return REDIS_ERR;
982     }
983     redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");
984     return REDIS_OK;
985 
986 werr:
987     fclose(fp);
988     unlink(tmpfile);
989     redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));
990     if (di) dictReleaseIterator(di);
991     return REDIS_ERR;
992 }
993 
994 /* This is how rewriting of the append only file in background works:
995  *
996  * 1) The user calls BGREWRITEAOF
997  * 2) Redis calls this function, that forks():
998  *    2a) the child rewrite the append only file in a temp file.
999  *    2b) the parent accumulates differences in server.aof_rewrite_buf.
1000  * 3) When the child finished '2a' exists.
1001  * 4) The parent will trap the exit code, if it's OK, will append the
1002  *    data accumulated into server.aof_rewrite_buf into the temp file, and
1003  *    finally will rename(2) the temp file in the actual file name.
1004  *    The the new file is reopened as the new append only file. Profit!
1005  */
1006 int rewriteAppendOnlyFileBackground(void) {
1007     pid_t childpid;
1008     long long start;
1009 
1010     if (server.aof_child_pid != -1) return REDIS_ERR;
1011     start = ustime();
1012     if ((childpid = fork()) == 0) {
1013         char tmpfile[256];
1014 
1015         /* Child */
1016         closeListeningSockets(0);
1017         redisSetProcTitle("redis-aof-rewrite");
1018         snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
1019         if (rewriteAppendOnlyFile(tmpfile) == REDIS_OK) {
1020             size_t private_dirty = zmalloc_get_private_dirty();
1021 
1022             if (private_dirty) {
1023                 redisLog(REDIS_NOTICE,
1024                     "AOF rewrite: %zu MB of memory used by copy-on-write",
1025                     private_dirty/(1024*1024));
1026             }
1027             exitFromChild(0);
1028         } else {
1029             exitFromChild(1);
1030         }
1031     } else {
1032         /* Parent */
1033         server.stat_fork_time = ustime()-start;
1034         if (childpid == -1) {
1035             redisLog(REDIS_WARNING,
1036                 "Can't rewrite append only file in background: fork: %s",
1037                 strerror(errno));
1038             return REDIS_ERR;
1039         }
1040         redisLog(REDIS_NOTICE,
1041             "Background append only file rewriting started by pid %d",childpid);
1042         server.aof_rewrite_scheduled = 0;
1043         server.aof_rewrite_time_start = time(NULL);
1044         server.aof_child_pid = childpid;
1045         updateDictResizePolicy();
1046         /* We set appendseldb to -1 in order to force the next call to the
1047          * feedAppendOnlyFile() to issue a SELECT command, so the differences
1048          * accumulated by the parent into server.aof_rewrite_buf will start
1049          * with a SELECT statement and it will be safe to merge. */
1050         server.aof_selected_db = -1;
1051         replicationScriptCacheFlush();
1052         return REDIS_OK;
1053     }
1054     return REDIS_OK; /* unreached */
1055 }
1056 
1057 void bgrewriteaofCommand(redisClient *c) {
1058     if (server.aof_child_pid != -1) {
1059         addReplyError(c,"Background append only file rewriting already in progress");
1060     } else if (server.rdb_child_pid != -1) {
1061         server.aof_rewrite_scheduled = 1;
1062         addReplyStatus(c,"Background append only file rewriting scheduled");
1063     } else if (rewriteAppendOnlyFileBackground() == REDIS_OK) {
1064         addReplyStatus(c,"Background append only file rewriting started");
1065     } else {
1066         addReply(c,shared.err);
1067     }
1068 }
1069 
1070 void aofRemoveTempFile(pid_t childpid) {
1071     char tmpfile[256];
1072 
1073     snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid);
1074     unlink(tmpfile);
1075 }
1076 
1077 /* Update the server.aof_current_size filed explicitly using stat(2)
1078  * to check the size of the file. This is useful after a rewrite or after
1079  * a restart, normally the size is updated just adding the write length
1080  * to the current length, that is much faster. */
1081 void aofUpdateCurrentSize(void) {
1082     struct redis_stat sb;
1083 
1084     if (redis_fstat(server.aof_fd,&sb) == -1) {
1085         redisLog(REDIS_WARNING,"Unable to obtain the AOF file length. stat: %s",
1086             strerror(errno));
1087     } else {
1088         server.aof_current_size = sb.st_size;
1089     }
1090 }
1091 
1092 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1093  * Handle this. */
1094 void backgroundRewriteDoneHandler(int exitcode, int bysignal) {
1095     if (!bysignal && exitcode == 0) {
1096         int newfd, oldfd;
1097         char tmpfile[256];
1098         long long now = ustime();
1099 
1100         redisLog(REDIS_NOTICE,
1101             "Background AOF rewrite terminated with success");
1102 
1103         /* Flush the differences accumulated by the parent to the
1104          * rewritten AOF. */
1105         snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof",
1106             (int)server.aof_child_pid);
1107         newfd = open(tmpfile,O_WRONLY|O_APPEND);
1108         if (newfd == -1) {
1109             redisLog(REDIS_WARNING,
1110                 "Unable to open the temporary AOF produced by the child: %s", strerror(errno));
1111             goto cleanup;
1112         }
1113 
1114         if (aofRewriteBufferWrite(newfd) == -1) {
1115             redisLog(REDIS_WARNING,
1116                 "Error trying to flush the parent diff to the rewritten AOF: %s", strerror(errno));
1117             close(newfd);
1118             goto cleanup;
1119         }
1120 
1121         redisLog(REDIS_NOTICE,
1122             "Parent diff successfully flushed to the rewritten AOF (%lu bytes)", aofRewriteBufferSize());
1123 
1124         /* The only remaining thing to do is to rename the temporary file to
1125          * the configured file and switch the file descriptor used to do AOF
1126          * writes. We don't want close(2) or rename(2) calls to block the
1127          * server on old file deletion.
1128          *
1129          * There are two possible scenarios:
1130          *
1131          * 1) AOF is DISABLED and this was a one time rewrite. The temporary
1132          * file will be renamed to the configured file. When this file already
1133          * exists, it will be unlinked, which may block the server.
1134          *
1135          * 2) AOF is ENABLED and the rewritten AOF will immediately start
1136          * receiving writes. After the temporary file is renamed to the
1137          * configured file, the original AOF file descriptor will be closed.
1138          * Since this will be the last reference to that file, closing it
1139          * causes the underlying file to be unlinked, which may block the
1140          * server.
1141          *
1142          * To mitigate the blocking effect of the unlink operation (either
1143          * caused by rename(2) in scenario 1, or by close(2) in scenario 2), we
1144          * use a background thread to take care of this. First, we
1145          * make scenario 1 identical to scenario 2 by opening the target file
1146          * when it exists. The unlink operation after the rename(2) will then
1147          * be executed upon calling close(2) for its descriptor. Everything to
1148          * guarantee atomicity for this switch has already happened by then, so
1149          * we don't care what the outcome or duration of that close operation
1150          * is, as long as the file descriptor is released again. */
1151         if (server.aof_fd == -1) {
1152             /* AOF disabled */
1153 
1154              /* Don't care if this fails: oldfd will be -1 and we handle that.
1155               * One notable case of -1 return is if the old file does
1156               * not exist. */
1157              oldfd = open(server.aof_filename,O_RDONLY|O_NONBLOCK);
1158         } else {
1159             /* AOF enabled */
1160             oldfd = -1; /* We'll set this to the current AOF filedes later. */
1161         }
1162 
1163         /* Rename the temporary file. This will not unlink the target file if
1164          * it exists, because we reference it with "oldfd". */
1165         if (rename(tmpfile,server.aof_filename) == -1) {
1166             redisLog(REDIS_WARNING,
1167                 "Error trying to rename the temporary AOF file: %s", strerror(errno));
1168             close(newfd);
1169             if (oldfd != -1) close(oldfd);
1170             goto cleanup;
1171         }
1172 
1173         if (server.aof_fd == -1) {
1174             /* AOF disabled, we don't need to set the AOF file descriptor
1175              * to this new file, so we can close it. */
1176             close(newfd);
1177         } else {
1178             /* AOF enabled, replace the old fd with the new one. */
1179             oldfd = server.aof_fd;
1180             server.aof_fd = newfd;
1181             if (server.aof_fsync == AOF_FSYNC_ALWAYS)
1182                 aof_fsync(newfd);
1183             else if (server.aof_fsync == AOF_FSYNC_EVERYSEC)
1184                 aof_background_fsync(newfd);
1185             server.aof_selected_db = -1; /* Make sure SELECT is re-issued */
1186             aofUpdateCurrentSize();
1187             server.aof_rewrite_base_size = server.aof_current_size;
1188 
1189             /* Clear regular AOF buffer since its contents was just written to
1190              * the new AOF from the background rewrite buffer. */
1191             sdsfree(server.aof_buf);
1192             server.aof_buf = sdsempty();
1193         }
1194 
1195         server.aof_lastbgrewrite_status = REDIS_OK;
1196 
1197         redisLog(REDIS_NOTICE, "Background AOF rewrite finished successfully");
1198         /* Change state from WAIT_REWRITE to ON if needed */
1199         if (server.aof_state == REDIS_AOF_WAIT_REWRITE)
1200             server.aof_state = REDIS_AOF_ON;
1201 
1202         /* Asynchronously close the overwritten AOF. */
1203         if (oldfd != -1) bioCreateBackgroundJob(REDIS_BIO_CLOSE_FILE,(void*)(long)oldfd,NULL,NULL);
1204 
1205         redisLog(REDIS_VERBOSE,
1206             "Background AOF rewrite signal handler took %lldus", ustime()-now);
1207     } else if (!bysignal && exitcode != 0) {
1208         server.aof_lastbgrewrite_status = REDIS_ERR;
1209 
1210         redisLog(REDIS_WARNING,
1211             "Background AOF rewrite terminated with error");
1212     } else {
1213         server.aof_lastbgrewrite_status = REDIS_ERR;
1214 
1215         redisLog(REDIS_WARNING,
1216             "Background AOF rewrite terminated by signal %d", bysignal);
1217     }
1218 
1219 cleanup:
1220     aofRewriteBufferReset();
1221     aofRemoveTempFile(server.aof_child_pid);
1222     server.aof_child_pid = -1;
1223     server.aof_rewrite_time_last = time(NULL)-server.aof_rewrite_time_start;
1224     server.aof_rewrite_time_start = -1;
1225     /* Schedule a new rewrite if we are waiting for it to switch the AOF ON. */
1226     if (server.aof_state == REDIS_AOF_WAIT_REWRITE)
1227         server.aof_rewrite_scheduled = 1;
1228 }
1229