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