xref: /redis-3.2.3/src/aof.c (revision 3064e9bd)
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 void aofClosePipes(void);
44 
45 /* ----------------------------------------------------------------------------
46  * AOF rewrite buffer implementation.
47  *
48  * The following code implement a simple buffer used in order to accumulate
49  * changes while the background process is rewriting the AOF file.
50  *
51  * We only need to append, but can't just use realloc with a large block
52  * because 'huge' reallocs are not always handled as one could expect
53  * (via remapping of pages at OS level) but may involve copying data.
54  *
55  * For this reason we use a list of blocks, every block is
56  * AOF_RW_BUF_BLOCK_SIZE bytes.
57  * ------------------------------------------------------------------------- */
58 
59 #define AOF_RW_BUF_BLOCK_SIZE (1024*1024*10)    /* 10 MB per block */
60 
61 typedef struct aofrwblock {
62     unsigned long used, free;
63     char buf[AOF_RW_BUF_BLOCK_SIZE];
64 } aofrwblock;
65 
66 /* This function free the old AOF rewrite buffer if needed, and initialize
67  * a fresh new one. It tests for server.aof_rewrite_buf_blocks equal to NULL
68  * so can be used for the first initialization as well. */
69 void aofRewriteBufferReset(void) {
70     if (server.aof_rewrite_buf_blocks)
71         listRelease(server.aof_rewrite_buf_blocks);
72 
73     server.aof_rewrite_buf_blocks = listCreate();
74     listSetFreeMethod(server.aof_rewrite_buf_blocks,zfree);
75 }
76 
77 /* Return the current size of the AOF rerwite buffer. */
78 unsigned long aofRewriteBufferSize(void) {
79     listNode *ln;
80     listIter li;
81     unsigned long size = 0;
82 
83     listRewind(server.aof_rewrite_buf_blocks,&li);
84     while((ln = listNext(&li))) {
85         aofrwblock *block = listNodeValue(ln);
86         size += block->used;
87     }
88     return size;
89 }
90 
91 /* Event handler used to send data to the child process doing the AOF
92  * rewrite. We send pieces of our AOF differences buffer so that the final
93  * write when the child finishes the rewrite will be small. */
94 void aofChildWriteDiffData(aeEventLoop *el, int fd, void *privdata, int mask) {
95     listNode *ln;
96     aofrwblock *block;
97     ssize_t nwritten;
98     REDIS_NOTUSED(el);
99     REDIS_NOTUSED(fd);
100     REDIS_NOTUSED(privdata);
101     REDIS_NOTUSED(mask);
102 
103     while(1) {
104         ln = listFirst(server.aof_rewrite_buf_blocks);
105         block = ln ? ln->value : NULL;
106         if (server.aof_stop_sending_diff || !block) {
107             aeDeleteFileEvent(server.el,server.aof_pipe_write_data_to_child,
108                               AE_WRITABLE);
109             return;
110         }
111         if (block->used > 0) {
112             nwritten = write(server.aof_pipe_write_data_to_child,
113                              block->buf,block->used);
114             if (nwritten <= 0) return;
115             memmove(block->buf,block->buf+nwritten,block->used-nwritten);
116             block->used -= nwritten;
117         }
118         if (block->used == 0) listDelNode(server.aof_rewrite_buf_blocks,ln);
119     }
120 }
121 
122 /* Append data to the AOF rewrite buffer, allocating new blocks if needed. */
123 void aofRewriteBufferAppend(unsigned char *s, unsigned long len) {
124     listNode *ln = listLast(server.aof_rewrite_buf_blocks);
125     aofrwblock *block = ln ? ln->value : NULL;
126 
127     while(len) {
128         /* If we already got at least an allocated block, try appending
129          * at least some piece into it. */
130         if (block) {
131             unsigned long thislen = (block->free < len) ? block->free : len;
132             if (thislen) {  /* The current block is not already full. */
133                 memcpy(block->buf+block->used, s, thislen);
134                 block->used += thislen;
135                 block->free -= thislen;
136                 s += thislen;
137                 len -= thislen;
138             }
139         }
140 
141         if (len) { /* First block to allocate, or need another block. */
142             int numblocks;
143 
144             block = zmalloc(sizeof(*block));
145             block->free = AOF_RW_BUF_BLOCK_SIZE;
146             block->used = 0;
147             listAddNodeTail(server.aof_rewrite_buf_blocks,block);
148 
149             /* Log every time we cross more 10 or 100 blocks, respectively
150              * as a notice or warning. */
151             numblocks = listLength(server.aof_rewrite_buf_blocks);
152             if (((numblocks+1) % 10) == 0) {
153                 int level = ((numblocks+1) % 100) == 0 ? REDIS_WARNING :
154                                                          REDIS_NOTICE;
155                 redisLog(level,"Background AOF buffer size: %lu MB",
156                     aofRewriteBufferSize()/(1024*1024));
157             }
158         }
159     }
160 
161     /* Install a file event to send data to the rewrite child if there is
162      * not one already. */
163     if (aeGetFileEvents(server.el,server.aof_pipe_write_data_to_child) == 0) {
164         aeCreateFileEvent(server.el, server.aof_pipe_write_data_to_child,
165             AE_WRITABLE, aofChildWriteDiffData, NULL);
166     }
167 }
168 
169 /* Write the buffer (possibly composed of multiple blocks) into the specified
170  * fd. If a short write or any other error happens -1 is returned,
171  * otherwise the number of bytes written is returned. */
172 ssize_t aofRewriteBufferWrite(int fd) {
173     listNode *ln;
174     listIter li;
175     ssize_t count = 0;
176 
177     listRewind(server.aof_rewrite_buf_blocks,&li);
178     while((ln = listNext(&li))) {
179         aofrwblock *block = listNodeValue(ln);
180         ssize_t nwritten;
181 
182         if (block->used) {
183             nwritten = write(fd,block->buf,block->used);
184             if (nwritten != (ssize_t)block->used) {
185                 if (nwritten == 0) errno = EIO;
186                 return -1;
187             }
188             count += nwritten;
189         }
190     }
191     return count;
192 }
193 
194 /* ----------------------------------------------------------------------------
195  * AOF file implementation
196  * ------------------------------------------------------------------------- */
197 
198 /* Starts a background task that performs fsync() against the specified
199  * file descriptor (the one of the AOF file) in another thread. */
200 void aof_background_fsync(int fd) {
201     bioCreateBackgroundJob(REDIS_BIO_AOF_FSYNC,(void*)(long)fd,NULL,NULL);
202 }
203 
204 /* Called when the user switches from "appendonly yes" to "appendonly no"
205  * at runtime using the CONFIG command. */
206 void stopAppendOnly(void) {
207     redisAssert(server.aof_state != REDIS_AOF_OFF);
208     flushAppendOnlyFile(1);
209     aof_fsync(server.aof_fd);
210     close(server.aof_fd);
211 
212     server.aof_fd = -1;
213     server.aof_selected_db = -1;
214     server.aof_state = REDIS_AOF_OFF;
215     /* rewrite operation in progress? kill it, wait child exit */
216     if (server.aof_child_pid != -1) {
217         int statloc;
218 
219         redisLog(REDIS_NOTICE,"Killing running AOF rewrite child: %ld",
220             (long) server.aof_child_pid);
221         if (kill(server.aof_child_pid,SIGUSR1) != -1)
222             wait3(&statloc,0,NULL);
223         /* reset the buffer accumulating changes while the child saves */
224         aofRewriteBufferReset();
225         aofRemoveTempFile(server.aof_child_pid);
226         server.aof_child_pid = -1;
227         server.aof_rewrite_time_start = -1;
228         /* close pipes used for IPC between the two processes. */
229         aofClosePipes();
230     }
231 }
232 
233 /* Called when the user switches from "appendonly no" to "appendonly yes"
234  * at runtime using the CONFIG command. */
235 int startAppendOnly(void) {
236     server.aof_last_fsync = server.unixtime;
237     server.aof_fd = open(server.aof_filename,O_WRONLY|O_APPEND|O_CREAT,0644);
238     redisAssert(server.aof_state == REDIS_AOF_OFF);
239     if (server.aof_fd == -1) {
240         redisLog(REDIS_WARNING,"Redis needs to enable the AOF but can't open the append only file: %s",strerror(errno));
241         return REDIS_ERR;
242     }
243     if (rewriteAppendOnlyFileBackground() == REDIS_ERR) {
244         close(server.aof_fd);
245         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.");
246         return REDIS_ERR;
247     }
248     /* We correctly switched on AOF, now wait for the rerwite to be complete
249      * in order to append data on disk. */
250     server.aof_state = REDIS_AOF_WAIT_REWRITE;
251     return REDIS_OK;
252 }
253 
254 /* Write the append only file buffer on disk.
255  *
256  * Since we are required to write the AOF before replying to the client,
257  * and the only way the client socket can get a write is entering when the
258  * the event loop, we accumulate all the AOF writes in a memory
259  * buffer and write it on disk using this function just before entering
260  * the event loop again.
261  *
262  * About the 'force' argument:
263  *
264  * When the fsync policy is set to 'everysec' we may delay the flush if there
265  * is still an fsync() going on in the background thread, since for instance
266  * on Linux write(2) will be blocked by the background fsync anyway.
267  * When this happens we remember that there is some aof buffer to be
268  * flushed ASAP, and will try to do that in the serverCron() function.
269  *
270  * However if force is set to 1 we'll write regardless of the background
271  * fsync. */
272 #define AOF_WRITE_LOG_ERROR_RATE 30 /* Seconds between errors logging. */
273 void flushAppendOnlyFile(int force) {
274     ssize_t nwritten;
275     int sync_in_progress = 0;
276     mstime_t latency;
277 
278     if (sdslen(server.aof_buf) == 0) return;
279 
280     if (server.aof_fsync == AOF_FSYNC_EVERYSEC)
281         sync_in_progress = bioPendingJobsOfType(REDIS_BIO_AOF_FSYNC) != 0;
282 
283     if (server.aof_fsync == AOF_FSYNC_EVERYSEC && !force) {
284         /* With this append fsync policy we do background fsyncing.
285          * If the fsync is still in progress we can try to delay
286          * the write for a couple of seconds. */
287         if (sync_in_progress) {
288             if (server.aof_flush_postponed_start == 0) {
289                 /* No previous write postponinig, remember that we are
290                  * postponing the flush and return. */
291                 server.aof_flush_postponed_start = server.unixtime;
292                 return;
293             } else if (server.unixtime - server.aof_flush_postponed_start < 2) {
294                 /* We were already waiting for fsync to finish, but for less
295                  * than two seconds this is still ok. Postpone again. */
296                 return;
297             }
298             /* Otherwise fall trough, and go write since we can't wait
299              * over two seconds. */
300             server.aof_delayed_fsync++;
301             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.");
302         }
303     }
304     /* We want to perform a single write. This should be guaranteed atomic
305      * at least if the filesystem we are writing is a real physical one.
306      * While this will save us against the server being killed I don't think
307      * there is much to do about the whole server stopping for power problems
308      * or alike */
309 
310     latencyStartMonitor(latency);
311     nwritten = write(server.aof_fd,server.aof_buf,sdslen(server.aof_buf));
312     latencyEndMonitor(latency);
313     /* We want to capture different events for delayed writes:
314      * when the delay happens with a pending fsync, or with a saving child
315      * active, and when the above two conditions are missing.
316      * We also use an additional event name to save all samples which is
317      * useful for graphing / monitoring purposes. */
318     if (sync_in_progress) {
319         latencyAddSampleIfNeeded("aof-write-pending-fsync",latency);
320     } else if (server.aof_child_pid != -1 || server.rdb_child_pid != -1) {
321         latencyAddSampleIfNeeded("aof-write-active-child",latency);
322     } else {
323         latencyAddSampleIfNeeded("aof-write-alone",latency);
324     }
325     latencyAddSampleIfNeeded("aof-write",latency);
326 
327     /* We performed the write so reset the postponed flush sentinel to zero. */
328     server.aof_flush_postponed_start = 0;
329 
330     if (nwritten != (signed)sdslen(server.aof_buf)) {
331         static time_t last_write_error_log = 0;
332         int can_log = 0;
333 
334         /* Limit logging rate to 1 line per AOF_WRITE_LOG_ERROR_RATE seconds. */
335         if ((server.unixtime - last_write_error_log) > AOF_WRITE_LOG_ERROR_RATE) {
336             can_log = 1;
337             last_write_error_log = server.unixtime;
338         }
339 
340         /* Lof the AOF write error and record the error code. */
341         if (nwritten == -1) {
342             if (can_log) {
343                 redisLog(REDIS_WARNING,"Error writing to the AOF file: %s",
344                     strerror(errno));
345                 server.aof_last_write_errno = errno;
346             }
347         } else {
348             if (can_log) {
349                 redisLog(REDIS_WARNING,"Short write while writing to "
350                                        "the AOF file: (nwritten=%lld, "
351                                        "expected=%lld)",
352                                        (long long)nwritten,
353                                        (long long)sdslen(server.aof_buf));
354             }
355 
356             if (ftruncate(server.aof_fd, server.aof_current_size) == -1) {
357                 if (can_log) {
358                     redisLog(REDIS_WARNING, "Could not remove short write "
359                              "from the append-only file.  Redis may refuse "
360                              "to load the AOF the next time it starts.  "
361                              "ftruncate: %s", strerror(errno));
362                 }
363             } else {
364                 /* If the ftrunacate() succeeded we can set nwritten to
365                  * -1 since there is no longer partial data into the AOF. */
366                 nwritten = -1;
367             }
368             server.aof_last_write_errno = ENOSPC;
369         }
370 
371         /* Handle the AOF write error. */
372         if (server.aof_fsync == AOF_FSYNC_ALWAYS) {
373             /* We can't recover when the fsync policy is ALWAYS since the
374              * reply for the client is already in the output buffers, and we
375              * have the contract with the user that on acknowledged write data
376              * is synched on disk. */
377             redisLog(REDIS_WARNING,"Can't recover from AOF write error when the AOF fsync policy is 'always'. Exiting...");
378             exit(1);
379         } else {
380             /* Recover from failed write leaving data into the buffer. However
381              * set an error to stop accepting writes as long as the error
382              * condition is not cleared. */
383             server.aof_last_write_status = REDIS_ERR;
384 
385             /* Trim the sds buffer if there was a partial write, and there
386              * was no way to undo it with ftruncate(2). */
387             if (nwritten > 0) {
388                 server.aof_current_size += nwritten;
389                 sdsrange(server.aof_buf,nwritten,-1);
390             }
391             return; /* We'll try again on the next call... */
392         }
393     } else {
394         /* Successful write(2). If AOF was in error state, restore the
395          * OK state and log the event. */
396         if (server.aof_last_write_status == REDIS_ERR) {
397             redisLog(REDIS_WARNING,
398                 "AOF write error looks solved, Redis can write again.");
399             server.aof_last_write_status = REDIS_OK;
400         }
401     }
402     server.aof_current_size += nwritten;
403 
404     /* Re-use AOF buffer when it is small enough. The maximum comes from the
405      * arena size of 4k minus some overhead (but is otherwise arbitrary). */
406     if ((sdslen(server.aof_buf)+sdsavail(server.aof_buf)) < 4000) {
407         sdsclear(server.aof_buf);
408     } else {
409         sdsfree(server.aof_buf);
410         server.aof_buf = sdsempty();
411     }
412 
413     /* Don't fsync if no-appendfsync-on-rewrite is set to yes and there are
414      * children doing I/O in the background. */
415     if (server.aof_no_fsync_on_rewrite &&
416         (server.aof_child_pid != -1 || server.rdb_child_pid != -1))
417             return;
418 
419     /* Perform the fsync if needed. */
420     if (server.aof_fsync == AOF_FSYNC_ALWAYS) {
421         /* aof_fsync is defined as fdatasync() for Linux in order to avoid
422          * flushing metadata. */
423         latencyStartMonitor(latency);
424         aof_fsync(server.aof_fd); /* Let's try to get this data on the disk */
425         latencyEndMonitor(latency);
426         latencyAddSampleIfNeeded("aof-fsync-always",latency);
427         server.aof_last_fsync = server.unixtime;
428     } else if ((server.aof_fsync == AOF_FSYNC_EVERYSEC &&
429                 server.unixtime > server.aof_last_fsync)) {
430         if (!sync_in_progress) aof_background_fsync(server.aof_fd);
431         server.aof_last_fsync = server.unixtime;
432     }
433 }
434 
435 sds catAppendOnlyGenericCommand(sds dst, int argc, robj **argv) {
436     char buf[32];
437     int len, j;
438     robj *o;
439 
440     buf[0] = '*';
441     len = 1+ll2string(buf+1,sizeof(buf)-1,argc);
442     buf[len++] = '\r';
443     buf[len++] = '\n';
444     dst = sdscatlen(dst,buf,len);
445 
446     for (j = 0; j < argc; j++) {
447         o = getDecodedObject(argv[j]);
448         buf[0] = '$';
449         len = 1+ll2string(buf+1,sizeof(buf)-1,sdslen(o->ptr));
450         buf[len++] = '\r';
451         buf[len++] = '\n';
452         dst = sdscatlen(dst,buf,len);
453         dst = sdscatlen(dst,o->ptr,sdslen(o->ptr));
454         dst = sdscatlen(dst,"\r\n",2);
455         decrRefCount(o);
456     }
457     return dst;
458 }
459 
460 /* Create the sds representation of an PEXPIREAT command, using
461  * 'seconds' as time to live and 'cmd' to understand what command
462  * we are translating into a PEXPIREAT.
463  *
464  * This command is used in order to translate EXPIRE and PEXPIRE commands
465  * into PEXPIREAT command so that we retain precision in the append only
466  * file, and the time is always absolute and not relative. */
467 sds catAppendOnlyExpireAtCommand(sds buf, struct redisCommand *cmd, robj *key, robj *seconds) {
468     long long when;
469     robj *argv[3];
470 
471     /* Make sure we can use strtol */
472     seconds = getDecodedObject(seconds);
473     when = strtoll(seconds->ptr,NULL,10);
474     /* Convert argument into milliseconds for EXPIRE, SETEX, EXPIREAT */
475     if (cmd->proc == expireCommand || cmd->proc == setexCommand ||
476         cmd->proc == expireatCommand)
477     {
478         when *= 1000;
479     }
480     /* Convert into absolute time for EXPIRE, PEXPIRE, SETEX, PSETEX */
481     if (cmd->proc == expireCommand || cmd->proc == pexpireCommand ||
482         cmd->proc == setexCommand || cmd->proc == psetexCommand)
483     {
484         when += mstime();
485     }
486     decrRefCount(seconds);
487 
488     argv[0] = createStringObject("PEXPIREAT",9);
489     argv[1] = key;
490     argv[2] = createStringObjectFromLongLong(when);
491     buf = catAppendOnlyGenericCommand(buf, 3, argv);
492     decrRefCount(argv[0]);
493     decrRefCount(argv[2]);
494     return buf;
495 }
496 
497 void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) {
498     sds buf = sdsempty();
499     robj *tmpargv[3];
500 
501     /* The DB this command was targeting is not the same as the last command
502      * we appendend. To issue a SELECT command is needed. */
503     if (dictid != server.aof_selected_db) {
504         char seldb[64];
505 
506         snprintf(seldb,sizeof(seldb),"%d",dictid);
507         buf = sdscatprintf(buf,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
508             (unsigned long)strlen(seldb),seldb);
509         server.aof_selected_db = dictid;
510     }
511 
512     if (cmd->proc == expireCommand || cmd->proc == pexpireCommand ||
513         cmd->proc == expireatCommand) {
514         /* Translate EXPIRE/PEXPIRE/EXPIREAT into PEXPIREAT */
515         buf = catAppendOnlyExpireAtCommand(buf,cmd,argv[1],argv[2]);
516     } else if (cmd->proc == setexCommand || cmd->proc == psetexCommand) {
517         /* Translate SETEX/PSETEX to SET and PEXPIREAT */
518         tmpargv[0] = createStringObject("SET",3);
519         tmpargv[1] = argv[1];
520         tmpargv[2] = argv[3];
521         buf = catAppendOnlyGenericCommand(buf,3,tmpargv);
522         decrRefCount(tmpargv[0]);
523         buf = catAppendOnlyExpireAtCommand(buf,cmd,argv[1],argv[2]);
524     } else {
525         /* All the other commands don't need translation or need the
526          * same translation already operated in the command vector
527          * for the replication itself. */
528         buf = catAppendOnlyGenericCommand(buf,argc,argv);
529     }
530 
531     /* Append to the AOF buffer. This will be flushed on disk just before
532      * of re-entering the event loop, so before the client will get a
533      * positive reply about the operation performed. */
534     if (server.aof_state == REDIS_AOF_ON)
535         server.aof_buf = sdscatlen(server.aof_buf,buf,sdslen(buf));
536 
537     /* If a background append only file rewriting is in progress we want to
538      * accumulate the differences between the child DB and the current one
539      * in a buffer, so that when the child process will do its work we
540      * can append the differences to the new append only file. */
541     if (server.aof_child_pid != -1)
542         aofRewriteBufferAppend((unsigned char*)buf,sdslen(buf));
543 
544     sdsfree(buf);
545 }
546 
547 /* ----------------------------------------------------------------------------
548  * AOF loading
549  * ------------------------------------------------------------------------- */
550 
551 /* In Redis commands are always executed in the context of a client, so in
552  * order to load the append only file we need to create a fake client. */
553 struct redisClient *createFakeClient(void) {
554     struct redisClient *c = zmalloc(sizeof(*c));
555 
556     selectDb(c,0);
557     c->fd = -1;
558     c->name = NULL;
559     c->querybuf = sdsempty();
560     c->querybuf_peak = 0;
561     c->argc = 0;
562     c->argv = NULL;
563     c->bufpos = 0;
564     c->flags = 0;
565     c->btype = REDIS_BLOCKED_NONE;
566     /* We set the fake client as a slave waiting for the synchronization
567      * so that Redis will not try to send replies to this client. */
568     c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
569     c->reply = listCreate();
570     c->reply_bytes = 0;
571     c->obuf_soft_limit_reached_time = 0;
572     c->watched_keys = listCreate();
573     c->peerid = NULL;
574     listSetFreeMethod(c->reply,decrRefCountVoid);
575     listSetDupMethod(c->reply,dupClientReplyValue);
576     initClientMultiState(c);
577     return c;
578 }
579 
580 void freeFakeClientArgv(struct redisClient *c) {
581     int j;
582 
583     for (j = 0; j < c->argc; j++)
584         decrRefCount(c->argv[j]);
585     zfree(c->argv);
586 }
587 
588 void freeFakeClient(struct redisClient *c) {
589     sdsfree(c->querybuf);
590     listRelease(c->reply);
591     listRelease(c->watched_keys);
592     freeClientMultiState(c);
593     zfree(c);
594 }
595 
596 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
597  * error (the append only file is zero-length) REDIS_ERR is returned. On
598  * fatal error an error message is logged and the program exists. */
599 int loadAppendOnlyFile(char *filename) {
600     struct redisClient *fakeClient;
601     FILE *fp = fopen(filename,"r");
602     struct redis_stat sb;
603     int old_aof_state = server.aof_state;
604     long loops = 0;
605 
606     if (fp && redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0) {
607         server.aof_current_size = 0;
608         fclose(fp);
609         return REDIS_ERR;
610     }
611 
612     if (fp == NULL) {
613         redisLog(REDIS_WARNING,"Fatal error: can't open the append log file for reading: %s",strerror(errno));
614         exit(1);
615     }
616 
617     /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
618      * to the same file we're about to read. */
619     server.aof_state = REDIS_AOF_OFF;
620 
621     fakeClient = createFakeClient();
622     startLoading(fp);
623 
624     while(1) {
625         int argc, j;
626         unsigned long len;
627         robj **argv;
628         char buf[128];
629         sds argsds;
630         struct redisCommand *cmd;
631 
632         /* Serve the clients from time to time */
633         if (!(loops++ % 1000)) {
634             loadingProgress(ftello(fp));
635             processEventsWhileBlocked();
636         }
637 
638         if (fgets(buf,sizeof(buf),fp) == NULL) {
639             if (feof(fp))
640                 break;
641             else
642                 goto readerr;
643         }
644         if (buf[0] != '*') goto fmterr;
645         if (buf[1] == '\0') goto readerr;
646         argc = atoi(buf+1);
647         if (argc < 1) goto fmterr;
648 
649         argv = zmalloc(sizeof(robj*)*argc);
650         fakeClient->argc = argc;
651         fakeClient->argv = argv;
652 
653         for (j = 0; j < argc; j++) {
654             if (fgets(buf,sizeof(buf),fp) == NULL) {
655                 fakeClient->argc = j; /* Free up to j-1. */
656                 freeFakeClientArgv(fakeClient);
657                 goto readerr;
658             }
659             if (buf[0] != '$') goto fmterr;
660             len = strtol(buf+1,NULL,10);
661             argsds = sdsnewlen(NULL,len);
662             if (len && fread(argsds,len,1,fp) == 0) {
663                 sdsfree(argsds);
664                 fakeClient->argc = j; /* Free up to j-1. */
665                 freeFakeClientArgv(fakeClient);
666                 goto readerr;
667             }
668             argv[j] = createObject(REDIS_STRING,argsds);
669             if (fread(buf,2,1,fp) == 0) {
670                 fakeClient->argc = j+1; /* Free up to j. */
671                 freeFakeClientArgv(fakeClient);
672                 goto readerr; /* discard CRLF */
673             }
674         }
675 
676         /* Command lookup */
677         cmd = lookupCommand(argv[0]->ptr);
678         if (!cmd) {
679             redisLog(REDIS_WARNING,"Unknown command '%s' reading the append only file", (char*)argv[0]->ptr);
680             exit(1);
681         }
682 
683         /* Run the command in the context of a fake client */
684         cmd->proc(fakeClient);
685 
686         /* The fake client should not have a reply */
687         redisAssert(fakeClient->bufpos == 0 && listLength(fakeClient->reply) == 0);
688         /* The fake client should never get blocked */
689         redisAssert((fakeClient->flags & REDIS_BLOCKED) == 0);
690 
691         /* Clean up. Command code may have changed argv/argc so we use the
692          * argv/argc of the client instead of the local variables. */
693         freeFakeClientArgv(fakeClient);
694     }
695 
696     /* This point can only be reached when EOF is reached without errors.
697      * If the client is in the middle of a MULTI/EXEC, log error and quit. */
698     if (fakeClient->flags & REDIS_MULTI) goto uxeof;
699 
700 loaded_ok: /* DB loaded, cleanup and return REDIS_OK to the caller. */
701     fclose(fp);
702     freeFakeClient(fakeClient);
703     server.aof_state = old_aof_state;
704     stopLoading();
705     aofUpdateCurrentSize();
706     server.aof_rewrite_base_size = server.aof_current_size;
707     return REDIS_OK;
708 
709 readerr: /* Read error. If feof(fp) is true, fall through to unexpected EOF. */
710     if (!feof(fp)) {
711         redisLog(REDIS_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno));
712         exit(1);
713     }
714 
715 uxeof: /* Unexpected AOF end of file. */
716     if (server.aof_load_truncated) {
717         redisLog(REDIS_WARNING,"!!! Warning: short read while loading the AOF file !!!");
718         redisLog(REDIS_WARNING,
719             "AOF loaded anyway because aof-load-truncated is enabled");
720         goto loaded_ok;
721     }
722     redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file. You can: 1) Make a backup of your AOF file, then use ./redis-check-aof --fix <filename>. 2) Alternatively you can set the 'aof-load-truncated' configuration option to yes and restart the server.");
723     exit(1);
724 
725 fmterr: /* Format error. */
726     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>");
727     exit(1);
728 }
729 
730 /* ----------------------------------------------------------------------------
731  * AOF rewrite
732  * ------------------------------------------------------------------------- */
733 
734 /* Delegate writing an object to writing a bulk string or bulk long long.
735  * This is not placed in rio.c since that adds the redis.h dependency. */
736 int rioWriteBulkObject(rio *r, robj *obj) {
737     /* Avoid using getDecodedObject to help copy-on-write (we are often
738      * in a child process when this function is called). */
739     if (obj->encoding == REDIS_ENCODING_INT) {
740         return rioWriteBulkLongLong(r,(long)obj->ptr);
741     } else if (sdsEncodedObject(obj)) {
742         return rioWriteBulkString(r,obj->ptr,sdslen(obj->ptr));
743     } else {
744         redisPanic("Unknown string encoding");
745     }
746 }
747 
748 /* Emit the commands needed to rebuild a list object.
749  * The function returns 0 on error, 1 on success. */
750 int rewriteListObject(rio *r, robj *key, robj *o) {
751     long long count = 0, items = listTypeLength(o);
752 
753     if (o->encoding == REDIS_ENCODING_ZIPLIST) {
754         unsigned char *zl = o->ptr;
755         unsigned char *p = ziplistIndex(zl,0);
756         unsigned char *vstr;
757         unsigned int vlen;
758         long long vlong;
759 
760         while(ziplistGet(p,&vstr,&vlen,&vlong)) {
761             if (count == 0) {
762                 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
763                     REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
764 
765                 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
766                 if (rioWriteBulkString(r,"RPUSH",5) == 0) return 0;
767                 if (rioWriteBulkObject(r,key) == 0) return 0;
768             }
769             if (vstr) {
770                 if (rioWriteBulkString(r,(char*)vstr,vlen) == 0) return 0;
771             } else {
772                 if (rioWriteBulkLongLong(r,vlong) == 0) return 0;
773             }
774             p = ziplistNext(zl,p);
775             if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
776             items--;
777         }
778     } else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
779         list *list = o->ptr;
780         listNode *ln;
781         listIter li;
782 
783         listRewind(list,&li);
784         while((ln = listNext(&li))) {
785             robj *eleobj = listNodeValue(ln);
786 
787             if (count == 0) {
788                 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
789                     REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
790 
791                 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
792                 if (rioWriteBulkString(r,"RPUSH",5) == 0) return 0;
793                 if (rioWriteBulkObject(r,key) == 0) return 0;
794             }
795             if (rioWriteBulkObject(r,eleobj) == 0) return 0;
796             if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
797             items--;
798         }
799     } else {
800         redisPanic("Unknown list encoding");
801     }
802     return 1;
803 }
804 
805 /* Emit the commands needed to rebuild a set object.
806  * The function returns 0 on error, 1 on success. */
807 int rewriteSetObject(rio *r, robj *key, robj *o) {
808     long long count = 0, items = setTypeSize(o);
809 
810     if (o->encoding == REDIS_ENCODING_INTSET) {
811         int ii = 0;
812         int64_t llval;
813 
814         while(intsetGet(o->ptr,ii++,&llval)) {
815             if (count == 0) {
816                 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
817                     REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
818 
819                 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
820                 if (rioWriteBulkString(r,"SADD",4) == 0) return 0;
821                 if (rioWriteBulkObject(r,key) == 0) return 0;
822             }
823             if (rioWriteBulkLongLong(r,llval) == 0) return 0;
824             if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
825             items--;
826         }
827     } else if (o->encoding == REDIS_ENCODING_HT) {
828         dictIterator *di = dictGetIterator(o->ptr);
829         dictEntry *de;
830 
831         while((de = dictNext(di)) != NULL) {
832             robj *eleobj = dictGetKey(de);
833             if (count == 0) {
834                 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
835                     REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
836 
837                 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
838                 if (rioWriteBulkString(r,"SADD",4) == 0) return 0;
839                 if (rioWriteBulkObject(r,key) == 0) return 0;
840             }
841             if (rioWriteBulkObject(r,eleobj) == 0) return 0;
842             if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
843             items--;
844         }
845         dictReleaseIterator(di);
846     } else {
847         redisPanic("Unknown set encoding");
848     }
849     return 1;
850 }
851 
852 /* Emit the commands needed to rebuild a sorted set object.
853  * The function returns 0 on error, 1 on success. */
854 int rewriteSortedSetObject(rio *r, robj *key, robj *o) {
855     long long count = 0, items = zsetLength(o);
856 
857     if (o->encoding == REDIS_ENCODING_ZIPLIST) {
858         unsigned char *zl = o->ptr;
859         unsigned char *eptr, *sptr;
860         unsigned char *vstr;
861         unsigned int vlen;
862         long long vll;
863         double score;
864 
865         eptr = ziplistIndex(zl,0);
866         redisAssert(eptr != NULL);
867         sptr = ziplistNext(zl,eptr);
868         redisAssert(sptr != NULL);
869 
870         while (eptr != NULL) {
871             redisAssert(ziplistGet(eptr,&vstr,&vlen,&vll));
872             score = zzlGetScore(sptr);
873 
874             if (count == 0) {
875                 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
876                     REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
877 
878                 if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0;
879                 if (rioWriteBulkString(r,"ZADD",4) == 0) return 0;
880                 if (rioWriteBulkObject(r,key) == 0) return 0;
881             }
882             if (rioWriteBulkDouble(r,score) == 0) return 0;
883             if (vstr != NULL) {
884                 if (rioWriteBulkString(r,(char*)vstr,vlen) == 0) return 0;
885             } else {
886                 if (rioWriteBulkLongLong(r,vll) == 0) return 0;
887             }
888             zzlNext(zl,&eptr,&sptr);
889             if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
890             items--;
891         }
892     } else if (o->encoding == REDIS_ENCODING_SKIPLIST) {
893         zset *zs = o->ptr;
894         dictIterator *di = dictGetIterator(zs->dict);
895         dictEntry *de;
896 
897         while((de = dictNext(di)) != NULL) {
898             robj *eleobj = dictGetKey(de);
899             double *score = dictGetVal(de);
900 
901             if (count == 0) {
902                 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
903                     REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
904 
905                 if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0;
906                 if (rioWriteBulkString(r,"ZADD",4) == 0) return 0;
907                 if (rioWriteBulkObject(r,key) == 0) return 0;
908             }
909             if (rioWriteBulkDouble(r,*score) == 0) return 0;
910             if (rioWriteBulkObject(r,eleobj) == 0) return 0;
911             if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
912             items--;
913         }
914         dictReleaseIterator(di);
915     } else {
916         redisPanic("Unknown sorted zset encoding");
917     }
918     return 1;
919 }
920 
921 /* Write either the key or the value of the currently selected item of a hash.
922  * The 'hi' argument passes a valid Redis hash iterator.
923  * The 'what' filed specifies if to write a key or a value and can be
924  * either REDIS_HASH_KEY or REDIS_HASH_VALUE.
925  *
926  * The function returns 0 on error, non-zero on success. */
927 static int rioWriteHashIteratorCursor(rio *r, hashTypeIterator *hi, int what) {
928     if (hi->encoding == REDIS_ENCODING_ZIPLIST) {
929         unsigned char *vstr = NULL;
930         unsigned int vlen = UINT_MAX;
931         long long vll = LLONG_MAX;
932 
933         hashTypeCurrentFromZiplist(hi, what, &vstr, &vlen, &vll);
934         if (vstr) {
935             return rioWriteBulkString(r, (char*)vstr, vlen);
936         } else {
937             return rioWriteBulkLongLong(r, vll);
938         }
939 
940     } else if (hi->encoding == REDIS_ENCODING_HT) {
941         robj *value;
942 
943         hashTypeCurrentFromHashTable(hi, what, &value);
944         return rioWriteBulkObject(r, value);
945     }
946 
947     redisPanic("Unknown hash encoding");
948     return 0;
949 }
950 
951 /* Emit the commands needed to rebuild a hash object.
952  * The function returns 0 on error, 1 on success. */
953 int rewriteHashObject(rio *r, robj *key, robj *o) {
954     hashTypeIterator *hi;
955     long long count = 0, items = hashTypeLength(o);
956 
957     hi = hashTypeInitIterator(o);
958     while (hashTypeNext(hi) != REDIS_ERR) {
959         if (count == 0) {
960             int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
961                 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
962 
963             if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0;
964             if (rioWriteBulkString(r,"HMSET",5) == 0) return 0;
965             if (rioWriteBulkObject(r,key) == 0) return 0;
966         }
967 
968         if (rioWriteHashIteratorCursor(r, hi, REDIS_HASH_KEY) == 0) return 0;
969         if (rioWriteHashIteratorCursor(r, hi, REDIS_HASH_VALUE) == 0) return 0;
970         if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
971         items--;
972     }
973 
974     hashTypeReleaseIterator(hi);
975 
976     return 1;
977 }
978 
979 /* This function is called by the child rewriting the AOF file to read
980  * the difference accumulated from the parent into a buffer, that is
981  * concatenated at the end of the rewrite. */
982 ssize_t aofReadDiffFromParent(void) {
983     char buf[65536]; /* Default pipe buffer size on most Linux sytems. */
984     ssize_t nread, total = 0;
985 
986     while ((nread =
987             read(server.aof_pipe_read_data_from_parent,buf,sizeof(buf))) > 0) {
988         server.aof_child_diff = sdscatlen(server.aof_child_diff,buf,nread);
989         total += nread;
990     }
991     return total;
992 }
993 
994 /* Write a sequence of commands able to fully rebuild the dataset into
995  * "filename". Used both by REWRITEAOF and BGREWRITEAOF.
996  *
997  * In order to minimize the number of commands needed in the rewritten
998  * log Redis uses variadic commands when possible, such as RPUSH, SADD
999  * and ZADD. However at max REDIS_AOF_REWRITE_ITEMS_PER_CMD items per time
1000  * are inserted using a single command. */
1001 int rewriteAppendOnlyFile(char *filename) {
1002     dictIterator *di = NULL;
1003     dictEntry *de;
1004     rio aof;
1005     FILE *fp;
1006     char tmpfile[256];
1007     int j;
1008     long long now = mstime();
1009     char byte;
1010     size_t processed = 0;
1011 
1012     /* Note that we have to use a different temp name here compared to the
1013      * one used by rewriteAppendOnlyFileBackground() function. */
1014     snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
1015     fp = fopen(tmpfile,"w");
1016     if (!fp) {
1017         redisLog(REDIS_WARNING, "Opening the temp file for AOF rewrite in rewriteAppendOnlyFile(): %s", strerror(errno));
1018         return REDIS_ERR;
1019     }
1020 
1021     server.aof_child_diff = sdsempty();
1022     rioInitWithFile(&aof,fp);
1023     if (server.aof_rewrite_incremental_fsync)
1024         rioSetAutoSync(&aof,REDIS_AOF_AUTOSYNC_BYTES);
1025     for (j = 0; j < server.dbnum; j++) {
1026         char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
1027         redisDb *db = server.db+j;
1028         dict *d = db->dict;
1029         if (dictSize(d) == 0) continue;
1030         di = dictGetSafeIterator(d);
1031         if (!di) {
1032             fclose(fp);
1033             return REDIS_ERR;
1034         }
1035 
1036         /* SELECT the new DB */
1037         if (rioWrite(&aof,selectcmd,sizeof(selectcmd)-1) == 0) goto werr;
1038         if (rioWriteBulkLongLong(&aof,j) == 0) goto werr;
1039 
1040         /* Iterate this DB writing every entry */
1041         while((de = dictNext(di)) != NULL) {
1042             sds keystr;
1043             robj key, *o;
1044             long long expiretime;
1045 
1046             keystr = dictGetKey(de);
1047             o = dictGetVal(de);
1048             initStaticStringObject(key,keystr);
1049 
1050             expiretime = getExpire(db,&key);
1051 
1052             /* If this key is already expired skip it */
1053             if (expiretime != -1 && expiretime < now) continue;
1054 
1055             /* Save the key and associated value */
1056             if (o->type == REDIS_STRING) {
1057                 /* Emit a SET command */
1058                 char cmd[]="*3\r\n$3\r\nSET\r\n";
1059                 if (rioWrite(&aof,cmd,sizeof(cmd)-1) == 0) goto werr;
1060                 /* Key and value */
1061                 if (rioWriteBulkObject(&aof,&key) == 0) goto werr;
1062                 if (rioWriteBulkObject(&aof,o) == 0) goto werr;
1063             } else if (o->type == REDIS_LIST) {
1064                 if (rewriteListObject(&aof,&key,o) == 0) goto werr;
1065             } else if (o->type == REDIS_SET) {
1066                 if (rewriteSetObject(&aof,&key,o) == 0) goto werr;
1067             } else if (o->type == REDIS_ZSET) {
1068                 if (rewriteSortedSetObject(&aof,&key,o) == 0) goto werr;
1069             } else if (o->type == REDIS_HASH) {
1070                 if (rewriteHashObject(&aof,&key,o) == 0) goto werr;
1071             } else {
1072                 redisPanic("Unknown object type");
1073             }
1074             /* Save the expire time */
1075             if (expiretime != -1) {
1076                 char cmd[]="*3\r\n$9\r\nPEXPIREAT\r\n";
1077                 if (rioWrite(&aof,cmd,sizeof(cmd)-1) == 0) goto werr;
1078                 if (rioWriteBulkObject(&aof,&key) == 0) goto werr;
1079                 if (rioWriteBulkLongLong(&aof,expiretime) == 0) goto werr;
1080             }
1081             /* Read some diff from the parent process from time to time. */
1082             if (aof.processed_bytes > processed+1024*10) {
1083                 processed = aof.processed_bytes;
1084                 aofReadDiffFromParent();
1085             }
1086         }
1087         dictReleaseIterator(di);
1088     }
1089 
1090     /* Do an initial slow fsync here while the parent is still sending
1091      * data, in order to make the next final fsync faster. */
1092     if (fflush(fp) == EOF) goto werr;
1093     if (fsync(fileno(fp)) == -1) goto werr;
1094 
1095     /* Read again a few times to get more data from the parent.
1096      * We can't read forever (the server may receive data from clients
1097      * fater than it is able to send data to the child), so we try to read
1098      * some more data in a loop as soon as there is a good chance more data
1099      * will come. If it looks like we are wasting time, we abort (this
1100      * happens after 20 ms without new data). */
1101     int nodata = 0;
1102     mstime_t start = mstime();
1103     while(mstime()-start < 1000 && nodata < 20) {
1104         if (aeWait(server.aof_pipe_read_data_from_parent, AE_READABLE, 1) <= 0)
1105         {
1106             nodata++;
1107             continue;
1108         }
1109         nodata = 0; /* Start counting from zero, we stop on N *contiguous*
1110                        timeouts. */
1111         aofReadDiffFromParent();
1112     }
1113 
1114     /* Ask the master to stop sending diffs. */
1115     if (write(server.aof_pipe_write_ack_to_parent,"!",1) != 1) goto werr;
1116     if (anetNonBlock(NULL,server.aof_pipe_read_ack_from_parent) != ANET_OK)
1117         goto werr;
1118     /* We read the ACK from the server using a 10 seconds timeout. Normally
1119      * it should reply ASAP, but just in case we lose its reply, we are sure
1120      * the child will eventually get terminated. */
1121     if (syncRead(server.aof_pipe_read_ack_from_parent,&byte,1,5000) != 1 ||
1122         byte != '!') goto werr;
1123     redisLog(REDIS_NOTICE,"Parent agreed to stop sending diffs. Finalizing AOF...");
1124 
1125     /* Read the final diff if any. */
1126     aofReadDiffFromParent();
1127 
1128     /* Write the received diff to the file. */
1129     redisLog(REDIS_NOTICE,
1130         "Concatenating %.2f MB of AOF diff received from parent.",
1131         (double) sdslen(server.aof_child_diff) / (1024*1024));
1132     if (rioWrite(&aof,server.aof_child_diff,sdslen(server.aof_child_diff)) == 0)
1133         goto werr;
1134 
1135     /* Make sure data will not remain on the OS's output buffers */
1136     if (fflush(fp) == EOF) goto werr;
1137     if (fsync(fileno(fp)) == -1) goto werr;
1138     if (fclose(fp) == EOF) goto werr;
1139 
1140     /* Use RENAME to make sure the DB file is changed atomically only
1141      * if the generate DB file is ok. */
1142     if (rename(tmpfile,filename) == -1) {
1143         redisLog(REDIS_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno));
1144         unlink(tmpfile);
1145         return REDIS_ERR;
1146     }
1147     redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");
1148     return REDIS_OK;
1149 
1150 werr:
1151     fclose(fp);
1152     unlink(tmpfile);
1153     redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));
1154     if (di) dictReleaseIterator(di);
1155     return REDIS_ERR;
1156 }
1157 
1158 /* ----------------------------------------------------------------------------
1159  * AOF rewrite pipes for IPC
1160  * -------------------------------------------------------------------------- */
1161 
1162 /* This event handler is called when the AOF rewriting child sends us a
1163  * single '!' char to signal we should stop sending buffer diffs. The
1164  * parent sends a '!' as well to acknowledge. */
1165 void aofChildPipeReadable(aeEventLoop *el, int fd, void *privdata, int mask) {
1166     char byte;
1167     REDIS_NOTUSED(el);
1168     REDIS_NOTUSED(privdata);
1169     REDIS_NOTUSED(mask);
1170 
1171     if (read(fd,&byte,1) == 1 && byte == '!') {
1172         redisLog(REDIS_NOTICE,"AOF rewrite child asks to stop sending diffs.");
1173         server.aof_stop_sending_diff = 1;
1174         if (write(server.aof_pipe_write_ack_to_child,"!",1) != 1) {
1175             /* If we can't send the ack, inform the user, but don't try again
1176              * since in the other side the children will use a timeout if the
1177              * kernel can't buffer our write, or, the children was
1178              * terminated. */
1179             redisLog(REDIS_WARNING,"Can't send ACK to AOF child: %s",
1180                 strerror(errno));
1181         }
1182     }
1183     /* Remove the handler since this can be called only one time during a
1184      * rewrite. */
1185     aeDeleteFileEvent(server.el,server.aof_pipe_read_ack_from_child,AE_READABLE);
1186 }
1187 
1188 /* Create the pipes used for parent - child process IPC during rewrite.
1189  * We have a data pipe used to send AOF incremental diffs to the child,
1190  * and two other pipes used by the children to signal it finished with
1191  * the rewrite so no more data should be written, and another for the
1192  * parent to acknowledge it understood this new condition. */
1193 int aofCreatePipes(void) {
1194     int fds[6] = {-1, -1, -1, -1, -1, -1};
1195     int j;
1196 
1197     if (pipe(fds) == -1) goto error; /* parent -> children data. */
1198     if (pipe(fds+2) == -1) goto error; /* children -> parent ack. */
1199     if (pipe(fds+4) == -1) goto error; /* children -> parent ack. */
1200     /* Parent -> children data is non blocking. */
1201     if (anetNonBlock(NULL,fds[0]) != ANET_OK) goto error;
1202     if (anetNonBlock(NULL,fds[1]) != ANET_OK) goto error;
1203     if (aeCreateFileEvent(server.el, fds[2], AE_READABLE, aofChildPipeReadable, NULL) == AE_ERR) goto error;
1204 
1205     server.aof_pipe_write_data_to_child = fds[1];
1206     server.aof_pipe_read_data_from_parent = fds[0];
1207     server.aof_pipe_write_ack_to_parent = fds[3];
1208     server.aof_pipe_read_ack_from_child = fds[2];
1209     server.aof_pipe_write_ack_to_child = fds[5];
1210     server.aof_pipe_read_ack_from_parent = fds[4];
1211     server.aof_stop_sending_diff = 0;
1212     return REDIS_OK;
1213 
1214 error:
1215     redisLog(REDIS_WARNING,"Error opening /setting AOF rewrite IPC pipes: %s",
1216         strerror(errno));
1217     for (j = 0; j < 6; j++) if(fds[j] != -1) close(fds[j]);
1218     return REDIS_ERR;
1219 }
1220 
1221 void aofClosePipes(void) {
1222     aeDeleteFileEvent(server.el,server.aof_pipe_read_ack_from_child,AE_READABLE);
1223     aeDeleteFileEvent(server.el,server.aof_pipe_write_data_to_child,AE_WRITABLE);
1224     close(server.aof_pipe_write_data_to_child);
1225     close(server.aof_pipe_read_data_from_parent);
1226     close(server.aof_pipe_write_ack_to_parent);
1227     close(server.aof_pipe_read_ack_from_child);
1228     close(server.aof_pipe_write_ack_to_child);
1229     close(server.aof_pipe_read_ack_from_parent);
1230 }
1231 
1232 /* ----------------------------------------------------------------------------
1233  * AOF backgorund rewrite
1234  * ------------------------------------------------------------------------- */
1235 
1236 /* This is how rewriting of the append only file in background works:
1237  *
1238  * 1) The user calls BGREWRITEAOF
1239  * 2) Redis calls this function, that forks():
1240  *    2a) the child rewrite the append only file in a temp file.
1241  *    2b) the parent accumulates differences in server.aof_rewrite_buf.
1242  * 3) When the child finished '2a' exists.
1243  * 4) The parent will trap the exit code, if it's OK, will append the
1244  *    data accumulated into server.aof_rewrite_buf into the temp file, and
1245  *    finally will rename(2) the temp file in the actual file name.
1246  *    The the new file is reopened as the new append only file. Profit!
1247  */
1248 int rewriteAppendOnlyFileBackground(void) {
1249     pid_t childpid;
1250     long long start;
1251 
1252     if (server.aof_child_pid != -1) return REDIS_ERR;
1253     if (aofCreatePipes() != REDIS_OK) return REDIS_ERR;
1254     start = ustime();
1255     if ((childpid = fork()) == 0) {
1256         char tmpfile[256];
1257 
1258         /* Child */
1259         closeListeningSockets(0);
1260         redisSetProcTitle("redis-aof-rewrite");
1261         snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
1262         if (rewriteAppendOnlyFile(tmpfile) == REDIS_OK) {
1263             size_t private_dirty = zmalloc_get_private_dirty();
1264 
1265             if (private_dirty) {
1266                 redisLog(REDIS_NOTICE,
1267                     "AOF rewrite: %zu MB of memory used by copy-on-write",
1268                     private_dirty/(1024*1024));
1269             }
1270             exitFromChild(0);
1271         } else {
1272             exitFromChild(1);
1273         }
1274     } else {
1275         /* Parent */
1276         server.stat_fork_time = ustime()-start;
1277         server.stat_fork_rate = (double) zmalloc_used_memory() * 1000000 / server.stat_fork_time / (1024*1024*1024); /* GB per second. */
1278         latencyAddSampleIfNeeded("fork",server.stat_fork_time/1000);
1279         if (childpid == -1) {
1280             redisLog(REDIS_WARNING,
1281                 "Can't rewrite append only file in background: fork: %s",
1282                 strerror(errno));
1283             return REDIS_ERR;
1284         }
1285         redisLog(REDIS_NOTICE,
1286             "Background append only file rewriting started by pid %d",childpid);
1287         server.aof_rewrite_scheduled = 0;
1288         server.aof_rewrite_time_start = time(NULL);
1289         server.aof_child_pid = childpid;
1290         updateDictResizePolicy();
1291         /* We set appendseldb to -1 in order to force the next call to the
1292          * feedAppendOnlyFile() to issue a SELECT command, so the differences
1293          * accumulated by the parent into server.aof_rewrite_buf will start
1294          * with a SELECT statement and it will be safe to merge. */
1295         server.aof_selected_db = -1;
1296         replicationScriptCacheFlush();
1297         return REDIS_OK;
1298     }
1299     return REDIS_OK; /* unreached */
1300 }
1301 
1302 void bgrewriteaofCommand(redisClient *c) {
1303     if (server.aof_child_pid != -1) {
1304         addReplyError(c,"Background append only file rewriting already in progress");
1305     } else if (server.rdb_child_pid != -1) {
1306         server.aof_rewrite_scheduled = 1;
1307         addReplyStatus(c,"Background append only file rewriting scheduled");
1308     } else if (rewriteAppendOnlyFileBackground() == REDIS_OK) {
1309         addReplyStatus(c,"Background append only file rewriting started");
1310     } else {
1311         addReply(c,shared.err);
1312     }
1313 }
1314 
1315 void aofRemoveTempFile(pid_t childpid) {
1316     char tmpfile[256];
1317 
1318     snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid);
1319     unlink(tmpfile);
1320 }
1321 
1322 /* Update the server.aof_current_size field explicitly using stat(2)
1323  * to check the size of the file. This is useful after a rewrite or after
1324  * a restart, normally the size is updated just adding the write length
1325  * to the current length, that is much faster. */
1326 void aofUpdateCurrentSize(void) {
1327     struct redis_stat sb;
1328     mstime_t latency;
1329 
1330     latencyStartMonitor(latency);
1331     if (redis_fstat(server.aof_fd,&sb) == -1) {
1332         redisLog(REDIS_WARNING,"Unable to obtain the AOF file length. stat: %s",
1333             strerror(errno));
1334     } else {
1335         server.aof_current_size = sb.st_size;
1336     }
1337     latencyEndMonitor(latency);
1338     latencyAddSampleIfNeeded("aof-fstat",latency);
1339 }
1340 
1341 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1342  * Handle this. */
1343 void backgroundRewriteDoneHandler(int exitcode, int bysignal) {
1344     if (!bysignal && exitcode == 0) {
1345         int newfd, oldfd;
1346         char tmpfile[256];
1347         long long now = ustime();
1348         mstime_t latency;
1349 
1350         redisLog(REDIS_NOTICE,
1351             "Background AOF rewrite terminated with success");
1352 
1353         /* Flush the differences accumulated by the parent to the
1354          * rewritten AOF. */
1355         latencyStartMonitor(latency);
1356         snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof",
1357             (int)server.aof_child_pid);
1358         newfd = open(tmpfile,O_WRONLY|O_APPEND);
1359         if (newfd == -1) {
1360             redisLog(REDIS_WARNING,
1361                 "Unable to open the temporary AOF produced by the child: %s", strerror(errno));
1362             goto cleanup;
1363         }
1364 
1365         if (aofRewriteBufferWrite(newfd) == -1) {
1366             redisLog(REDIS_WARNING,
1367                 "Error trying to flush the parent diff to the rewritten AOF: %s", strerror(errno));
1368             close(newfd);
1369             goto cleanup;
1370         }
1371         latencyEndMonitor(latency);
1372         latencyAddSampleIfNeeded("aof-rewrite-diff-write",latency);
1373 
1374         redisLog(REDIS_NOTICE,
1375             "Redidual parent diff successfully flushed to the rewritten AOF (%.2f MB)", (double) aofRewriteBufferSize() / (1024*1024));
1376 
1377         /* The only remaining thing to do is to rename the temporary file to
1378          * the configured file and switch the file descriptor used to do AOF
1379          * writes. We don't want close(2) or rename(2) calls to block the
1380          * server on old file deletion.
1381          *
1382          * There are two possible scenarios:
1383          *
1384          * 1) AOF is DISABLED and this was a one time rewrite. The temporary
1385          * file will be renamed to the configured file. When this file already
1386          * exists, it will be unlinked, which may block the server.
1387          *
1388          * 2) AOF is ENABLED and the rewritten AOF will immediately start
1389          * receiving writes. After the temporary file is renamed to the
1390          * configured file, the original AOF file descriptor will be closed.
1391          * Since this will be the last reference to that file, closing it
1392          * causes the underlying file to be unlinked, which may block the
1393          * server.
1394          *
1395          * To mitigate the blocking effect of the unlink operation (either
1396          * caused by rename(2) in scenario 1, or by close(2) in scenario 2), we
1397          * use a background thread to take care of this. First, we
1398          * make scenario 1 identical to scenario 2 by opening the target file
1399          * when it exists. The unlink operation after the rename(2) will then
1400          * be executed upon calling close(2) for its descriptor. Everything to
1401          * guarantee atomicity for this switch has already happened by then, so
1402          * we don't care what the outcome or duration of that close operation
1403          * is, as long as the file descriptor is released again. */
1404         if (server.aof_fd == -1) {
1405             /* AOF disabled */
1406 
1407              /* Don't care if this fails: oldfd will be -1 and we handle that.
1408               * One notable case of -1 return is if the old file does
1409               * not exist. */
1410              oldfd = open(server.aof_filename,O_RDONLY|O_NONBLOCK);
1411         } else {
1412             /* AOF enabled */
1413             oldfd = -1; /* We'll set this to the current AOF filedes later. */
1414         }
1415 
1416         /* Rename the temporary file. This will not unlink the target file if
1417          * it exists, because we reference it with "oldfd". */
1418         latencyStartMonitor(latency);
1419         if (rename(tmpfile,server.aof_filename) == -1) {
1420             redisLog(REDIS_WARNING,
1421                 "Error trying to rename the temporary AOF file: %s", strerror(errno));
1422             close(newfd);
1423             if (oldfd != -1) close(oldfd);
1424             goto cleanup;
1425         }
1426         latencyEndMonitor(latency);
1427         latencyAddSampleIfNeeded("aof-rename",latency);
1428 
1429         if (server.aof_fd == -1) {
1430             /* AOF disabled, we don't need to set the AOF file descriptor
1431              * to this new file, so we can close it. */
1432             close(newfd);
1433         } else {
1434             /* AOF enabled, replace the old fd with the new one. */
1435             oldfd = server.aof_fd;
1436             server.aof_fd = newfd;
1437             if (server.aof_fsync == AOF_FSYNC_ALWAYS)
1438                 aof_fsync(newfd);
1439             else if (server.aof_fsync == AOF_FSYNC_EVERYSEC)
1440                 aof_background_fsync(newfd);
1441             server.aof_selected_db = -1; /* Make sure SELECT is re-issued */
1442             aofUpdateCurrentSize();
1443             server.aof_rewrite_base_size = server.aof_current_size;
1444 
1445             /* Clear regular AOF buffer since its contents was just written to
1446              * the new AOF from the background rewrite buffer. */
1447             sdsfree(server.aof_buf);
1448             server.aof_buf = sdsempty();
1449         }
1450 
1451         server.aof_lastbgrewrite_status = REDIS_OK;
1452 
1453         redisLog(REDIS_NOTICE, "Background AOF rewrite finished successfully");
1454         /* Change state from WAIT_REWRITE to ON if needed */
1455         if (server.aof_state == REDIS_AOF_WAIT_REWRITE)
1456             server.aof_state = REDIS_AOF_ON;
1457 
1458         /* Asynchronously close the overwritten AOF. */
1459         if (oldfd != -1) bioCreateBackgroundJob(REDIS_BIO_CLOSE_FILE,(void*)(long)oldfd,NULL,NULL);
1460 
1461         redisLog(REDIS_VERBOSE,
1462             "Background AOF rewrite signal handler took %lldus", ustime()-now);
1463     } else if (!bysignal && exitcode != 0) {
1464         server.aof_lastbgrewrite_status = REDIS_ERR;
1465 
1466         redisLog(REDIS_WARNING,
1467             "Background AOF rewrite terminated with error");
1468     } else {
1469         server.aof_lastbgrewrite_status = REDIS_ERR;
1470 
1471         redisLog(REDIS_WARNING,
1472             "Background AOF rewrite terminated by signal %d", bysignal);
1473     }
1474 
1475 cleanup:
1476     aofClosePipes();
1477     aofRewriteBufferReset();
1478     aofRemoveTempFile(server.aof_child_pid);
1479     server.aof_child_pid = -1;
1480     server.aof_rewrite_time_last = time(NULL)-server.aof_rewrite_time_start;
1481     server.aof_rewrite_time_start = -1;
1482     /* Schedule a new rewrite if we are waiting for it to switch the AOF ON. */
1483     if (server.aof_state == REDIS_AOF_WAIT_REWRITE)
1484         server.aof_rewrite_scheduled = 1;
1485 }
1486