]> git.saurik.com Git - redis.git/blob - src/aof.c
60694dbfa26634bc5184c623c58a33958b5fa4ce
[redis.git] / src / aof.c
1 #include "redis.h"
2
3 #include <signal.h>
4 #include <fcntl.h>
5 #include <sys/stat.h>
6 #include <sys/types.h>
7 #include <sys/time.h>
8 #include <sys/resource.h>
9 #include <sys/wait.h>
10
11 void aofUpdateCurrentSize(void);
12
13 /* Called when the user switches from "appendonly yes" to "appendonly no"
14 * at runtime using the CONFIG command. */
15 void stopAppendOnly(void) {
16 flushAppendOnlyFile();
17 aof_fsync(server.appendfd);
18 close(server.appendfd);
19
20 server.appendfd = -1;
21 server.appendseldb = -1;
22 server.appendonly = 0;
23 /* rewrite operation in progress? kill it, wait child exit */
24 if (server.bgrewritechildpid != -1) {
25 int statloc;
26
27 if (kill(server.bgrewritechildpid,SIGKILL) != -1)
28 wait3(&statloc,0,NULL);
29 /* reset the buffer accumulating changes while the child saves */
30 sdsfree(server.bgrewritebuf);
31 server.bgrewritebuf = sdsempty();
32 server.bgrewritechildpid = -1;
33 }
34 }
35
36 /* Called when the user switches from "appendonly no" to "appendonly yes"
37 * at runtime using the CONFIG command. */
38 int startAppendOnly(void) {
39 server.appendonly = 1;
40 server.lastfsync = time(NULL);
41 server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
42 if (server.appendfd == -1) {
43 redisLog(REDIS_WARNING,"Used tried to switch on AOF via CONFIG, but I can't open the AOF file: %s",strerror(errno));
44 return REDIS_ERR;
45 }
46 if (rewriteAppendOnlyFileBackground() == REDIS_ERR) {
47 server.appendonly = 0;
48 close(server.appendfd);
49 redisLog(REDIS_WARNING,"Used tried to switch on AOF via CONFIG, I can't trigger a background AOF rewrite operation. Check the above logs for more info about the error.",strerror(errno));
50 return REDIS_ERR;
51 }
52 return REDIS_OK;
53 }
54
55 /* Write the append only file buffer on disk.
56 *
57 * Since we are required to write the AOF before replying to the client,
58 * and the only way the client socket can get a write is entering when the
59 * the event loop, we accumulate all the AOF writes in a memory
60 * buffer and write it on disk using this function just before entering
61 * the event loop again. */
62 void flushAppendOnlyFile(void) {
63 ssize_t nwritten;
64
65 if (sdslen(server.aofbuf) == 0) return;
66
67 /* We want to perform a single write. This should be guaranteed atomic
68 * at least if the filesystem we are writing is a real physical one.
69 * While this will save us against the server being killed I don't think
70 * there is much to do about the whole server stopping for power problems
71 * or alike */
72 nwritten = write(server.appendfd,server.aofbuf,sdslen(server.aofbuf));
73 if (nwritten != (signed)sdslen(server.aofbuf)) {
74 /* Ooops, we are in troubles. The best thing to do for now is
75 * aborting instead of giving the illusion that everything is
76 * working as expected. */
77 if (nwritten == -1) {
78 redisLog(REDIS_WARNING,"Exiting on error writing to the append-only file: %s",strerror(errno));
79 } else {
80 redisLog(REDIS_WARNING,"Exiting on short write while writing to the append-only file: %s",strerror(errno));
81 }
82 exit(1);
83 }
84 server.appendonly_current_size += nwritten;
85
86 /* Re-use AOF buffer when it is small enough. The maximum comes from the
87 * arena size of 4k minus some overhead (but is otherwise arbitrary). */
88 if ((sdslen(server.aofbuf)+sdsavail(server.aofbuf)) < 4000) {
89 sdsclear(server.aofbuf);
90 } else {
91 sdsfree(server.aofbuf);
92 server.aofbuf = sdsempty();
93 }
94
95 /* Don't fsync if no-appendfsync-on-rewrite is set to yes and there are
96 * children doing I/O in the background. */
97 if (server.no_appendfsync_on_rewrite &&
98 (server.bgrewritechildpid != -1 || server.bgsavechildpid != -1))
99 return;
100
101 /* Perform the fsync if needed. */
102 if (server.appendfsync == APPENDFSYNC_ALWAYS ||
103 (server.appendfsync == APPENDFSYNC_EVERYSEC &&
104 server.unixtime > server.lastfsync))
105 {
106 /* aof_fsync is defined as fdatasync() for Linux in order to avoid
107 * flushing metadata. */
108 aof_fsync(server.appendfd); /* Let's try to get this data on the disk */
109 server.lastfsync = server.unixtime;
110 }
111 }
112
113 sds catAppendOnlyGenericCommand(sds buf, int argc, robj **argv) {
114 int j;
115 buf = sdscatprintf(buf,"*%d\r\n",argc);
116 for (j = 0; j < argc; j++) {
117 robj *o = getDecodedObject(argv[j]);
118 buf = sdscatprintf(buf,"$%lu\r\n",(unsigned long)sdslen(o->ptr));
119 buf = sdscatlen(buf,o->ptr,sdslen(o->ptr));
120 buf = sdscatlen(buf,"\r\n",2);
121 decrRefCount(o);
122 }
123 return buf;
124 }
125
126 sds catAppendOnlyExpireAtCommand(sds buf, robj *key, robj *seconds) {
127 int argc = 3;
128 long when;
129 robj *argv[3];
130
131 /* Make sure we can use strtol */
132 seconds = getDecodedObject(seconds);
133 when = time(NULL)+strtol(seconds->ptr,NULL,10);
134 decrRefCount(seconds);
135
136 argv[0] = createStringObject("EXPIREAT",8);
137 argv[1] = key;
138 argv[2] = createObject(REDIS_STRING,
139 sdscatprintf(sdsempty(),"%ld",when));
140 buf = catAppendOnlyGenericCommand(buf, argc, argv);
141 decrRefCount(argv[0]);
142 decrRefCount(argv[2]);
143 return buf;
144 }
145
146 void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) {
147 sds buf = sdsempty();
148 robj *tmpargv[3];
149
150 /* The DB this command was targetting is not the same as the last command
151 * we appendend. To issue a SELECT command is needed. */
152 if (dictid != server.appendseldb) {
153 char seldb[64];
154
155 snprintf(seldb,sizeof(seldb),"%d",dictid);
156 buf = sdscatprintf(buf,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
157 (unsigned long)strlen(seldb),seldb);
158 server.appendseldb = dictid;
159 }
160
161 if (cmd->proc == expireCommand) {
162 /* Translate EXPIRE into EXPIREAT */
163 buf = catAppendOnlyExpireAtCommand(buf,argv[1],argv[2]);
164 } else if (cmd->proc == setexCommand) {
165 /* Translate SETEX to SET and EXPIREAT */
166 tmpargv[0] = createStringObject("SET",3);
167 tmpargv[1] = argv[1];
168 tmpargv[2] = argv[3];
169 buf = catAppendOnlyGenericCommand(buf,3,tmpargv);
170 decrRefCount(tmpargv[0]);
171 buf = catAppendOnlyExpireAtCommand(buf,argv[1],argv[2]);
172 } else {
173 buf = catAppendOnlyGenericCommand(buf,argc,argv);
174 }
175
176 /* Append to the AOF buffer. This will be flushed on disk just before
177 * of re-entering the event loop, so before the client will get a
178 * positive reply about the operation performed. */
179 server.aofbuf = sdscatlen(server.aofbuf,buf,sdslen(buf));
180
181 /* If a background append only file rewriting is in progress we want to
182 * accumulate the differences between the child DB and the current one
183 * in a buffer, so that when the child process will do its work we
184 * can append the differences to the new append only file. */
185 if (server.bgrewritechildpid != -1)
186 server.bgrewritebuf = sdscatlen(server.bgrewritebuf,buf,sdslen(buf));
187
188 sdsfree(buf);
189 }
190
191 /* In Redis commands are always executed in the context of a client, so in
192 * order to load the append only file we need to create a fake client. */
193 struct redisClient *createFakeClient(void) {
194 struct redisClient *c = zmalloc(sizeof(*c));
195
196 selectDb(c,0);
197 c->fd = -1;
198 c->querybuf = sdsempty();
199 c->argc = 0;
200 c->argv = NULL;
201 c->bufpos = 0;
202 c->flags = 0;
203 /* We set the fake client as a slave waiting for the synchronization
204 * so that Redis will not try to send replies to this client. */
205 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
206 c->reply = listCreate();
207 c->watched_keys = listCreate();
208 listSetFreeMethod(c->reply,decrRefCount);
209 listSetDupMethod(c->reply,dupClientReplyValue);
210 initClientMultiState(c);
211 return c;
212 }
213
214 void freeFakeClient(struct redisClient *c) {
215 sdsfree(c->querybuf);
216 listRelease(c->reply);
217 listRelease(c->watched_keys);
218 freeClientMultiState(c);
219 zfree(c);
220 }
221
222 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
223 * error (the append only file is zero-length) REDIS_ERR is returned. On
224 * fatal error an error message is logged and the program exists. */
225 int loadAppendOnlyFile(char *filename) {
226 struct redisClient *fakeClient;
227 FILE *fp = fopen(filename,"r");
228 struct redis_stat sb;
229 int appendonly = server.appendonly;
230 long loops = 0;
231
232 if (fp && redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0) {
233 server.appendonly_current_size = 0;
234 fclose(fp);
235 return REDIS_ERR;
236 }
237
238 if (fp == NULL) {
239 redisLog(REDIS_WARNING,"Fatal error: can't open the append log file for reading: %s",strerror(errno));
240 exit(1);
241 }
242
243 /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
244 * to the same file we're about to read. */
245 server.appendonly = 0;
246
247 fakeClient = createFakeClient();
248 startLoading(fp);
249
250 while(1) {
251 int argc, j;
252 unsigned long len;
253 robj **argv;
254 char buf[128];
255 sds argsds;
256 struct redisCommand *cmd;
257
258 /* Serve the clients from time to time */
259 if (!(loops++ % 1000)) {
260 loadingProgress(ftello(fp));
261 aeProcessEvents(server.el, AE_FILE_EVENTS|AE_DONT_WAIT);
262 }
263
264 if (fgets(buf,sizeof(buf),fp) == NULL) {
265 if (feof(fp))
266 break;
267 else
268 goto readerr;
269 }
270 if (buf[0] != '*') goto fmterr;
271 argc = atoi(buf+1);
272 argv = zmalloc(sizeof(robj*)*argc);
273 for (j = 0; j < argc; j++) {
274 if (fgets(buf,sizeof(buf),fp) == NULL) goto readerr;
275 if (buf[0] != '$') goto fmterr;
276 len = strtol(buf+1,NULL,10);
277 argsds = sdsnewlen(NULL,len);
278 if (len && fread(argsds,len,1,fp) == 0) goto fmterr;
279 argv[j] = createObject(REDIS_STRING,argsds);
280 if (fread(buf,2,1,fp) == 0) goto fmterr; /* discard CRLF */
281 }
282
283 /* Command lookup */
284 cmd = lookupCommand(argv[0]->ptr);
285 if (!cmd) {
286 redisLog(REDIS_WARNING,"Unknown command '%s' reading the append only file", argv[0]->ptr);
287 exit(1);
288 }
289 /* Run the command in the context of a fake client */
290 fakeClient->argc = argc;
291 fakeClient->argv = argv;
292 cmd->proc(fakeClient);
293
294 /* The fake client should not have a reply */
295 redisAssert(fakeClient->bufpos == 0 && listLength(fakeClient->reply) == 0);
296 /* The fake client should never get blocked */
297 redisAssert((fakeClient->flags & REDIS_BLOCKED) == 0);
298
299 /* Clean up. Command code may have changed argv/argc so we use the
300 * argv/argc of the client instead of the local variables. */
301 for (j = 0; j < fakeClient->argc; j++)
302 decrRefCount(fakeClient->argv[j]);
303 zfree(fakeClient->argv);
304 }
305
306 /* This point can only be reached when EOF is reached without errors.
307 * If the client is in the middle of a MULTI/EXEC, log error and quit. */
308 if (fakeClient->flags & REDIS_MULTI) goto readerr;
309
310 fclose(fp);
311 freeFakeClient(fakeClient);
312 server.appendonly = appendonly;
313 stopLoading();
314 aofUpdateCurrentSize();
315 server.auto_aofrewrite_base_size = server.appendonly_current_size;
316 return REDIS_OK;
317
318 readerr:
319 if (feof(fp)) {
320 redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file");
321 } else {
322 redisLog(REDIS_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno));
323 }
324 exit(1);
325 fmterr:
326 redisLog(REDIS_WARNING,"Bad file format reading the append only file: make a backup of your AOF file, then use ./redis-check-aof --fix <filename>");
327 exit(1);
328 }
329
330 /* Write a sequence of commands able to fully rebuild the dataset into
331 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
332 int rewriteAppendOnlyFile(char *filename) {
333 dictIterator *di = NULL;
334 dictEntry *de;
335 FILE *fp;
336 char tmpfile[256];
337 int j;
338 time_t now = time(NULL);
339
340 /* Note that we have to use a different temp name here compared to the
341 * one used by rewriteAppendOnlyFileBackground() function. */
342 snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
343 fp = fopen(tmpfile,"w");
344 if (!fp) {
345 redisLog(REDIS_WARNING, "Failed rewriting the append only file: %s", strerror(errno));
346 return REDIS_ERR;
347 }
348 for (j = 0; j < server.dbnum; j++) {
349 char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
350 redisDb *db = server.db+j;
351 dict *d = db->dict;
352 if (dictSize(d) == 0) continue;
353 di = dictGetSafeIterator(d);
354 if (!di) {
355 fclose(fp);
356 return REDIS_ERR;
357 }
358
359 /* SELECT the new DB */
360 if (fwrite(selectcmd,sizeof(selectcmd)-1,1,fp) == 0) goto werr;
361 if (fwriteBulkLongLong(fp,j) == 0) goto werr;
362
363 /* Iterate this DB writing every entry */
364 while((de = dictNext(di)) != NULL) {
365 sds keystr;
366 robj key, *o;
367 time_t expiretime;
368
369 keystr = dictGetEntryKey(de);
370 o = dictGetEntryVal(de);
371 initStaticStringObject(key,keystr);
372
373 expiretime = getExpire(db,&key);
374
375 /* Save the key and associated value */
376 if (o->type == REDIS_STRING) {
377 /* Emit a SET command */
378 char cmd[]="*3\r\n$3\r\nSET\r\n";
379 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
380 /* Key and value */
381 if (fwriteBulkObject(fp,&key) == 0) goto werr;
382 if (fwriteBulkObject(fp,o) == 0) goto werr;
383 } else if (o->type == REDIS_LIST) {
384 /* Emit the RPUSHes needed to rebuild the list */
385 char cmd[]="*3\r\n$5\r\nRPUSH\r\n";
386 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
387 unsigned char *zl = o->ptr;
388 unsigned char *p = ziplistIndex(zl,0);
389 unsigned char *vstr;
390 unsigned int vlen;
391 long long vlong;
392
393 while(ziplistGet(p,&vstr,&vlen,&vlong)) {
394 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
395 if (fwriteBulkObject(fp,&key) == 0) goto werr;
396 if (vstr) {
397 if (fwriteBulkString(fp,(char*)vstr,vlen) == 0)
398 goto werr;
399 } else {
400 if (fwriteBulkLongLong(fp,vlong) == 0)
401 goto werr;
402 }
403 p = ziplistNext(zl,p);
404 }
405 } else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
406 list *list = o->ptr;
407 listNode *ln;
408 listIter li;
409
410 listRewind(list,&li);
411 while((ln = listNext(&li))) {
412 robj *eleobj = listNodeValue(ln);
413
414 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
415 if (fwriteBulkObject(fp,&key) == 0) goto werr;
416 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
417 }
418 } else {
419 redisPanic("Unknown list encoding");
420 }
421 } else if (o->type == REDIS_SET) {
422 char cmd[]="*3\r\n$4\r\nSADD\r\n";
423
424 /* Emit the SADDs needed to rebuild the set */
425 if (o->encoding == REDIS_ENCODING_INTSET) {
426 int ii = 0;
427 int64_t llval;
428 while(intsetGet(o->ptr,ii++,&llval)) {
429 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
430 if (fwriteBulkObject(fp,&key) == 0) goto werr;
431 if (fwriteBulkLongLong(fp,llval) == 0) goto werr;
432 }
433 } else if (o->encoding == REDIS_ENCODING_HT) {
434 dictIterator *di = dictGetIterator(o->ptr);
435 dictEntry *de;
436 while((de = dictNext(di)) != NULL) {
437 robj *eleobj = dictGetEntryKey(de);
438 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
439 if (fwriteBulkObject(fp,&key) == 0) goto werr;
440 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
441 }
442 dictReleaseIterator(di);
443 } else {
444 redisPanic("Unknown set encoding");
445 }
446 } else if (o->type == REDIS_ZSET) {
447 /* Emit the ZADDs needed to rebuild the sorted set */
448 char cmd[]="*4\r\n$4\r\nZADD\r\n";
449
450 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
451 unsigned char *zl = o->ptr;
452 unsigned char *eptr, *sptr;
453 unsigned char *vstr;
454 unsigned int vlen;
455 long long vll;
456 double score;
457
458 eptr = ziplistIndex(zl,0);
459 redisAssert(eptr != NULL);
460 sptr = ziplistNext(zl,eptr);
461 redisAssert(sptr != NULL);
462
463 while (eptr != NULL) {
464 redisAssert(ziplistGet(eptr,&vstr,&vlen,&vll));
465 score = zzlGetScore(sptr);
466
467 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
468 if (fwriteBulkObject(fp,&key) == 0) goto werr;
469 if (fwriteBulkDouble(fp,score) == 0) goto werr;
470 if (vstr != NULL) {
471 if (fwriteBulkString(fp,(char*)vstr,vlen) == 0)
472 goto werr;
473 } else {
474 if (fwriteBulkLongLong(fp,vll) == 0)
475 goto werr;
476 }
477 zzlNext(zl,&eptr,&sptr);
478 }
479 } else if (o->encoding == REDIS_ENCODING_SKIPLIST) {
480 zset *zs = o->ptr;
481 dictIterator *di = dictGetIterator(zs->dict);
482 dictEntry *de;
483
484 while((de = dictNext(di)) != NULL) {
485 robj *eleobj = dictGetEntryKey(de);
486 double *score = dictGetEntryVal(de);
487
488 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
489 if (fwriteBulkObject(fp,&key) == 0) goto werr;
490 if (fwriteBulkDouble(fp,*score) == 0) goto werr;
491 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
492 }
493 dictReleaseIterator(di);
494 } else {
495 redisPanic("Unknown sorted set encoding");
496 }
497 } else if (o->type == REDIS_HASH) {
498 char cmd[]="*4\r\n$4\r\nHSET\r\n";
499
500 /* Emit the HSETs needed to rebuild the hash */
501 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
502 unsigned char *p = zipmapRewind(o->ptr);
503 unsigned char *field, *val;
504 unsigned int flen, vlen;
505
506 while((p = zipmapNext(p,&field,&flen,&val,&vlen)) != NULL) {
507 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
508 if (fwriteBulkObject(fp,&key) == 0) goto werr;
509 if (fwriteBulkString(fp,(char*)field,flen) == 0)
510 goto werr;
511 if (fwriteBulkString(fp,(char*)val,vlen) == 0)
512 goto werr;
513 }
514 } else {
515 dictIterator *di = dictGetIterator(o->ptr);
516 dictEntry *de;
517
518 while((de = dictNext(di)) != NULL) {
519 robj *field = dictGetEntryKey(de);
520 robj *val = dictGetEntryVal(de);
521
522 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
523 if (fwriteBulkObject(fp,&key) == 0) goto werr;
524 if (fwriteBulkObject(fp,field) == 0) goto werr;
525 if (fwriteBulkObject(fp,val) == 0) goto werr;
526 }
527 dictReleaseIterator(di);
528 }
529 } else {
530 redisPanic("Unknown object type");
531 }
532 /* Save the expire time */
533 if (expiretime != -1) {
534 char cmd[]="*3\r\n$8\r\nEXPIREAT\r\n";
535 /* If this key is already expired skip it */
536 if (expiretime < now) continue;
537 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
538 if (fwriteBulkObject(fp,&key) == 0) goto werr;
539 if (fwriteBulkLongLong(fp,expiretime) == 0) goto werr;
540 }
541 }
542 dictReleaseIterator(di);
543 }
544
545 /* Make sure data will not remain on the OS's output buffers */
546 fflush(fp);
547 aof_fsync(fileno(fp));
548 fclose(fp);
549
550 /* Use RENAME to make sure the DB file is changed atomically only
551 * if the generate DB file is ok. */
552 if (rename(tmpfile,filename) == -1) {
553 redisLog(REDIS_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno));
554 unlink(tmpfile);
555 return REDIS_ERR;
556 }
557 redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");
558 return REDIS_OK;
559
560 werr:
561 fclose(fp);
562 unlink(tmpfile);
563 redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));
564 if (di) dictReleaseIterator(di);
565 return REDIS_ERR;
566 }
567
568 /* This is how rewriting of the append only file in background works:
569 *
570 * 1) The user calls BGREWRITEAOF
571 * 2) Redis calls this function, that forks():
572 * 2a) the child rewrite the append only file in a temp file.
573 * 2b) the parent accumulates differences in server.bgrewritebuf.
574 * 3) When the child finished '2a' exists.
575 * 4) The parent will trap the exit code, if it's OK, will append the
576 * data accumulated into server.bgrewritebuf into the temp file, and
577 * finally will rename(2) the temp file in the actual file name.
578 * The the new file is reopened as the new append only file. Profit!
579 */
580 int rewriteAppendOnlyFileBackground(void) {
581 pid_t childpid;
582 long long start;
583
584 if (server.bgrewritechildpid != -1) return REDIS_ERR;
585 start = ustime();
586 if ((childpid = fork()) == 0) {
587 char tmpfile[256];
588
589 /* Child */
590 if (server.ipfd > 0) close(server.ipfd);
591 if (server.sofd > 0) close(server.sofd);
592 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
593 if (rewriteAppendOnlyFile(tmpfile) == REDIS_OK) {
594 _exit(0);
595 } else {
596 _exit(1);
597 }
598 } else {
599 /* Parent */
600 server.stat_fork_time = ustime()-start;
601 if (childpid == -1) {
602 redisLog(REDIS_WARNING,
603 "Can't rewrite append only file in background: fork: %s",
604 strerror(errno));
605 return REDIS_ERR;
606 }
607 redisLog(REDIS_NOTICE,
608 "Background append only file rewriting started by pid %d",childpid);
609 server.bgrewritechildpid = childpid;
610 updateDictResizePolicy();
611 /* We set appendseldb to -1 in order to force the next call to the
612 * feedAppendOnlyFile() to issue a SELECT command, so the differences
613 * accumulated by the parent into server.bgrewritebuf will start
614 * with a SELECT statement and it will be safe to merge. */
615 server.appendseldb = -1;
616 return REDIS_OK;
617 }
618 return REDIS_OK; /* unreached */
619 }
620
621 void bgrewriteaofCommand(redisClient *c) {
622 if (server.bgrewritechildpid != -1) {
623 addReplyError(c,"Background append only file rewriting already in progress");
624 } else if (server.bgsavechildpid != -1) {
625 server.aofrewrite_scheduled = 1;
626 addReplyStatus(c,"Background append only file rewriting scheduled");
627 } else if (rewriteAppendOnlyFileBackground() == REDIS_OK) {
628 addReplyStatus(c,"Background append only file rewriting started");
629 } else {
630 addReply(c,shared.err);
631 }
632 }
633
634 void aofRemoveTempFile(pid_t childpid) {
635 char tmpfile[256];
636
637 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid);
638 unlink(tmpfile);
639 }
640
641 /* Update the server.appendonly_current_size filed explicitly using stat(2)
642 * to check the size of the file. This is useful after a rewrite or after
643 * a restart, normally the size is updated just adding the write length
644 * to the current lenght, that is much faster. */
645 void aofUpdateCurrentSize(void) {
646 struct redis_stat sb;
647
648 if (redis_fstat(server.appendfd,&sb) == -1) {
649 redisLog(REDIS_WARNING,"Unable to check the AOF length: %s",
650 strerror(errno));
651 } else {
652 server.appendonly_current_size = sb.st_size;
653 }
654 }
655
656 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
657 * Handle this. */
658 void backgroundRewriteDoneHandler(int exitcode, int bysignal) {
659 if (!bysignal && exitcode == 0) {
660 int fd;
661 char tmpfile[256];
662
663 redisLog(REDIS_NOTICE,
664 "Background append only file rewriting terminated with success");
665 /* Now it's time to flush the differences accumulated by the parent */
666 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) server.bgrewritechildpid);
667 fd = open(tmpfile,O_WRONLY|O_APPEND);
668 if (fd == -1) {
669 redisLog(REDIS_WARNING, "Not able to open the temp append only file produced by the child: %s", strerror(errno));
670 goto cleanup;
671 }
672 /* Flush our data... */
673 if (write(fd,server.bgrewritebuf,sdslen(server.bgrewritebuf)) !=
674 (signed) sdslen(server.bgrewritebuf)) {
675 redisLog(REDIS_WARNING, "Error or short write trying to flush the parent diff of the append log file in the child temp file: %s", strerror(errno));
676 close(fd);
677 goto cleanup;
678 }
679 redisLog(REDIS_NOTICE,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server.bgrewritebuf));
680 /* Now our work is to rename the temp file into the stable file. And
681 * switch the file descriptor used by the server for append only. */
682 if (rename(tmpfile,server.appendfilename) == -1) {
683 redisLog(REDIS_WARNING,"Can't rename the temp append only file into the stable one: %s", strerror(errno));
684 close(fd);
685 goto cleanup;
686 }
687 /* Mission completed... almost */
688 redisLog(REDIS_NOTICE,"Append only file successfully rewritten.");
689 if (server.appendfd != -1) {
690 /* If append only is actually enabled... */
691 close(server.appendfd);
692 server.appendfd = fd;
693 if (server.appendfsync != APPENDFSYNC_NO) aof_fsync(fd);
694 server.appendseldb = -1; /* Make sure it will issue SELECT */
695 redisLog(REDIS_NOTICE,"The new append only file was selected for future appends.");
696 aofUpdateCurrentSize();
697 server.auto_aofrewrite_base_size = server.appendonly_current_size;
698 } else {
699 /* If append only is disabled we just generate a dump in this
700 * format. Why not? */
701 close(fd);
702 }
703 } else if (!bysignal && exitcode != 0) {
704 redisLog(REDIS_WARNING, "Background append only file rewriting error");
705 } else {
706 redisLog(REDIS_WARNING,
707 "Background append only file rewriting terminated by signal %d",
708 bysignal);
709 }
710 cleanup:
711 sdsfree(server.bgrewritebuf);
712 server.bgrewritebuf = sdsempty();
713 aofRemoveTempFile(server.bgrewritechildpid);
714 server.bgrewritechildpid = -1;
715 }