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