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