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;
160 /* Called when the user switches from "appendonly no" to "appendonly yes"
161 * at runtime using the CONFIG command. */
162 int startAppendOnly(void) {
163 server
.aof_last_fsync
= server
.unixtime
;
164 server
.aof_fd
= open(server
.aof_filename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
165 redisAssert(server
.aof_state
== REDIS_AOF_OFF
);
166 if (server
.aof_fd
== -1) {
167 redisLog(REDIS_WARNING
,"Redis needs to enable the AOF but can't open the append only file: %s",strerror(errno
));
170 if (rewriteAppendOnlyFileBackground() == REDIS_ERR
) {
171 close(server
.aof_fd
);
172 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.");
175 /* We correctly switched on AOF, now wait for the rerwite to be complete
176 * in order to append data on disk. */
177 server
.aof_state
= REDIS_AOF_WAIT_REWRITE
;
181 /* Write the append only file buffer on disk.
183 * Since we are required to write the AOF before replying to the client,
184 * and the only way the client socket can get a write is entering when the
185 * the event loop, we accumulate all the AOF writes in a memory
186 * buffer and write it on disk using this function just before entering
187 * the event loop again.
189 * About the 'force' argument:
191 * When the fsync policy is set to 'everysec' we may delay the flush if there
192 * is still an fsync() going on in the background thread, since for instance
193 * on Linux write(2) will be blocked by the background fsync anyway.
194 * When this happens we remember that there is some aof buffer to be
195 * flushed ASAP, and will try to do that in the serverCron() function.
197 * However if force is set to 1 we'll write regardless of the background
199 void flushAppendOnlyFile(int force
) {
201 int sync_in_progress
= 0;
203 if (sdslen(server
.aof_buf
) == 0) return;
205 if (server
.aof_fsync
== AOF_FSYNC_EVERYSEC
)
206 sync_in_progress
= bioPendingJobsOfType(REDIS_BIO_AOF_FSYNC
) != 0;
208 if (server
.aof_fsync
== AOF_FSYNC_EVERYSEC
&& !force
) {
209 /* With this append fsync policy we do background fsyncing.
210 * If the fsync is still in progress we can try to delay
211 * the write for a couple of seconds. */
212 if (sync_in_progress
) {
213 if (server
.aof_flush_postponed_start
== 0) {
214 /* No previous write postponinig, remember that we are
215 * postponing the flush and return. */
216 server
.aof_flush_postponed_start
= server
.unixtime
;
218 } else if (server
.unixtime
- server
.aof_flush_postponed_start
< 2) {
219 /* We were already waiting for fsync to finish, but for less
220 * than two seconds this is still ok. Postpone again. */
223 /* Otherwise fall trough, and go write since we can't wait
224 * over two seconds. */
225 server
.aof_delayed_fsync
++;
226 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.");
229 /* If you are following this code path, then we are going to write so
230 * set reset the postponed flush sentinel to zero. */
231 server
.aof_flush_postponed_start
= 0;
233 /* We want to perform a single write. This should be guaranteed atomic
234 * at least if the filesystem we are writing is a real physical one.
235 * While this will save us against the server being killed I don't think
236 * there is much to do about the whole server stopping for power problems
238 nwritten
= write(server
.aof_fd
,server
.aof_buf
,sdslen(server
.aof_buf
));
239 if (nwritten
!= (signed)sdslen(server
.aof_buf
)) {
240 /* Ooops, we are in troubles. The best thing to do for now is
241 * aborting instead of giving the illusion that everything is
242 * working as expected. */
243 if (nwritten
== -1) {
244 redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
));
246 redisLog(REDIS_WARNING
,"Exiting on short write while writing to "
247 "the append-only file: %s (nwritten=%ld, "
251 (long)sdslen(server
.aof_buf
));
255 server
.aof_current_size
+= nwritten
;
257 /* Re-use AOF buffer when it is small enough. The maximum comes from the
258 * arena size of 4k minus some overhead (but is otherwise arbitrary). */
259 if ((sdslen(server
.aof_buf
)+sdsavail(server
.aof_buf
)) < 4000) {
260 sdsclear(server
.aof_buf
);
262 sdsfree(server
.aof_buf
);
263 server
.aof_buf
= sdsempty();
266 /* Don't fsync if no-appendfsync-on-rewrite is set to yes and there are
267 * children doing I/O in the background. */
268 if (server
.aof_no_fsync_on_rewrite
&&
269 (server
.aof_child_pid
!= -1 || server
.rdb_child_pid
!= -1))
272 /* Perform the fsync if needed. */
273 if (server
.aof_fsync
== AOF_FSYNC_ALWAYS
) {
274 /* aof_fsync is defined as fdatasync() for Linux in order to avoid
275 * flushing metadata. */
276 aof_fsync(server
.aof_fd
); /* Let's try to get this data on the disk */
277 server
.aof_last_fsync
= server
.unixtime
;
278 } else if ((server
.aof_fsync
== AOF_FSYNC_EVERYSEC
&&
279 server
.unixtime
> server
.aof_last_fsync
)) {
280 if (!sync_in_progress
) aof_background_fsync(server
.aof_fd
);
281 server
.aof_last_fsync
= server
.unixtime
;
285 sds
catAppendOnlyGenericCommand(sds dst
, int argc
, robj
**argv
) {
291 len
= 1+ll2string(buf
+1,sizeof(buf
)-1,argc
);
294 dst
= sdscatlen(dst
,buf
,len
);
296 for (j
= 0; j
< argc
; j
++) {
297 o
= getDecodedObject(argv
[j
]);
299 len
= 1+ll2string(buf
+1,sizeof(buf
)-1,sdslen(o
->ptr
));
302 dst
= sdscatlen(dst
,buf
,len
);
303 dst
= sdscatlen(dst
,o
->ptr
,sdslen(o
->ptr
));
304 dst
= sdscatlen(dst
,"\r\n",2);
310 /* Create the sds representation of an PEXPIREAT command, using
311 * 'seconds' as time to live and 'cmd' to understand what command
312 * we are translating into a PEXPIREAT.
314 * This command is used in order to translate EXPIRE and PEXPIRE commands
315 * into PEXPIREAT command so that we retain precision in the append only
316 * file, and the time is always absolute and not relative. */
317 sds
catAppendOnlyExpireAtCommand(sds buf
, struct redisCommand
*cmd
, robj
*key
, robj
*seconds
) {
321 /* Make sure we can use strtol */
322 seconds
= getDecodedObject(seconds
);
323 when
= strtoll(seconds
->ptr
,NULL
,10);
324 /* Convert argument into milliseconds for EXPIRE, SETEX, EXPIREAT */
325 if (cmd
->proc
== expireCommand
|| cmd
->proc
== setexCommand
||
326 cmd
->proc
== expireatCommand
)
330 /* Convert into absolute time for EXPIRE, PEXPIRE, SETEX, PSETEX */
331 if (cmd
->proc
== expireCommand
|| cmd
->proc
== pexpireCommand
||
332 cmd
->proc
== setexCommand
|| cmd
->proc
== psetexCommand
)
336 decrRefCount(seconds
);
338 argv
[0] = createStringObject("PEXPIREAT",9);
340 argv
[2] = createStringObjectFromLongLong(when
);
341 buf
= catAppendOnlyGenericCommand(buf
, 3, argv
);
342 decrRefCount(argv
[0]);
343 decrRefCount(argv
[2]);
347 void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
348 sds buf
= sdsempty();
351 /* The DB this command was targetting is not the same as the last command
352 * we appendend. To issue a SELECT command is needed. */
353 if (dictid
!= server
.aof_selected_db
) {
356 snprintf(seldb
,sizeof(seldb
),"%d",dictid
);
357 buf
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
358 (unsigned long)strlen(seldb
),seldb
);
359 server
.aof_selected_db
= dictid
;
362 if (cmd
->proc
== expireCommand
|| cmd
->proc
== pexpireCommand
||
363 cmd
->proc
== expireatCommand
) {
364 /* Translate EXPIRE/PEXPIRE/EXPIREAT into PEXPIREAT */
365 buf
= catAppendOnlyExpireAtCommand(buf
,cmd
,argv
[1],argv
[2]);
366 } else if (cmd
->proc
== setexCommand
|| cmd
->proc
== psetexCommand
) {
367 /* Translate SETEX/PSETEX to SET and PEXPIREAT */
368 tmpargv
[0] = createStringObject("SET",3);
369 tmpargv
[1] = argv
[1];
370 tmpargv
[2] = argv
[3];
371 buf
= catAppendOnlyGenericCommand(buf
,3,tmpargv
);
372 decrRefCount(tmpargv
[0]);
373 buf
= catAppendOnlyExpireAtCommand(buf
,cmd
,argv
[1],argv
[2]);
375 /* All the other commands don't need translation or need the
376 * same translation already operated in the command vector
377 * for the replication itself. */
378 buf
= catAppendOnlyGenericCommand(buf
,argc
,argv
);
381 /* Append to the AOF buffer. This will be flushed on disk just before
382 * of re-entering the event loop, so before the client will get a
383 * positive reply about the operation performed. */
384 if (server
.aof_state
== REDIS_AOF_ON
)
385 server
.aof_buf
= sdscatlen(server
.aof_buf
,buf
,sdslen(buf
));
387 /* If a background append only file rewriting is in progress we want to
388 * accumulate the differences between the child DB and the current one
389 * in a buffer, so that when the child process will do its work we
390 * can append the differences to the new append only file. */
391 if (server
.aof_child_pid
!= -1)
392 aofRewriteBufferAppend((unsigned char*)buf
,sdslen(buf
));
397 /* ----------------------------------------------------------------------------
399 * ------------------------------------------------------------------------- */
401 /* In Redis commands are always executed in the context of a client, so in
402 * order to load the append only file we need to create a fake client. */
403 struct redisClient
*createFakeClient(void) {
404 struct redisClient
*c
= zmalloc(sizeof(*c
));
408 c
->querybuf
= sdsempty();
409 c
->querybuf_peak
= 0;
414 /* We set the fake client as a slave waiting for the synchronization
415 * so that Redis will not try to send replies to this client. */
416 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
417 c
->reply
= listCreate();
419 c
->obuf_soft_limit_reached_time
= 0;
420 c
->watched_keys
= listCreate();
421 listSetFreeMethod(c
->reply
,decrRefCount
);
422 listSetDupMethod(c
->reply
,dupClientReplyValue
);
423 initClientMultiState(c
);
427 void freeFakeClient(struct redisClient
*c
) {
428 sdsfree(c
->querybuf
);
429 listRelease(c
->reply
);
430 listRelease(c
->watched_keys
);
431 freeClientMultiState(c
);
435 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
436 * error (the append only file is zero-length) REDIS_ERR is returned. On
437 * fatal error an error message is logged and the program exists. */
438 int loadAppendOnlyFile(char *filename
) {
439 struct redisClient
*fakeClient
;
440 FILE *fp
= fopen(filename
,"r");
441 struct redis_stat sb
;
442 int old_aof_state
= server
.aof_state
;
445 if (fp
&& redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0) {
446 server
.aof_current_size
= 0;
452 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
456 /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
457 * to the same file we're about to read. */
458 server
.aof_state
= REDIS_AOF_OFF
;
460 fakeClient
= createFakeClient();
469 struct redisCommand
*cmd
;
471 /* Serve the clients from time to time */
472 if (!(loops
++ % 1000)) {
473 loadingProgress(ftello(fp
));
474 aeProcessEvents(server
.el
, AE_FILE_EVENTS
|AE_DONT_WAIT
);
477 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
483 if (buf
[0] != '*') goto fmterr
;
485 if (argc
< 1) goto fmterr
;
487 argv
= zmalloc(sizeof(robj
*)*argc
);
488 for (j
= 0; j
< argc
; j
++) {
489 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
490 if (buf
[0] != '$') goto fmterr
;
491 len
= strtol(buf
+1,NULL
,10);
492 argsds
= sdsnewlen(NULL
,len
);
493 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
494 argv
[j
] = createObject(REDIS_STRING
,argsds
);
495 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
499 cmd
= lookupCommand(argv
[0]->ptr
);
501 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
504 /* Run the command in the context of a fake client */
505 fakeClient
->argc
= argc
;
506 fakeClient
->argv
= argv
;
507 cmd
->proc(fakeClient
);
509 /* The fake client should not have a reply */
510 redisAssert(fakeClient
->bufpos
== 0 && listLength(fakeClient
->reply
) == 0);
511 /* The fake client should never get blocked */
512 redisAssert((fakeClient
->flags
& REDIS_BLOCKED
) == 0);
514 /* Clean up. Command code may have changed argv/argc so we use the
515 * argv/argc of the client instead of the local variables. */
516 for (j
= 0; j
< fakeClient
->argc
; j
++)
517 decrRefCount(fakeClient
->argv
[j
]);
518 zfree(fakeClient
->argv
);
521 /* This point can only be reached when EOF is reached without errors.
522 * If the client is in the middle of a MULTI/EXEC, log error and quit. */
523 if (fakeClient
->flags
& REDIS_MULTI
) goto readerr
;
526 freeFakeClient(fakeClient
);
527 server
.aof_state
= old_aof_state
;
529 aofUpdateCurrentSize();
530 server
.aof_rewrite_base_size
= server
.aof_current_size
;
535 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
537 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
541 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>");
545 /* ----------------------------------------------------------------------------
547 * ------------------------------------------------------------------------- */
549 /* Delegate writing an object to writing a bulk string or bulk long long.
550 * This is not placed in rio.c since that adds the redis.h dependency. */
551 int rioWriteBulkObject(rio
*r
, robj
*obj
) {
552 /* Avoid using getDecodedObject to help copy-on-write (we are often
553 * in a child process when this function is called). */
554 if (obj
->encoding
== REDIS_ENCODING_INT
) {
555 return rioWriteBulkLongLong(r
,(long)obj
->ptr
);
556 } else if (obj
->encoding
== REDIS_ENCODING_RAW
) {
557 return rioWriteBulkString(r
,obj
->ptr
,sdslen(obj
->ptr
));
559 redisPanic("Unknown string encoding");
563 /* Emit the commands needed to rebuild a list object.
564 * The function returns 0 on error, 1 on success. */
565 int rewriteListObject(rio
*r
, robj
*key
, robj
*o
) {
566 long long count
= 0, items
= listTypeLength(o
);
568 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
569 unsigned char *zl
= o
->ptr
;
570 unsigned char *p
= ziplistIndex(zl
,0);
575 while(ziplistGet(p
,&vstr
,&vlen
,&vlong
)) {
577 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
578 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
580 if (rioWriteBulkCount(r
,'*',2+cmd_items
) == 0) return 0;
581 if (rioWriteBulkString(r
,"RPUSH",5) == 0) return 0;
582 if (rioWriteBulkObject(r
,key
) == 0) return 0;
585 if (rioWriteBulkString(r
,(char*)vstr
,vlen
) == 0) return 0;
587 if (rioWriteBulkLongLong(r
,vlong
) == 0) return 0;
589 p
= ziplistNext(zl
,p
);
590 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
593 } else if (o
->encoding
== REDIS_ENCODING_LINKEDLIST
) {
598 listRewind(list
,&li
);
599 while((ln
= listNext(&li
))) {
600 robj
*eleobj
= listNodeValue(ln
);
603 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
604 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
606 if (rioWriteBulkCount(r
,'*',2+cmd_items
) == 0) return 0;
607 if (rioWriteBulkString(r
,"RPUSH",5) == 0) return 0;
608 if (rioWriteBulkObject(r
,key
) == 0) return 0;
610 if (rioWriteBulkObject(r
,eleobj
) == 0) return 0;
611 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
615 redisPanic("Unknown list encoding");
620 /* Emit the commands needed to rebuild a set object.
621 * The function returns 0 on error, 1 on success. */
622 int rewriteSetObject(rio
*r
, robj
*key
, robj
*o
) {
623 long long count
= 0, items
= setTypeSize(o
);
625 if (o
->encoding
== REDIS_ENCODING_INTSET
) {
629 while(intsetGet(o
->ptr
,ii
++,&llval
)) {
631 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
632 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
634 if (rioWriteBulkCount(r
,'*',2+cmd_items
) == 0) return 0;
635 if (rioWriteBulkString(r
,"SADD",4) == 0) return 0;
636 if (rioWriteBulkObject(r
,key
) == 0) return 0;
638 if (rioWriteBulkLongLong(r
,llval
) == 0) return 0;
639 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
642 } else if (o
->encoding
== REDIS_ENCODING_HT
) {
643 dictIterator
*di
= dictGetIterator(o
->ptr
);
646 while((de
= dictNext(di
)) != NULL
) {
647 robj
*eleobj
= dictGetKey(de
);
649 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
650 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
652 if (rioWriteBulkCount(r
,'*',2+cmd_items
) == 0) return 0;
653 if (rioWriteBulkString(r
,"SADD",4) == 0) return 0;
654 if (rioWriteBulkObject(r
,key
) == 0) return 0;
656 if (rioWriteBulkObject(r
,eleobj
) == 0) return 0;
657 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
660 dictReleaseIterator(di
);
662 redisPanic("Unknown set encoding");
667 /* Emit the commands needed to rebuild a sorted set object.
668 * The function returns 0 on error, 1 on success. */
669 int rewriteSortedSetObject(rio
*r
, robj
*key
, robj
*o
) {
670 long long count
= 0, items
= zsetLength(o
);
672 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
673 unsigned char *zl
= o
->ptr
;
674 unsigned char *eptr
, *sptr
;
680 eptr
= ziplistIndex(zl
,0);
681 redisAssert(eptr
!= NULL
);
682 sptr
= ziplistNext(zl
,eptr
);
683 redisAssert(sptr
!= NULL
);
685 while (eptr
!= NULL
) {
686 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vll
));
687 score
= zzlGetScore(sptr
);
690 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
691 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
693 if (rioWriteBulkCount(r
,'*',2+cmd_items
*2) == 0) return 0;
694 if (rioWriteBulkString(r
,"ZADD",4) == 0) return 0;
695 if (rioWriteBulkObject(r
,key
) == 0) return 0;
697 if (rioWriteBulkDouble(r
,score
) == 0) return 0;
699 if (rioWriteBulkString(r
,(char*)vstr
,vlen
) == 0) return 0;
701 if (rioWriteBulkLongLong(r
,vll
) == 0) return 0;
703 zzlNext(zl
,&eptr
,&sptr
);
704 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
707 } else if (o
->encoding
== REDIS_ENCODING_SKIPLIST
) {
709 dictIterator
*di
= dictGetIterator(zs
->dict
);
712 while((de
= dictNext(di
)) != NULL
) {
713 robj
*eleobj
= dictGetKey(de
);
714 double *score
= dictGetVal(de
);
717 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
718 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
720 if (rioWriteBulkCount(r
,'*',2+cmd_items
*2) == 0) return 0;
721 if (rioWriteBulkString(r
,"ZADD",4) == 0) return 0;
722 if (rioWriteBulkObject(r
,key
) == 0) return 0;
724 if (rioWriteBulkDouble(r
,*score
) == 0) return 0;
725 if (rioWriteBulkObject(r
,eleobj
) == 0) return 0;
726 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
729 dictReleaseIterator(di
);
731 redisPanic("Unknown sorted zset encoding");
736 /* Write either the key or the value of the currently selected item of an hash.
737 * The 'hi' argument passes a valid Redis hash iterator.
738 * The 'what' filed specifies if to write a key or a value and can be
739 * either REDIS_HASH_KEY or REDIS_HASH_VALUE.
741 * The function returns 0 on error, non-zero on success. */
742 static int rioWriteHashIteratorCursor(rio
*r
, hashTypeIterator
*hi
, int what
) {
743 if (hi
->encoding
== REDIS_ENCODING_ZIPLIST
) {
744 unsigned char *vstr
= NULL
;
745 unsigned int vlen
= UINT_MAX
;
746 long long vll
= LLONG_MAX
;
748 hashTypeCurrentFromZiplist(hi
, what
, &vstr
, &vlen
, &vll
);
750 return rioWriteBulkString(r
, (char*)vstr
, vlen
);
752 return rioWriteBulkLongLong(r
, vll
);
755 } else if (hi
->encoding
== REDIS_ENCODING_HT
) {
758 hashTypeCurrentFromHashTable(hi
, what
, &value
);
759 return rioWriteBulkObject(r
, value
);
762 redisPanic("Unknown hash encoding");
766 /* Emit the commands needed to rebuild a hash object.
767 * The function returns 0 on error, 1 on success. */
768 int rewriteHashObject(rio
*r
, robj
*key
, robj
*o
) {
769 hashTypeIterator
*hi
;
770 long long count
= 0, items
= hashTypeLength(o
);
772 hi
= hashTypeInitIterator(o
);
773 while (hashTypeNext(hi
) != REDIS_ERR
) {
775 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
776 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
778 if (rioWriteBulkCount(r
,'*',2+cmd_items
*2) == 0) return 0;
779 if (rioWriteBulkString(r
,"HMSET",5) == 0) return 0;
780 if (rioWriteBulkObject(r
,key
) == 0) return 0;
783 if (rioWriteHashIteratorCursor(r
, hi
, REDIS_HASH_KEY
) == 0) return 0;
784 if (rioWriteHashIteratorCursor(r
, hi
, REDIS_HASH_VALUE
) == 0) return 0;
785 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
789 hashTypeReleaseIterator(hi
);
794 /* Write a sequence of commands able to fully rebuild the dataset into
795 * "filename". Used both by REWRITEAOF and BGREWRITEAOF.
797 * In order to minimize the number of commands needed in the rewritten
798 * log Redis uses variadic commands when possible, such as RPUSH, SADD
799 * and ZADD. However at max REDIS_AOF_REWRITE_ITEMS_PER_CMD items per time
800 * are inserted using a single command. */
801 int rewriteAppendOnlyFile(char *filename
) {
802 dictIterator
*di
= NULL
;
808 long long now
= mstime();
810 /* Note that we have to use a different temp name here compared to the
811 * one used by rewriteAppendOnlyFileBackground() function. */
812 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
813 fp
= fopen(tmpfile
,"w");
815 redisLog(REDIS_WARNING
, "Opening the temp file for AOF rewrite in rewriteAppendOnlyFile(): %s", strerror(errno
));
819 rioInitWithFile(&aof
,fp
);
820 for (j
= 0; j
< server
.dbnum
; j
++) {
821 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
822 redisDb
*db
= server
.db
+j
;
824 if (dictSize(d
) == 0) continue;
825 di
= dictGetSafeIterator(d
);
831 /* SELECT the new DB */
832 if (rioWrite(&aof
,selectcmd
,sizeof(selectcmd
)-1) == 0) goto werr
;
833 if (rioWriteBulkLongLong(&aof
,j
) == 0) goto werr
;
835 /* Iterate this DB writing every entry */
836 while((de
= dictNext(di
)) != NULL
) {
839 long long expiretime
;
841 keystr
= dictGetKey(de
);
843 initStaticStringObject(key
,keystr
);
845 expiretime
= getExpire(db
,&key
);
847 /* Save the key and associated value */
848 if (o
->type
== REDIS_STRING
) {
849 /* Emit a SET command */
850 char cmd
[]="*3\r\n$3\r\nSET\r\n";
851 if (rioWrite(&aof
,cmd
,sizeof(cmd
)-1) == 0) goto werr
;
853 if (rioWriteBulkObject(&aof
,&key
) == 0) goto werr
;
854 if (rioWriteBulkObject(&aof
,o
) == 0) goto werr
;
855 } else if (o
->type
== REDIS_LIST
) {
856 if (rewriteListObject(&aof
,&key
,o
) == 0) goto werr
;
857 } else if (o
->type
== REDIS_SET
) {
858 if (rewriteSetObject(&aof
,&key
,o
) == 0) goto werr
;
859 } else if (o
->type
== REDIS_ZSET
) {
860 if (rewriteSortedSetObject(&aof
,&key
,o
) == 0) goto werr
;
861 } else if (o
->type
== REDIS_HASH
) {
862 if (rewriteHashObject(&aof
,&key
,o
) == 0) goto werr
;
864 redisPanic("Unknown object type");
866 /* Save the expire time */
867 if (expiretime
!= -1) {
868 char cmd
[]="*3\r\n$9\r\nPEXPIREAT\r\n";
869 /* If this key is already expired skip it */
870 if (expiretime
< now
) continue;
871 if (rioWrite(&aof
,cmd
,sizeof(cmd
)-1) == 0) goto werr
;
872 if (rioWriteBulkObject(&aof
,&key
) == 0) goto werr
;
873 if (rioWriteBulkLongLong(&aof
,expiretime
) == 0) goto werr
;
876 dictReleaseIterator(di
);
879 /* Make sure data will not remain on the OS's output buffers */
881 aof_fsync(fileno(fp
));
884 /* Use RENAME to make sure the DB file is changed atomically only
885 * if the generate DB file is ok. */
886 if (rename(tmpfile
,filename
) == -1) {
887 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
891 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
897 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
898 if (di
) dictReleaseIterator(di
);
902 /* This is how rewriting of the append only file in background works:
904 * 1) The user calls BGREWRITEAOF
905 * 2) Redis calls this function, that forks():
906 * 2a) the child rewrite the append only file in a temp file.
907 * 2b) the parent accumulates differences in server.aof_rewrite_buf.
908 * 3) When the child finished '2a' exists.
909 * 4) The parent will trap the exit code, if it's OK, will append the
910 * data accumulated into server.aof_rewrite_buf into the temp file, and
911 * finally will rename(2) the temp file in the actual file name.
912 * The the new file is reopened as the new append only file. Profit!
914 int rewriteAppendOnlyFileBackground(void) {
918 if (server
.aof_child_pid
!= -1) return REDIS_ERR
;
920 if ((childpid
= fork()) == 0) {
924 if (server
.ipfd
> 0) close(server
.ipfd
);
925 if (server
.sofd
> 0) close(server
.sofd
);
926 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
927 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
934 server
.stat_fork_time
= ustime()-start
;
935 if (childpid
== -1) {
936 redisLog(REDIS_WARNING
,
937 "Can't rewrite append only file in background: fork: %s",
941 redisLog(REDIS_NOTICE
,
942 "Background append only file rewriting started by pid %d",childpid
);
943 server
.aof_rewrite_scheduled
= 0;
944 server
.aof_child_pid
= childpid
;
945 updateDictResizePolicy();
946 /* We set appendseldb to -1 in order to force the next call to the
947 * feedAppendOnlyFile() to issue a SELECT command, so the differences
948 * accumulated by the parent into server.aof_rewrite_buf will start
949 * with a SELECT statement and it will be safe to merge. */
950 server
.aof_selected_db
= -1;
953 return REDIS_OK
; /* unreached */
956 void bgrewriteaofCommand(redisClient
*c
) {
957 if (server
.aof_child_pid
!= -1) {
958 addReplyError(c
,"Background append only file rewriting already in progress");
959 } else if (server
.rdb_child_pid
!= -1) {
960 server
.aof_rewrite_scheduled
= 1;
961 addReplyStatus(c
,"Background append only file rewriting scheduled");
962 } else if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
963 addReplyStatus(c
,"Background append only file rewriting started");
965 addReply(c
,shared
.err
);
969 void aofRemoveTempFile(pid_t childpid
) {
972 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
976 /* Update the server.aof_current_size filed explicitly using stat(2)
977 * to check the size of the file. This is useful after a rewrite or after
978 * a restart, normally the size is updated just adding the write length
979 * to the current length, that is much faster. */
980 void aofUpdateCurrentSize(void) {
981 struct redis_stat sb
;
983 if (redis_fstat(server
.aof_fd
,&sb
) == -1) {
984 redisLog(REDIS_WARNING
,"Unable to obtain the AOF file length. stat: %s",
987 server
.aof_current_size
= sb
.st_size
;
991 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
993 void backgroundRewriteDoneHandler(int exitcode
, int bysignal
) {
994 if (!bysignal
&& exitcode
== 0) {
997 long long now
= ustime();
999 redisLog(REDIS_NOTICE
,
1000 "Background AOF rewrite terminated with success");
1002 /* Flush the differences accumulated by the parent to the
1004 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof",
1005 (int)server
.aof_child_pid
);
1006 newfd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
1008 redisLog(REDIS_WARNING
,
1009 "Unable to open the temporary AOF produced by the child: %s", strerror(errno
));
1013 if (aofRewriteBufferWrite(newfd
) == -1) {
1014 redisLog(REDIS_WARNING
,
1015 "Error trying to flush the parent diff to the rewritten AOF: %s", strerror(errno
));
1020 redisLog(REDIS_NOTICE
,
1021 "Parent diff successfully flushed to the rewritten AOF (%lu bytes)", aofRewriteBufferSize());
1023 /* The only remaining thing to do is to rename the temporary file to
1024 * the configured file and switch the file descriptor used to do AOF
1025 * writes. We don't want close(2) or rename(2) calls to block the
1026 * server on old file deletion.
1028 * There are two possible scenarios:
1030 * 1) AOF is DISABLED and this was a one time rewrite. The temporary
1031 * file will be renamed to the configured file. When this file already
1032 * exists, it will be unlinked, which may block the server.
1034 * 2) AOF is ENABLED and the rewritten AOF will immediately start
1035 * receiving writes. After the temporary file is renamed to the
1036 * configured file, the original AOF file descriptor will be closed.
1037 * Since this will be the last reference to that file, closing it
1038 * causes the underlying file to be unlinked, which may block the
1041 * To mitigate the blocking effect of the unlink operation (either
1042 * caused by rename(2) in scenario 1, or by close(2) in scenario 2), we
1043 * use a background thread to take care of this. First, we
1044 * make scenario 1 identical to scenario 2 by opening the target file
1045 * when it exists. The unlink operation after the rename(2) will then
1046 * be executed upon calling close(2) for its descriptor. Everything to
1047 * guarantee atomicity for this switch has already happened by then, so
1048 * we don't care what the outcome or duration of that close operation
1049 * is, as long as the file descriptor is released again. */
1050 if (server
.aof_fd
== -1) {
1053 /* Don't care if this fails: oldfd will be -1 and we handle that.
1054 * One notable case of -1 return is if the old file does
1056 oldfd
= open(server
.aof_filename
,O_RDONLY
|O_NONBLOCK
);
1059 oldfd
= -1; /* We'll set this to the current AOF filedes later. */
1062 /* Rename the temporary file. This will not unlink the target file if
1063 * it exists, because we reference it with "oldfd". */
1064 if (rename(tmpfile
,server
.aof_filename
) == -1) {
1065 redisLog(REDIS_WARNING
,
1066 "Error trying to rename the temporary AOF file: %s", strerror(errno
));
1068 if (oldfd
!= -1) close(oldfd
);
1072 if (server
.aof_fd
== -1) {
1073 /* AOF disabled, we don't need to set the AOF file descriptor
1074 * to this new file, so we can close it. */
1077 /* AOF enabled, replace the old fd with the new one. */
1078 oldfd
= server
.aof_fd
;
1079 server
.aof_fd
= newfd
;
1080 if (server
.aof_fsync
== AOF_FSYNC_ALWAYS
)
1082 else if (server
.aof_fsync
== AOF_FSYNC_EVERYSEC
)
1083 aof_background_fsync(newfd
);
1084 server
.aof_selected_db
= -1; /* Make sure SELECT is re-issued */
1085 aofUpdateCurrentSize();
1086 server
.aof_rewrite_base_size
= server
.aof_current_size
;
1088 /* Clear regular AOF buffer since its contents was just written to
1089 * the new AOF from the background rewrite buffer. */
1090 sdsfree(server
.aof_buf
);
1091 server
.aof_buf
= sdsempty();
1094 redisLog(REDIS_NOTICE
, "Background AOF rewrite finished successfully");
1095 /* Change state from WAIT_REWRITE to ON if needed */
1096 if (server
.aof_state
== REDIS_AOF_WAIT_REWRITE
)
1097 server
.aof_state
= REDIS_AOF_ON
;
1099 /* Asynchronously close the overwritten AOF. */
1100 if (oldfd
!= -1) bioCreateBackgroundJob(REDIS_BIO_CLOSE_FILE
,(void*)(long)oldfd
,NULL
,NULL
);
1102 redisLog(REDIS_VERBOSE
,
1103 "Background AOF rewrite signal handler took %lldus", ustime()-now
);
1104 } else if (!bysignal
&& exitcode
!= 0) {
1105 redisLog(REDIS_WARNING
,
1106 "Background AOF rewrite terminated with error");
1108 redisLog(REDIS_WARNING
,
1109 "Background AOF rewrite terminated by signal %d", bysignal
);
1113 aofRewriteBufferReset();
1114 aofRemoveTempFile(server
.aof_child_pid
);
1115 server
.aof_child_pid
= -1;
1116 /* Schedule a new rewrite if we are waiting for it to switch the AOF ON. */
1117 if (server
.aof_state
== REDIS_AOF_WAIT_REWRITE
)
1118 server
.aof_rewrite_scheduled
= 1;