10 #include <sys/resource.h>
13 void aofUpdateCurrentSize(void);
15 /* ----------------------------------------------------------------------------
16 * AOF rewrite buffer implementation.
18 * The following code implement a simple buffer used in order to accumulate
19 * changes while the background process is rewriting the AOF file.
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.
25 * For this reason we use a list of blocks, every block is
26 * AOF_RW_BUF_BLOCK_SIZE bytes.
27 * ------------------------------------------------------------------------- */
29 #define AOF_RW_BUF_BLOCK_SIZE (1024*1024*10) /* 10 MB per block */
31 typedef struct aofrwblock
{
32 unsigned long used
, free
;
33 char buf
[AOF_RW_BUF_BLOCK_SIZE
];
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
);
43 server
.aof_rewrite_buf_blocks
= listCreate();
44 listSetFreeMethod(server
.aof_rewrite_buf_blocks
,zfree
);
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
;
52 if (block
== NULL
) return 0;
54 (listLength(server
.aof_rewrite_buf_blocks
)-1) * AOF_RW_BUF_BLOCK_SIZE
;
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
;
65 /* If we already got at least an allocated block, try appending
66 * at least some piece into it. */
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
;
78 if (len
) { /* First block to allocate, or need another block. */
81 block
= zmalloc(sizeof(*block
));
82 block
->free
= AOF_RW_BUF_BLOCK_SIZE
;
84 listAddNodeTail(server
.aof_rewrite_buf_blocks
,block
);
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
:
92 redisLog(level
,"Background AOF buffer size: %lu MB",
93 aofRewriteBufferSize()/(1024*1024));
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
) {
107 listRewind(server
.aof_rewrite_buf_blocks
,&li
);
108 while((ln
= listNext(&li
))) {
109 aofrwblock
*block
= listNodeValue(ln
);
113 nwritten
= write(fd
,block
->buf
,block
->used
);
114 if (nwritten
!= block
->used
) {
115 if (nwritten
== 0) errno
= EIO
;
124 /* ----------------------------------------------------------------------------
125 * AOF file implementation
126 * ------------------------------------------------------------------------- */
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
);
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
);
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) {
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;
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
));
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.");
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
;
182 /* Write the append only file buffer on disk.
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.
190 * About the 'force' argument:
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.
198 * However if force is set to 1 we'll write regardless of the background
200 void flushAppendOnlyFile(int force
) {
202 int sync_in_progress
= 0;
204 if (sdslen(server
.aof_buf
) == 0) return;
206 if (server
.aof_fsync
== AOF_FSYNC_EVERYSEC
)
207 sync_in_progress
= bioPendingJobsOfType(REDIS_BIO_AOF_FSYNC
) != 0;
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
;
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. */
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.");
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;
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
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
));
247 redisLog(REDIS_WARNING
,"Exiting on short write while writing to "
248 "the append-only file: %s (nwritten=%ld, "
252 (long)sdslen(server
.aof_buf
));
256 server
.aof_current_size
+= nwritten
;
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
);
263 sdsfree(server
.aof_buf
);
264 server
.aof_buf
= sdsempty();
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))
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
;
286 sds
catAppendOnlyGenericCommand(sds dst
, int argc
, robj
**argv
) {
292 len
= 1+ll2string(buf
+1,sizeof(buf
)-1,argc
);
295 dst
= sdscatlen(dst
,buf
,len
);
297 for (j
= 0; j
< argc
; j
++) {
298 o
= getDecodedObject(argv
[j
]);
300 len
= 1+ll2string(buf
+1,sizeof(buf
)-1,sdslen(o
->ptr
));
303 dst
= sdscatlen(dst
,buf
,len
);
304 dst
= sdscatlen(dst
,o
->ptr
,sdslen(o
->ptr
));
305 dst
= sdscatlen(dst
,"\r\n",2);
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.
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
) {
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
)
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
)
337 decrRefCount(seconds
);
339 argv
[0] = createStringObject("PEXPIREAT",9);
341 argv
[2] = createStringObjectFromLongLong(when
);
342 buf
= catAppendOnlyGenericCommand(buf
, 3, argv
);
343 decrRefCount(argv
[0]);
344 decrRefCount(argv
[2]);
348 void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
349 sds buf
= sdsempty();
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
) {
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
;
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]);
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
);
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
));
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
));
398 /* ----------------------------------------------------------------------------
400 * ------------------------------------------------------------------------- */
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
));
409 c
->querybuf
= sdsempty();
410 c
->querybuf_peak
= 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();
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
);
428 void freeFakeClient(struct redisClient
*c
) {
429 sdsfree(c
->querybuf
);
430 listRelease(c
->reply
);
431 listRelease(c
->watched_keys
);
432 freeClientMultiState(c
);
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
;
446 if (fp
&& redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0) {
447 server
.aof_current_size
= 0;
453 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
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
;
461 fakeClient
= createFakeClient();
470 struct redisCommand
*cmd
;
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
);
478 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
484 if (buf
[0] != '*') goto fmterr
;
486 if (argc
< 1) goto fmterr
;
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 */
500 cmd
= lookupCommand(argv
[0]->ptr
);
502 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
505 /* Run the command in the context of a fake client */
506 fakeClient
->argc
= argc
;
507 fakeClient
->argv
= argv
;
508 cmd
->proc(fakeClient
);
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);
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
);
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
;
527 freeFakeClient(fakeClient
);
528 server
.aof_state
= old_aof_state
;
530 aofUpdateCurrentSize();
531 server
.aof_rewrite_base_size
= server
.aof_current_size
;
536 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
538 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
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>");
546 /* ----------------------------------------------------------------------------
548 * ------------------------------------------------------------------------- */
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
));
560 redisPanic("Unknown string encoding");
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
);
569 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
570 unsigned char *zl
= o
->ptr
;
571 unsigned char *p
= ziplistIndex(zl
,0);
576 while(ziplistGet(p
,&vstr
,&vlen
,&vlong
)) {
578 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
579 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
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;
586 if (rioWriteBulkString(r
,(char*)vstr
,vlen
) == 0) return 0;
588 if (rioWriteBulkLongLong(r
,vlong
) == 0) return 0;
590 p
= ziplistNext(zl
,p
);
591 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
594 } else if (o
->encoding
== REDIS_ENCODING_LINKEDLIST
) {
599 listRewind(list
,&li
);
600 while((ln
= listNext(&li
))) {
601 robj
*eleobj
= listNodeValue(ln
);
604 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
605 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
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;
611 if (rioWriteBulkObject(r
,eleobj
) == 0) return 0;
612 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
616 redisPanic("Unknown list encoding");
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
);
626 if (o
->encoding
== REDIS_ENCODING_INTSET
) {
630 while(intsetGet(o
->ptr
,ii
++,&llval
)) {
632 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
633 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
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;
639 if (rioWriteBulkLongLong(r
,llval
) == 0) return 0;
640 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
643 } else if (o
->encoding
== REDIS_ENCODING_HT
) {
644 dictIterator
*di
= dictGetIterator(o
->ptr
);
647 while((de
= dictNext(di
)) != NULL
) {
648 robj
*eleobj
= dictGetKey(de
);
650 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
651 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
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;
657 if (rioWriteBulkObject(r
,eleobj
) == 0) return 0;
658 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
661 dictReleaseIterator(di
);
663 redisPanic("Unknown set encoding");
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
);
673 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
674 unsigned char *zl
= o
->ptr
;
675 unsigned char *eptr
, *sptr
;
681 eptr
= ziplistIndex(zl
,0);
682 redisAssert(eptr
!= NULL
);
683 sptr
= ziplistNext(zl
,eptr
);
684 redisAssert(sptr
!= NULL
);
686 while (eptr
!= NULL
) {
687 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vll
));
688 score
= zzlGetScore(sptr
);
691 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
692 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
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;
698 if (rioWriteBulkDouble(r
,score
) == 0) return 0;
700 if (rioWriteBulkString(r
,(char*)vstr
,vlen
) == 0) return 0;
702 if (rioWriteBulkLongLong(r
,vll
) == 0) return 0;
704 zzlNext(zl
,&eptr
,&sptr
);
705 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
708 } else if (o
->encoding
== REDIS_ENCODING_SKIPLIST
) {
710 dictIterator
*di
= dictGetIterator(zs
->dict
);
713 while((de
= dictNext(di
)) != NULL
) {
714 robj
*eleobj
= dictGetKey(de
);
715 double *score
= dictGetVal(de
);
718 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
719 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
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;
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;
730 dictReleaseIterator(di
);
732 redisPanic("Unknown sorted zset encoding");
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.
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
;
749 hashTypeCurrentFromZiplist(hi
, what
, &vstr
, &vlen
, &vll
);
751 return rioWriteBulkString(r
, (char*)vstr
, vlen
);
753 return rioWriteBulkLongLong(r
, vll
);
756 } else if (hi
->encoding
== REDIS_ENCODING_HT
) {
759 hashTypeCurrentFromHashTable(hi
, what
, &value
);
760 return rioWriteBulkObject(r
, value
);
763 redisPanic("Unknown hash encoding");
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
);
773 hi
= hashTypeInitIterator(o
);
774 while (hashTypeNext(hi
) != REDIS_ERR
) {
776 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
777 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
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;
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;
790 hashTypeReleaseIterator(hi
);
795 /* Write a sequence of commands able to fully rebuild the dataset into
796 * "filename". Used both by REWRITEAOF and BGREWRITEAOF.
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
;
809 long long now
= mstime();
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");
816 redisLog(REDIS_WARNING
, "Opening the temp file for AOF rewrite in rewriteAppendOnlyFile(): %s", strerror(errno
));
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
;
825 if (dictSize(d
) == 0) continue;
826 di
= dictGetSafeIterator(d
);
832 /* SELECT the new DB */
833 if (rioWrite(&aof
,selectcmd
,sizeof(selectcmd
)-1) == 0) goto werr
;
834 if (rioWriteBulkLongLong(&aof
,j
) == 0) goto werr
;
836 /* Iterate this DB writing every entry */
837 while((de
= dictNext(di
)) != NULL
) {
840 long long expiretime
;
842 keystr
= dictGetKey(de
);
844 initStaticStringObject(key
,keystr
);
846 expiretime
= getExpire(db
,&key
);
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
;
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
;
865 redisPanic("Unknown object type");
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
;
877 dictReleaseIterator(di
);
880 /* Make sure data will not remain on the OS's output buffers */
882 aof_fsync(fileno(fp
));
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
));
892 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
898 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
899 if (di
) dictReleaseIterator(di
);
903 /* This is how rewriting of the append only file in background works:
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!
915 int rewriteAppendOnlyFileBackground(void) {
919 if (server
.aof_child_pid
!= -1) return REDIS_ERR
;
921 if ((childpid
= fork()) == 0) {
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
) {
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",
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;
955 return REDIS_OK
; /* unreached */
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");
967 addReply(c
,shared
.err
);
971 void aofRemoveTempFile(pid_t childpid
) {
974 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
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
;
985 if (redis_fstat(server
.aof_fd
,&sb
) == -1) {
986 redisLog(REDIS_WARNING
,"Unable to obtain the AOF file length. stat: %s",
989 server
.aof_current_size
= sb
.st_size
;
993 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
995 void backgroundRewriteDoneHandler(int exitcode
, int bysignal
) {
996 if (!bysignal
&& exitcode
== 0) {
999 long long now
= ustime();
1001 redisLog(REDIS_NOTICE
,
1002 "Background AOF rewrite terminated with success");
1004 /* Flush the differences accumulated by the parent to the
1006 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof",
1007 (int)server
.aof_child_pid
);
1008 newfd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
1010 redisLog(REDIS_WARNING
,
1011 "Unable to open the temporary AOF produced by the child: %s", strerror(errno
));
1015 if (aofRewriteBufferWrite(newfd
) == -1) {
1016 redisLog(REDIS_WARNING
,
1017 "Error trying to flush the parent diff to the rewritten AOF: %s", strerror(errno
));
1022 redisLog(REDIS_NOTICE
,
1023 "Parent diff successfully flushed to the rewritten AOF (%lu bytes)", aofRewriteBufferSize());
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.
1030 * There are two possible scenarios:
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.
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
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) {
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
1058 oldfd
= open(server
.aof_filename
,O_RDONLY
|O_NONBLOCK
);
1061 oldfd
= -1; /* We'll set this to the current AOF filedes later. */
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
));
1070 if (oldfd
!= -1) close(oldfd
);
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. */
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
)
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
;
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();
1096 server
.aof_lastbgrewrite_status
= REDIS_OK
;
1098 redisLog(REDIS_NOTICE
, "Background AOF rewrite finished successfully");
1099 /* Change state from WAIT_REWRITE to ON if needed */
1100 if (server
.aof_state
== REDIS_AOF_WAIT_REWRITE
)
1101 server
.aof_state
= REDIS_AOF_ON
;
1103 /* Asynchronously close the overwritten AOF. */
1104 if (oldfd
!= -1) bioCreateBackgroundJob(REDIS_BIO_CLOSE_FILE
,(void*)(long)oldfd
,NULL
,NULL
);
1106 redisLog(REDIS_VERBOSE
,
1107 "Background AOF rewrite signal handler took %lldus", ustime()-now
);
1108 } else if (!bysignal
&& exitcode
!= 0) {
1109 server
.aof_lastbgrewrite_status
= REDIS_ERR
;
1111 redisLog(REDIS_WARNING
,
1112 "Background AOF rewrite terminated with error");
1114 server
.aof_lastbgrewrite_status
= REDIS_ERR
;
1116 redisLog(REDIS_WARNING
,
1117 "Background AOF rewrite terminated by signal %d", bysignal
);
1121 aofRewriteBufferReset();
1122 aofRemoveTempFile(server
.aof_child_pid
);
1123 server
.aof_child_pid
= -1;
1124 server
.aof_rewrite_time_last
= time(NULL
)-server
.aof_rewrite_time_start
;
1125 server
.aof_rewrite_time_start
= -1;
1126 /* Schedule a new rewrite if we are waiting for it to switch the AOF ON. */
1127 if (server
.aof_state
== REDIS_AOF_WAIT_REWRITE
)
1128 server
.aof_rewrite_scheduled
= 1;