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