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