xref: /redis-3.2.3/src/aof.c (revision 40f822da)
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 no 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 void flushAppendOnlyFile(int force) {
230     ssize_t nwritten;
231     int sync_in_progress = 0;
232 
233     if (sdslen(server.aof_buf) == 0) return;
234 
235     if (server.aof_fsync == AOF_FSYNC_EVERYSEC)
236         sync_in_progress = bioPendingJobsOfType(REDIS_BIO_AOF_FSYNC) != 0;
237 
238     if (server.aof_fsync == AOF_FSYNC_EVERYSEC && !force) {
239         /* With this append fsync policy we do background fsyncing.
240          * If the fsync is still in progress we can try to delay
241          * the write for a couple of seconds. */
242         if (sync_in_progress) {
243             if (server.aof_flush_postponed_start == 0) {
244                 /* No previous write postponinig, remember that we are
245                  * postponing the flush and return. */
246                 server.aof_flush_postponed_start = server.unixtime;
247                 return;
248             } else if (server.unixtime - server.aof_flush_postponed_start < 2) {
249                 /* We were already waiting for fsync to finish, but for less
250                  * than two seconds this is still ok. Postpone again. */
251                 return;
252             }
253             /* Otherwise fall trough, and go write since we can't wait
254              * over two seconds. */
255             server.aof_delayed_fsync++;
256             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.");
257         }
258     }
259     /* If you are following this code path, then we are going to write so
260      * set reset the postponed flush sentinel to zero. */
261     server.aof_flush_postponed_start = 0;
262 
263     /* We want to perform a single write. This should be guaranteed atomic
264      * at least if the filesystem we are writing is a real physical one.
265      * While this will save us against the server being killed I don't think
266      * there is much to do about the whole server stopping for power problems
267      * or alike */
268     nwritten = write(server.aof_fd,server.aof_buf,sdslen(server.aof_buf));
269     if (nwritten != (signed)sdslen(server.aof_buf)) {
270         /* Ooops, we are in troubles. The best thing to do for now is
271          * aborting instead of giving the illusion that everything is
272          * working as expected. */
273         if (nwritten == -1) {
274             redisLog(REDIS_WARNING,"Exiting on error writing to the append-only file: %s",strerror(errno));
275         } else {
276             redisLog(REDIS_WARNING,"Exiting on short write while writing to "
277                                    "the append-only file: %s (nwritten=%ld, "
278                                    "expected=%ld)",
279                                    strerror(errno),
280                                    (long)nwritten,
281                                    (long)sdslen(server.aof_buf));
282 
283             if (ftruncate(server.aof_fd, server.aof_current_size) == -1) {
284                 redisLog(REDIS_WARNING, "Could not remove short write "
285                          "from the append-only file.  Redis may refuse "
286                          "to load the AOF the next time it starts.  "
287                          "ftruncate: %s", strerror(errno));
288             }
289         }
290         exit(1);
291     }
292     server.aof_current_size += nwritten;
293 
294     /* Re-use AOF buffer when it is small enough. The maximum comes from the
295      * arena size of 4k minus some overhead (but is otherwise arbitrary). */
296     if ((sdslen(server.aof_buf)+sdsavail(server.aof_buf)) < 4000) {
297         sdsclear(server.aof_buf);
298     } else {
299         sdsfree(server.aof_buf);
300         server.aof_buf = sdsempty();
301     }
302 
303     /* Don't fsync if no-appendfsync-on-rewrite is set to yes and there are
304      * children doing I/O in the background. */
305     if (server.aof_no_fsync_on_rewrite &&
306         (server.aof_child_pid != -1 || server.rdb_child_pid != -1))
307             return;
308 
309     /* Perform the fsync if needed. */
310     if (server.aof_fsync == AOF_FSYNC_ALWAYS) {
311         /* aof_fsync is defined as fdatasync() for Linux in order to avoid
312          * flushing metadata. */
313         aof_fsync(server.aof_fd); /* Let's try to get this data on the disk */
314         server.aof_last_fsync = server.unixtime;
315     } else if ((server.aof_fsync == AOF_FSYNC_EVERYSEC &&
316                 server.unixtime > server.aof_last_fsync)) {
317         if (!sync_in_progress) aof_background_fsync(server.aof_fd);
318         server.aof_last_fsync = server.unixtime;
319     }
320 }
321 
322 sds catAppendOnlyGenericCommand(sds dst, int argc, robj **argv) {
323     char buf[32];
324     int len, j;
325     robj *o;
326 
327     buf[0] = '*';
328     len = 1+ll2string(buf+1,sizeof(buf)-1,argc);
329     buf[len++] = '\r';
330     buf[len++] = '\n';
331     dst = sdscatlen(dst,buf,len);
332 
333     for (j = 0; j < argc; j++) {
334         o = getDecodedObject(argv[j]);
335         buf[0] = '$';
336         len = 1+ll2string(buf+1,sizeof(buf)-1,sdslen(o->ptr));
337         buf[len++] = '\r';
338         buf[len++] = '\n';
339         dst = sdscatlen(dst,buf,len);
340         dst = sdscatlen(dst,o->ptr,sdslen(o->ptr));
341         dst = sdscatlen(dst,"\r\n",2);
342         decrRefCount(o);
343     }
344     return dst;
345 }
346 
347 /* Create the sds representation of an PEXPIREAT command, using
348  * 'seconds' as time to live and 'cmd' to understand what command
349  * we are translating into a PEXPIREAT.
350  *
351  * This command is used in order to translate EXPIRE and PEXPIRE commands
352  * into PEXPIREAT command so that we retain precision in the append only
353  * file, and the time is always absolute and not relative. */
354 sds catAppendOnlyExpireAtCommand(sds buf, struct redisCommand *cmd, robj *key, robj *seconds) {
355     long long when;
356     robj *argv[3];
357 
358     /* Make sure we can use strtol */
359     seconds = getDecodedObject(seconds);
360     when = strtoll(seconds->ptr,NULL,10);
361     /* Convert argument into milliseconds for EXPIRE, SETEX, EXPIREAT */
362     if (cmd->proc == expireCommand || cmd->proc == setexCommand ||
363         cmd->proc == expireatCommand)
364     {
365         when *= 1000;
366     }
367     /* Convert into absolute time for EXPIRE, PEXPIRE, SETEX, PSETEX */
368     if (cmd->proc == expireCommand || cmd->proc == pexpireCommand ||
369         cmd->proc == setexCommand || cmd->proc == psetexCommand)
370     {
371         when += mstime();
372     }
373     decrRefCount(seconds);
374 
375     argv[0] = createStringObject("PEXPIREAT",9);
376     argv[1] = key;
377     argv[2] = createStringObjectFromLongLong(when);
378     buf = catAppendOnlyGenericCommand(buf, 3, argv);
379     decrRefCount(argv[0]);
380     decrRefCount(argv[2]);
381     return buf;
382 }
383 
384 void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) {
385     sds buf = sdsempty();
386     robj *tmpargv[3];
387 
388     /* The DB this command was targeting is not the same as the last command
389      * we appendend. To issue a SELECT command is needed. */
390     if (dictid != server.aof_selected_db) {
391         char seldb[64];
392 
393         snprintf(seldb,sizeof(seldb),"%d",dictid);
394         buf = sdscatprintf(buf,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
395             (unsigned long)strlen(seldb),seldb);
396         server.aof_selected_db = dictid;
397     }
398 
399     if (cmd->proc == expireCommand || cmd->proc == pexpireCommand ||
400         cmd->proc == expireatCommand) {
401         /* Translate EXPIRE/PEXPIRE/EXPIREAT into PEXPIREAT */
402         buf = catAppendOnlyExpireAtCommand(buf,cmd,argv[1],argv[2]);
403     } else if (cmd->proc == setexCommand || cmd->proc == psetexCommand) {
404         /* Translate SETEX/PSETEX to SET and PEXPIREAT */
405         tmpargv[0] = createStringObject("SET",3);
406         tmpargv[1] = argv[1];
407         tmpargv[2] = argv[3];
408         buf = catAppendOnlyGenericCommand(buf,3,tmpargv);
409         decrRefCount(tmpargv[0]);
410         buf = catAppendOnlyExpireAtCommand(buf,cmd,argv[1],argv[2]);
411     } else {
412         /* All the other commands don't need translation or need the
413          * same translation already operated in the command vector
414          * for the replication itself. */
415         buf = catAppendOnlyGenericCommand(buf,argc,argv);
416     }
417 
418     /* Append to the AOF buffer. This will be flushed on disk just before
419      * of re-entering the event loop, so before the client will get a
420      * positive reply about the operation performed. */
421     if (server.aof_state == REDIS_AOF_ON)
422         server.aof_buf = sdscatlen(server.aof_buf,buf,sdslen(buf));
423 
424     /* If a background append only file rewriting is in progress we want to
425      * accumulate the differences between the child DB and the current one
426      * in a buffer, so that when the child process will do its work we
427      * can append the differences to the new append only file. */
428     if (server.aof_child_pid != -1)
429         aofRewriteBufferAppend((unsigned char*)buf,sdslen(buf));
430 
431     sdsfree(buf);
432 }
433 
434 /* ----------------------------------------------------------------------------
435  * AOF loading
436  * ------------------------------------------------------------------------- */
437 
438 /* In Redis commands are always executed in the context of a client, so in
439  * order to load the append only file we need to create a fake client. */
440 struct redisClient *createFakeClient(void) {
441     struct redisClient *c = zmalloc(sizeof(*c));
442 
443     selectDb(c,0);
444     c->fd = -1;
445     c->name = NULL;
446     c->querybuf = sdsempty();
447     c->querybuf_peak = 0;
448     c->argc = 0;
449     c->argv = NULL;
450     c->bufpos = 0;
451     c->flags = 0;
452     /* We set the fake client as a slave waiting for the synchronization
453      * so that Redis will not try to send replies to this client. */
454     c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
455     c->reply = listCreate();
456     c->reply_bytes = 0;
457     c->obuf_soft_limit_reached_time = 0;
458     c->watched_keys = listCreate();
459     listSetFreeMethod(c->reply,decrRefCountVoid);
460     listSetDupMethod(c->reply,dupClientReplyValue);
461     initClientMultiState(c);
462     return c;
463 }
464 
465 void freeFakeClient(struct redisClient *c) {
466     sdsfree(c->querybuf);
467     listRelease(c->reply);
468     listRelease(c->watched_keys);
469     freeClientMultiState(c);
470     zfree(c);
471 }
472 
473 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
474  * error (the append only file is zero-length) REDIS_ERR is returned. On
475  * fatal error an error message is logged and the program exists. */
476 int loadAppendOnlyFile(char *filename) {
477     struct redisClient *fakeClient;
478     FILE *fp = fopen(filename,"r");
479     struct redis_stat sb;
480     int old_aof_state = server.aof_state;
481     long loops = 0;
482 
483     if (fp && redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0) {
484         server.aof_current_size = 0;
485         fclose(fp);
486         return REDIS_ERR;
487     }
488 
489     if (fp == NULL) {
490         redisLog(REDIS_WARNING,"Fatal error: can't open the append log file for reading: %s",strerror(errno));
491         exit(1);
492     }
493 
494     /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
495      * to the same file we're about to read. */
496     server.aof_state = REDIS_AOF_OFF;
497 
498     fakeClient = createFakeClient();
499     startLoading(fp);
500 
501     while(1) {
502         int argc, j;
503         unsigned long len;
504         robj **argv;
505         char buf[128];
506         sds argsds;
507         struct redisCommand *cmd;
508 
509         /* Serve the clients from time to time */
510         if (!(loops++ % 1000)) {
511             loadingProgress(ftello(fp));
512             aeProcessEvents(server.el, AE_FILE_EVENTS|AE_DONT_WAIT);
513         }
514 
515         if (fgets(buf,sizeof(buf),fp) == NULL) {
516             if (feof(fp))
517                 break;
518             else
519                 goto readerr;
520         }
521         if (buf[0] != '*') goto fmterr;
522         argc = atoi(buf+1);
523         if (argc < 1) goto fmterr;
524 
525         argv = zmalloc(sizeof(robj*)*argc);
526         for (j = 0; j < argc; j++) {
527             if (fgets(buf,sizeof(buf),fp) == NULL) goto readerr;
528             if (buf[0] != '$') goto fmterr;
529             len = strtol(buf+1,NULL,10);
530             argsds = sdsnewlen(NULL,len);
531             if (len && fread(argsds,len,1,fp) == 0) goto fmterr;
532             argv[j] = createObject(REDIS_STRING,argsds);
533             if (fread(buf,2,1,fp) == 0) goto fmterr; /* discard CRLF */
534         }
535 
536         /* Command lookup */
537         cmd = lookupCommand(argv[0]->ptr);
538         if (!cmd) {
539             redisLog(REDIS_WARNING,"Unknown command '%s' reading the append only file", argv[0]->ptr);
540             exit(1);
541         }
542         /* Run the command in the context of a fake client */
543         fakeClient->argc = argc;
544         fakeClient->argv = argv;
545         cmd->proc(fakeClient);
546 
547         /* The fake client should not have a reply */
548         redisAssert(fakeClient->bufpos == 0 && listLength(fakeClient->reply) == 0);
549         /* The fake client should never get blocked */
550         redisAssert((fakeClient->flags & REDIS_BLOCKED) == 0);
551 
552         /* Clean up. Command code may have changed argv/argc so we use the
553          * argv/argc of the client instead of the local variables. */
554         for (j = 0; j < fakeClient->argc; j++)
555             decrRefCount(fakeClient->argv[j]);
556         zfree(fakeClient->argv);
557     }
558 
559     /* This point can only be reached when EOF is reached without errors.
560      * If the client is in the middle of a MULTI/EXEC, log error and quit. */
561     if (fakeClient->flags & REDIS_MULTI) goto readerr;
562 
563     fclose(fp);
564     freeFakeClient(fakeClient);
565     server.aof_state = old_aof_state;
566     stopLoading();
567     aofUpdateCurrentSize();
568     server.aof_rewrite_base_size = server.aof_current_size;
569     return REDIS_OK;
570 
571 readerr:
572     if (feof(fp)) {
573         redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file");
574     } else {
575         redisLog(REDIS_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno));
576     }
577     exit(1);
578 fmterr:
579     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>");
580     exit(1);
581 }
582 
583 /* ----------------------------------------------------------------------------
584  * AOF rewrite
585  * ------------------------------------------------------------------------- */
586 
587 /* Delegate writing an object to writing a bulk string or bulk long long.
588  * This is not placed in rio.c since that adds the redis.h dependency. */
589 int rioWriteBulkObject(rio *r, robj *obj) {
590     /* Avoid using getDecodedObject to help copy-on-write (we are often
591      * in a child process when this function is called). */
592     if (obj->encoding == REDIS_ENCODING_INT) {
593         return rioWriteBulkLongLong(r,(long)obj->ptr);
594     } else if (obj->encoding == REDIS_ENCODING_RAW) {
595         return rioWriteBulkString(r,obj->ptr,sdslen(obj->ptr));
596     } else {
597         redisPanic("Unknown string encoding");
598     }
599 }
600 
601 /* Emit the commands needed to rebuild a list object.
602  * The function returns 0 on error, 1 on success. */
603 int rewriteListObject(rio *r, robj *key, robj *o) {
604     long long count = 0, items = listTypeLength(o);
605 
606     if (o->encoding == REDIS_ENCODING_ZIPLIST) {
607         unsigned char *zl = o->ptr;
608         unsigned char *p = ziplistIndex(zl,0);
609         unsigned char *vstr;
610         unsigned int vlen;
611         long long vlong;
612 
613         while(ziplistGet(p,&vstr,&vlen,&vlong)) {
614             if (count == 0) {
615                 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
616                     REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
617 
618                 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
619                 if (rioWriteBulkString(r,"RPUSH",5) == 0) return 0;
620                 if (rioWriteBulkObject(r,key) == 0) return 0;
621             }
622             if (vstr) {
623                 if (rioWriteBulkString(r,(char*)vstr,vlen) == 0) return 0;
624             } else {
625                 if (rioWriteBulkLongLong(r,vlong) == 0) return 0;
626             }
627             p = ziplistNext(zl,p);
628             if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
629             items--;
630         }
631     } else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
632         list *list = o->ptr;
633         listNode *ln;
634         listIter li;
635 
636         listRewind(list,&li);
637         while((ln = listNext(&li))) {
638             robj *eleobj = listNodeValue(ln);
639 
640             if (count == 0) {
641                 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
642                     REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
643 
644                 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
645                 if (rioWriteBulkString(r,"RPUSH",5) == 0) return 0;
646                 if (rioWriteBulkObject(r,key) == 0) return 0;
647             }
648             if (rioWriteBulkObject(r,eleobj) == 0) return 0;
649             if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
650             items--;
651         }
652     } else {
653         redisPanic("Unknown list encoding");
654     }
655     return 1;
656 }
657 
658 /* Emit the commands needed to rebuild a set object.
659  * The function returns 0 on error, 1 on success. */
660 int rewriteSetObject(rio *r, robj *key, robj *o) {
661     long long count = 0, items = setTypeSize(o);
662 
663     if (o->encoding == REDIS_ENCODING_INTSET) {
664         int ii = 0;
665         int64_t llval;
666 
667         while(intsetGet(o->ptr,ii++,&llval)) {
668             if (count == 0) {
669                 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
670                     REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
671 
672                 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
673                 if (rioWriteBulkString(r,"SADD",4) == 0) return 0;
674                 if (rioWriteBulkObject(r,key) == 0) return 0;
675             }
676             if (rioWriteBulkLongLong(r,llval) == 0) return 0;
677             if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
678             items--;
679         }
680     } else if (o->encoding == REDIS_ENCODING_HT) {
681         dictIterator *di = dictGetIterator(o->ptr);
682         dictEntry *de;
683 
684         while((de = dictNext(di)) != NULL) {
685             robj *eleobj = dictGetKey(de);
686             if (count == 0) {
687                 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
688                     REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
689 
690                 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
691                 if (rioWriteBulkString(r,"SADD",4) == 0) return 0;
692                 if (rioWriteBulkObject(r,key) == 0) return 0;
693             }
694             if (rioWriteBulkObject(r,eleobj) == 0) return 0;
695             if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
696             items--;
697         }
698         dictReleaseIterator(di);
699     } else {
700         redisPanic("Unknown set encoding");
701     }
702     return 1;
703 }
704 
705 /* Emit the commands needed to rebuild a sorted set object.
706  * The function returns 0 on error, 1 on success. */
707 int rewriteSortedSetObject(rio *r, robj *key, robj *o) {
708     long long count = 0, items = zsetLength(o);
709 
710     if (o->encoding == REDIS_ENCODING_ZIPLIST) {
711         unsigned char *zl = o->ptr;
712         unsigned char *eptr, *sptr;
713         unsigned char *vstr;
714         unsigned int vlen;
715         long long vll;
716         double score;
717 
718         eptr = ziplistIndex(zl,0);
719         redisAssert(eptr != NULL);
720         sptr = ziplistNext(zl,eptr);
721         redisAssert(sptr != NULL);
722 
723         while (eptr != NULL) {
724             redisAssert(ziplistGet(eptr,&vstr,&vlen,&vll));
725             score = zzlGetScore(sptr);
726 
727             if (count == 0) {
728                 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
729                     REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
730 
731                 if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0;
732                 if (rioWriteBulkString(r,"ZADD",4) == 0) return 0;
733                 if (rioWriteBulkObject(r,key) == 0) return 0;
734             }
735             if (rioWriteBulkDouble(r,score) == 0) return 0;
736             if (vstr != NULL) {
737                 if (rioWriteBulkString(r,(char*)vstr,vlen) == 0) return 0;
738             } else {
739                 if (rioWriteBulkLongLong(r,vll) == 0) return 0;
740             }
741             zzlNext(zl,&eptr,&sptr);
742             if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
743             items--;
744         }
745     } else if (o->encoding == REDIS_ENCODING_SKIPLIST) {
746         zset *zs = o->ptr;
747         dictIterator *di = dictGetIterator(zs->dict);
748         dictEntry *de;
749 
750         while((de = dictNext(di)) != NULL) {
751             robj *eleobj = dictGetKey(de);
752             double *score = dictGetVal(de);
753 
754             if (count == 0) {
755                 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
756                     REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
757 
758                 if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0;
759                 if (rioWriteBulkString(r,"ZADD",4) == 0) return 0;
760                 if (rioWriteBulkObject(r,key) == 0) return 0;
761             }
762             if (rioWriteBulkDouble(r,*score) == 0) return 0;
763             if (rioWriteBulkObject(r,eleobj) == 0) return 0;
764             if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
765             items--;
766         }
767         dictReleaseIterator(di);
768     } else {
769         redisPanic("Unknown sorted zset encoding");
770     }
771     return 1;
772 }
773 
774 /* Write either the key or the value of the currently selected item of an hash.
775  * The 'hi' argument passes a valid Redis hash iterator.
776  * The 'what' filed specifies if to write a key or a value and can be
777  * either REDIS_HASH_KEY or REDIS_HASH_VALUE.
778  *
779  * The function returns 0 on error, non-zero on success. */
780 static int rioWriteHashIteratorCursor(rio *r, hashTypeIterator *hi, int what) {
781     if (hi->encoding == REDIS_ENCODING_ZIPLIST) {
782         unsigned char *vstr = NULL;
783         unsigned int vlen = UINT_MAX;
784         long long vll = LLONG_MAX;
785 
786         hashTypeCurrentFromZiplist(hi, what, &vstr, &vlen, &vll);
787         if (vstr) {
788             return rioWriteBulkString(r, (char*)vstr, vlen);
789         } else {
790             return rioWriteBulkLongLong(r, vll);
791         }
792 
793     } else if (hi->encoding == REDIS_ENCODING_HT) {
794         robj *value;
795 
796         hashTypeCurrentFromHashTable(hi, what, &value);
797         return rioWriteBulkObject(r, value);
798     }
799 
800     redisPanic("Unknown hash encoding");
801     return 0;
802 }
803 
804 /* Emit the commands needed to rebuild a hash object.
805  * The function returns 0 on error, 1 on success. */
806 int rewriteHashObject(rio *r, robj *key, robj *o) {
807     hashTypeIterator *hi;
808     long long count = 0, items = hashTypeLength(o);
809 
810     hi = hashTypeInitIterator(o);
811     while (hashTypeNext(hi) != REDIS_ERR) {
812         if (count == 0) {
813             int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
814                 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
815 
816             if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0;
817             if (rioWriteBulkString(r,"HMSET",5) == 0) return 0;
818             if (rioWriteBulkObject(r,key) == 0) return 0;
819         }
820 
821         if (rioWriteHashIteratorCursor(r, hi, REDIS_HASH_KEY) == 0) return 0;
822         if (rioWriteHashIteratorCursor(r, hi, REDIS_HASH_VALUE) == 0) return 0;
823         if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
824         items--;
825     }
826 
827     hashTypeReleaseIterator(hi);
828 
829     return 1;
830 }
831 
832 /* Write a sequence of commands able to fully rebuild the dataset into
833  * "filename". Used both by REWRITEAOF and BGREWRITEAOF.
834  *
835  * In order to minimize the number of commands needed in the rewritten
836  * log Redis uses variadic commands when possible, such as RPUSH, SADD
837  * and ZADD. However at max REDIS_AOF_REWRITE_ITEMS_PER_CMD items per time
838  * are inserted using a single command. */
839 int rewriteAppendOnlyFile(char *filename) {
840     dictIterator *di = NULL;
841     dictEntry *de;
842     rio aof;
843     FILE *fp;
844     char tmpfile[256];
845     int j;
846     long long now = mstime();
847 
848     /* Note that we have to use a different temp name here compared to the
849      * one used by rewriteAppendOnlyFileBackground() function. */
850     snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
851     fp = fopen(tmpfile,"w");
852     if (!fp) {
853         redisLog(REDIS_WARNING, "Opening the temp file for AOF rewrite in rewriteAppendOnlyFile(): %s", strerror(errno));
854         return REDIS_ERR;
855     }
856 
857     rioInitWithFile(&aof,fp);
858     for (j = 0; j < server.dbnum; j++) {
859         char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
860         redisDb *db = server.db+j;
861         dict *d = db->dict;
862         if (dictSize(d) == 0) continue;
863         di = dictGetSafeIterator(d);
864         if (!di) {
865             fclose(fp);
866             return REDIS_ERR;
867         }
868 
869         /* SELECT the new DB */
870         if (rioWrite(&aof,selectcmd,sizeof(selectcmd)-1) == 0) goto werr;
871         if (rioWriteBulkLongLong(&aof,j) == 0) goto werr;
872 
873         /* Iterate this DB writing every entry */
874         while((de = dictNext(di)) != NULL) {
875             sds keystr;
876             robj key, *o;
877             long long expiretime;
878 
879             keystr = dictGetKey(de);
880             o = dictGetVal(de);
881             initStaticStringObject(key,keystr);
882 
883             expiretime = getExpire(db,&key);
884 
885             /* Save the key and associated value */
886             if (o->type == REDIS_STRING) {
887                 /* Emit a SET command */
888                 char cmd[]="*3\r\n$3\r\nSET\r\n";
889                 if (rioWrite(&aof,cmd,sizeof(cmd)-1) == 0) goto werr;
890                 /* Key and value */
891                 if (rioWriteBulkObject(&aof,&key) == 0) goto werr;
892                 if (rioWriteBulkObject(&aof,o) == 0) goto werr;
893             } else if (o->type == REDIS_LIST) {
894                 if (rewriteListObject(&aof,&key,o) == 0) goto werr;
895             } else if (o->type == REDIS_SET) {
896                 if (rewriteSetObject(&aof,&key,o) == 0) goto werr;
897             } else if (o->type == REDIS_ZSET) {
898                 if (rewriteSortedSetObject(&aof,&key,o) == 0) goto werr;
899             } else if (o->type == REDIS_HASH) {
900                 if (rewriteHashObject(&aof,&key,o) == 0) goto werr;
901             } else {
902                 redisPanic("Unknown object type");
903             }
904             /* Save the expire time */
905             if (expiretime != -1) {
906                 char cmd[]="*3\r\n$9\r\nPEXPIREAT\r\n";
907                 /* If this key is already expired skip it */
908                 if (expiretime < now) continue;
909                 if (rioWrite(&aof,cmd,sizeof(cmd)-1) == 0) goto werr;
910                 if (rioWriteBulkObject(&aof,&key) == 0) goto werr;
911                 if (rioWriteBulkLongLong(&aof,expiretime) == 0) goto werr;
912             }
913         }
914         dictReleaseIterator(di);
915     }
916 
917     /* Make sure data will not remain on the OS's output buffers */
918     fflush(fp);
919     aof_fsync(fileno(fp));
920     fclose(fp);
921 
922     /* Use RENAME to make sure the DB file is changed atomically only
923      * if the generate DB file is ok. */
924     if (rename(tmpfile,filename) == -1) {
925         redisLog(REDIS_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno));
926         unlink(tmpfile);
927         return REDIS_ERR;
928     }
929     redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");
930     return REDIS_OK;
931 
932 werr:
933     fclose(fp);
934     unlink(tmpfile);
935     redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));
936     if (di) dictReleaseIterator(di);
937     return REDIS_ERR;
938 }
939 
940 /* This is how rewriting of the append only file in background works:
941  *
942  * 1) The user calls BGREWRITEAOF
943  * 2) Redis calls this function, that forks():
944  *    2a) the child rewrite the append only file in a temp file.
945  *    2b) the parent accumulates differences in server.aof_rewrite_buf.
946  * 3) When the child finished '2a' exists.
947  * 4) The parent will trap the exit code, if it's OK, will append the
948  *    data accumulated into server.aof_rewrite_buf into the temp file, and
949  *    finally will rename(2) the temp file in the actual file name.
950  *    The the new file is reopened as the new append only file. Profit!
951  */
952 int rewriteAppendOnlyFileBackground(void) {
953     pid_t childpid;
954     long long start;
955 
956     if (server.aof_child_pid != -1) return REDIS_ERR;
957     start = ustime();
958     if ((childpid = fork()) == 0) {
959         char tmpfile[256];
960 
961         /* Child */
962         if (server.ipfd > 0) close(server.ipfd);
963         if (server.sofd > 0) close(server.sofd);
964         snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
965         if (rewriteAppendOnlyFile(tmpfile) == REDIS_OK) {
966             size_t private_dirty = zmalloc_get_private_dirty();
967 
968             if (private_dirty) {
969                 redisLog(REDIS_NOTICE,
970                     "AOF rewrite: %lu MB of memory used by copy-on-write",
971                     private_dirty/(1024*1024));
972             }
973             exitFromChild(0);
974         } else {
975             exitFromChild(1);
976         }
977     } else {
978         /* Parent */
979         server.stat_fork_time = ustime()-start;
980         if (childpid == -1) {
981             redisLog(REDIS_WARNING,
982                 "Can't rewrite append only file in background: fork: %s",
983                 strerror(errno));
984             return REDIS_ERR;
985         }
986         redisLog(REDIS_NOTICE,
987             "Background append only file rewriting started by pid %d",childpid);
988         server.aof_rewrite_scheduled = 0;
989         server.aof_rewrite_time_start = time(NULL);
990         server.aof_child_pid = childpid;
991         updateDictResizePolicy();
992         /* We set appendseldb to -1 in order to force the next call to the
993          * feedAppendOnlyFile() to issue a SELECT command, so the differences
994          * accumulated by the parent into server.aof_rewrite_buf will start
995          * with a SELECT statement and it will be safe to merge. */
996         server.aof_selected_db = -1;
997         return REDIS_OK;
998     }
999     return REDIS_OK; /* unreached */
1000 }
1001 
1002 void bgrewriteaofCommand(redisClient *c) {
1003     if (server.aof_child_pid != -1) {
1004         addReplyError(c,"Background append only file rewriting already in progress");
1005     } else if (server.rdb_child_pid != -1) {
1006         server.aof_rewrite_scheduled = 1;
1007         addReplyStatus(c,"Background append only file rewriting scheduled");
1008     } else if (rewriteAppendOnlyFileBackground() == REDIS_OK) {
1009         addReplyStatus(c,"Background append only file rewriting started");
1010     } else {
1011         addReply(c,shared.err);
1012     }
1013 }
1014 
1015 void aofRemoveTempFile(pid_t childpid) {
1016     char tmpfile[256];
1017 
1018     snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid);
1019     unlink(tmpfile);
1020 }
1021 
1022 /* Update the server.aof_current_size filed explicitly using stat(2)
1023  * to check the size of the file. This is useful after a rewrite or after
1024  * a restart, normally the size is updated just adding the write length
1025  * to the current length, that is much faster. */
1026 void aofUpdateCurrentSize(void) {
1027     struct redis_stat sb;
1028 
1029     if (redis_fstat(server.aof_fd,&sb) == -1) {
1030         redisLog(REDIS_WARNING,"Unable to obtain the AOF file length. stat: %s",
1031             strerror(errno));
1032     } else {
1033         server.aof_current_size = sb.st_size;
1034     }
1035 }
1036 
1037 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1038  * Handle this. */
1039 void backgroundRewriteDoneHandler(int exitcode, int bysignal) {
1040     if (!bysignal && exitcode == 0) {
1041         int newfd, oldfd;
1042         char tmpfile[256];
1043         long long now = ustime();
1044 
1045         redisLog(REDIS_NOTICE,
1046             "Background AOF rewrite terminated with success");
1047 
1048         /* Flush the differences accumulated by the parent to the
1049          * rewritten AOF. */
1050         snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof",
1051             (int)server.aof_child_pid);
1052         newfd = open(tmpfile,O_WRONLY|O_APPEND);
1053         if (newfd == -1) {
1054             redisLog(REDIS_WARNING,
1055                 "Unable to open the temporary AOF produced by the child: %s", strerror(errno));
1056             goto cleanup;
1057         }
1058 
1059         if (aofRewriteBufferWrite(newfd) == -1) {
1060             redisLog(REDIS_WARNING,
1061                 "Error trying to flush the parent diff to the rewritten AOF: %s", strerror(errno));
1062             close(newfd);
1063             goto cleanup;
1064         }
1065 
1066         redisLog(REDIS_NOTICE,
1067             "Parent diff successfully flushed to the rewritten AOF (%lu bytes)", aofRewriteBufferSize());
1068 
1069         /* The only remaining thing to do is to rename the temporary file to
1070          * the configured file and switch the file descriptor used to do AOF
1071          * writes. We don't want close(2) or rename(2) calls to block the
1072          * server on old file deletion.
1073          *
1074          * There are two possible scenarios:
1075          *
1076          * 1) AOF is DISABLED and this was a one time rewrite. The temporary
1077          * file will be renamed to the configured file. When this file already
1078          * exists, it will be unlinked, which may block the server.
1079          *
1080          * 2) AOF is ENABLED and the rewritten AOF will immediately start
1081          * receiving writes. After the temporary file is renamed to the
1082          * configured file, the original AOF file descriptor will be closed.
1083          * Since this will be the last reference to that file, closing it
1084          * causes the underlying file to be unlinked, which may block the
1085          * server.
1086          *
1087          * To mitigate the blocking effect of the unlink operation (either
1088          * caused by rename(2) in scenario 1, or by close(2) in scenario 2), we
1089          * use a background thread to take care of this. First, we
1090          * make scenario 1 identical to scenario 2 by opening the target file
1091          * when it exists. The unlink operation after the rename(2) will then
1092          * be executed upon calling close(2) for its descriptor. Everything to
1093          * guarantee atomicity for this switch has already happened by then, so
1094          * we don't care what the outcome or duration of that close operation
1095          * is, as long as the file descriptor is released again. */
1096         if (server.aof_fd == -1) {
1097             /* AOF disabled */
1098 
1099              /* Don't care if this fails: oldfd will be -1 and we handle that.
1100               * One notable case of -1 return is if the old file does
1101               * not exist. */
1102              oldfd = open(server.aof_filename,O_RDONLY|O_NONBLOCK);
1103         } else {
1104             /* AOF enabled */
1105             oldfd = -1; /* We'll set this to the current AOF filedes later. */
1106         }
1107 
1108         /* Rename the temporary file. This will not unlink the target file if
1109          * it exists, because we reference it with "oldfd". */
1110         if (rename(tmpfile,server.aof_filename) == -1) {
1111             redisLog(REDIS_WARNING,
1112                 "Error trying to rename the temporary AOF file: %s", strerror(errno));
1113             close(newfd);
1114             if (oldfd != -1) close(oldfd);
1115             goto cleanup;
1116         }
1117 
1118         if (server.aof_fd == -1) {
1119             /* AOF disabled, we don't need to set the AOF file descriptor
1120              * to this new file, so we can close it. */
1121             close(newfd);
1122         } else {
1123             /* AOF enabled, replace the old fd with the new one. */
1124             oldfd = server.aof_fd;
1125             server.aof_fd = newfd;
1126             if (server.aof_fsync == AOF_FSYNC_ALWAYS)
1127                 aof_fsync(newfd);
1128             else if (server.aof_fsync == AOF_FSYNC_EVERYSEC)
1129                 aof_background_fsync(newfd);
1130             server.aof_selected_db = -1; /* Make sure SELECT is re-issued */
1131             aofUpdateCurrentSize();
1132             server.aof_rewrite_base_size = server.aof_current_size;
1133 
1134             /* Clear regular AOF buffer since its contents was just written to
1135              * the new AOF from the background rewrite buffer. */
1136             sdsfree(server.aof_buf);
1137             server.aof_buf = sdsempty();
1138         }
1139 
1140         server.aof_lastbgrewrite_status = REDIS_OK;
1141 
1142         redisLog(REDIS_NOTICE, "Background AOF rewrite finished successfully");
1143         /* Change state from WAIT_REWRITE to ON if needed */
1144         if (server.aof_state == REDIS_AOF_WAIT_REWRITE)
1145             server.aof_state = REDIS_AOF_ON;
1146 
1147         /* Asynchronously close the overwritten AOF. */
1148         if (oldfd != -1) bioCreateBackgroundJob(REDIS_BIO_CLOSE_FILE,(void*)(long)oldfd,NULL,NULL);
1149 
1150         redisLog(REDIS_VERBOSE,
1151             "Background AOF rewrite signal handler took %lldus", ustime()-now);
1152     } else if (!bysignal && exitcode != 0) {
1153         server.aof_lastbgrewrite_status = REDIS_ERR;
1154 
1155         redisLog(REDIS_WARNING,
1156             "Background AOF rewrite terminated with error");
1157     } else {
1158         server.aof_lastbgrewrite_status = REDIS_ERR;
1159 
1160         redisLog(REDIS_WARNING,
1161             "Background AOF rewrite terminated by signal %d", bysignal);
1162     }
1163 
1164 cleanup:
1165     aofRewriteBufferReset();
1166     aofRemoveTempFile(server.aof_child_pid);
1167     server.aof_child_pid = -1;
1168     server.aof_rewrite_time_last = time(NULL)-server.aof_rewrite_time_start;
1169     server.aof_rewrite_time_start = -1;
1170     /* Schedule a new rewrite if we are waiting for it to switch the AOF ON. */
1171     if (server.aof_state == REDIS_AOF_WAIT_REWRITE)
1172         server.aof_rewrite_scheduled = 1;
1173 }
1174