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