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