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