10 #include <sys/resource.h>
13 void aofUpdateCurrentSize(void);
15 void aof_background_fsync(int fd
) {
16 bioCreateBackgroundJob(REDIS_BIO_AOF_FSYNC
,(void*)(long)fd
,NULL
,NULL
);
19 /* Called when the user switches from "appendonly yes" to "appendonly no"
20 * at runtime using the CONFIG command. */
21 void stopAppendOnly(void) {
22 redisAssert(server
.aof_state
!= REDIS_AOF_OFF
);
23 flushAppendOnlyFile(1);
24 aof_fsync(server
.aof_fd
);
28 server
.aof_selected_db
= -1;
29 server
.aof_state
= REDIS_AOF_OFF
;
30 /* rewrite operation in progress? kill it, wait child exit */
31 if (server
.aof_child_pid
!= -1) {
34 redisLog(REDIS_NOTICE
,"Killing running AOF rewrite child: %ld",
35 (long) server
.aof_child_pid
);
36 if (kill(server
.aof_child_pid
,SIGKILL
) != -1)
37 wait3(&statloc
,0,NULL
);
38 /* reset the buffer accumulating changes while the child saves */
39 sdsfree(server
.aof_rewrite_buf
);
40 server
.aof_rewrite_buf
= sdsempty();
41 aofRemoveTempFile(server
.aof_child_pid
);
42 server
.aof_child_pid
= -1;
46 /* Called when the user switches from "appendonly no" to "appendonly yes"
47 * at runtime using the CONFIG command. */
48 int startAppendOnly(void) {
49 server
.aof_last_fsync
= time(NULL
);
50 server
.aof_fd
= open(server
.aof_filename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
51 redisAssert(server
.aof_state
== REDIS_AOF_OFF
);
52 if (server
.aof_fd
== -1) {
53 redisLog(REDIS_WARNING
,"Redis needs to enable the AOF but can't open the append only file: %s",strerror(errno
));
56 if (rewriteAppendOnlyFileBackground() == REDIS_ERR
) {
58 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.");
61 /* We correctly switched on AOF, now wait for the rerwite to be complete
62 * in order to append data on disk. */
63 server
.aof_state
= REDIS_AOF_WAIT_REWRITE
;
67 /* Write the append only file buffer on disk.
69 * Since we are required to write the AOF before replying to the client,
70 * and the only way the client socket can get a write is entering when the
71 * the event loop, we accumulate all the AOF writes in a memory
72 * buffer and write it on disk using this function just before entering
73 * the event loop again.
75 * About the 'force' argument:
77 * When the fsync policy is set to 'everysec' we may delay the flush if there
78 * is still an fsync() going on in the background thread, since for instance
79 * on Linux write(2) will be blocked by the background fsync anyway.
80 * When this happens we remember that there is some aof buffer to be
81 * flushed ASAP, and will try to do that in the serverCron() function.
83 * However if force is set to 1 we'll write regardless of the background
85 void flushAppendOnlyFile(int force
) {
87 int sync_in_progress
= 0;
89 if (sdslen(server
.aof_buf
) == 0) return;
91 if (server
.aof_fsync
== AOF_FSYNC_EVERYSEC
)
92 sync_in_progress
= bioPendingJobsOfType(REDIS_BIO_AOF_FSYNC
) != 0;
94 if (server
.aof_fsync
== AOF_FSYNC_EVERYSEC
&& !force
) {
95 /* With this append fsync policy we do background fsyncing.
96 * If the fsync is still in progress we can try to delay
97 * the write for a couple of seconds. */
98 if (sync_in_progress
) {
99 if (server
.aof_flush_postponed_start
== 0) {
100 /* No previous write postponinig, remember that we are
101 * postponing the flush and return. */
102 server
.aof_flush_postponed_start
= server
.unixtime
;
104 } else if (server
.unixtime
- server
.aof_flush_postponed_start
< 2) {
105 /* We were already waiting for fsync to finish, but for less
106 * than two seconds this is still ok. Postpone again. */
109 /* Otherwise fall trough, and go write since we can't wait
110 * over two seconds. */
111 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.");
114 /* If you are following this code path, then we are going to write so
115 * set reset the postponed flush sentinel to zero. */
116 server
.aof_flush_postponed_start
= 0;
118 /* We want to perform a single write. This should be guaranteed atomic
119 * at least if the filesystem we are writing is a real physical one.
120 * While this will save us against the server being killed I don't think
121 * there is much to do about the whole server stopping for power problems
123 nwritten
= write(server
.aof_fd
,server
.aof_buf
,sdslen(server
.aof_buf
));
124 if (nwritten
!= (signed)sdslen(server
.aof_buf
)) {
125 /* Ooops, we are in troubles. The best thing to do for now is
126 * aborting instead of giving the illusion that everything is
127 * working as expected. */
128 if (nwritten
== -1) {
129 redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
));
131 redisLog(REDIS_WARNING
,"Exiting on short write while writing to the append-only file: %s",strerror(errno
));
135 server
.aof_current_size
+= nwritten
;
137 /* Re-use AOF buffer when it is small enough. The maximum comes from the
138 * arena size of 4k minus some overhead (but is otherwise arbitrary). */
139 if ((sdslen(server
.aof_buf
)+sdsavail(server
.aof_buf
)) < 4000) {
140 sdsclear(server
.aof_buf
);
142 sdsfree(server
.aof_buf
);
143 server
.aof_buf
= sdsempty();
146 /* Don't fsync if no-appendfsync-on-rewrite is set to yes and there are
147 * children doing I/O in the background. */
148 if (server
.aof_no_fsync_on_rewrite
&&
149 (server
.aof_child_pid
!= -1 || server
.rdb_child_pid
!= -1))
152 /* Perform the fsync if needed. */
153 if (server
.aof_fsync
== AOF_FSYNC_ALWAYS
) {
154 /* aof_fsync is defined as fdatasync() for Linux in order to avoid
155 * flushing metadata. */
156 aof_fsync(server
.aof_fd
); /* Let's try to get this data on the disk */
157 server
.aof_last_fsync
= server
.unixtime
;
158 } else if ((server
.aof_fsync
== AOF_FSYNC_EVERYSEC
&&
159 server
.unixtime
> server
.aof_last_fsync
)) {
160 if (!sync_in_progress
) aof_background_fsync(server
.aof_fd
);
161 server
.aof_last_fsync
= server
.unixtime
;
165 sds
catAppendOnlyGenericCommand(sds dst
, int argc
, robj
**argv
) {
171 len
= 1+ll2string(buf
+1,sizeof(buf
)-1,argc
);
174 dst
= sdscatlen(dst
,buf
,len
);
176 for (j
= 0; j
< argc
; j
++) {
177 o
= getDecodedObject(argv
[j
]);
179 len
= 1+ll2string(buf
+1,sizeof(buf
)-1,sdslen(o
->ptr
));
182 dst
= sdscatlen(dst
,buf
,len
);
183 dst
= sdscatlen(dst
,o
->ptr
,sdslen(o
->ptr
));
184 dst
= sdscatlen(dst
,"\r\n",2);
190 /* Create the sds representation of an PEXPIREAT command, using
191 * 'seconds' as time to live and 'cmd' to understand what command
192 * we are translating into a PEXPIREAT.
194 * This command is used in order to translate EXPIRE and PEXPIRE commands
195 * into PEXPIREAT command so that we retain precision in the append only
196 * file, and the time is always absolute and not relative. */
197 sds
catAppendOnlyExpireAtCommand(sds buf
, struct redisCommand
*cmd
, robj
*key
, robj
*seconds
) {
201 /* Make sure we can use strtol */
202 seconds
= getDecodedObject(seconds
);
203 when
= strtoll(seconds
->ptr
,NULL
,10);
204 /* Convert argument into milliseconds for EXPIRE, SETEX, EXPIREAT */
205 if (cmd
->proc
== expireCommand
|| cmd
->proc
== setexCommand
||
206 cmd
->proc
== expireatCommand
)
210 /* Convert into absolute time for EXPIRE, PEXPIRE, SETEX, PSETEX */
211 if (cmd
->proc
== expireCommand
|| cmd
->proc
== pexpireCommand
||
212 cmd
->proc
== setexCommand
|| cmd
->proc
== psetexCommand
)
216 decrRefCount(seconds
);
218 argv
[0] = createStringObject("PEXPIREAT",9);
220 argv
[2] = createStringObjectFromLongLong(when
);
221 buf
= catAppendOnlyGenericCommand(buf
, 3, argv
);
222 decrRefCount(argv
[0]);
223 decrRefCount(argv
[2]);
227 void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
228 sds buf
= sdsempty();
231 /* The DB this command was targetting is not the same as the last command
232 * we appendend. To issue a SELECT command is needed. */
233 if (dictid
!= server
.aof_selected_db
) {
236 snprintf(seldb
,sizeof(seldb
),"%d",dictid
);
237 buf
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
238 (unsigned long)strlen(seldb
),seldb
);
239 server
.aof_selected_db
= dictid
;
242 if (cmd
->proc
== expireCommand
|| cmd
->proc
== pexpireCommand
||
243 cmd
->proc
== expireatCommand
) {
244 /* Translate EXPIRE/PEXPIRE/EXPIREAT into PEXPIREAT */
245 buf
= catAppendOnlyExpireAtCommand(buf
,cmd
,argv
[1],argv
[2]);
246 } else if (cmd
->proc
== setexCommand
|| cmd
->proc
== psetexCommand
) {
247 /* Translate SETEX/PSETEX to SET and PEXPIREAT */
248 tmpargv
[0] = createStringObject("SET",3);
249 tmpargv
[1] = argv
[1];
250 tmpargv
[2] = argv
[3];
251 buf
= catAppendOnlyGenericCommand(buf
,3,tmpargv
);
252 decrRefCount(tmpargv
[0]);
253 buf
= catAppendOnlyExpireAtCommand(buf
,cmd
,argv
[1],argv
[2]);
255 /* All the other commands don't need translation or need the
256 * same translation already operated in the command vector
257 * for the replication itself. */
258 buf
= catAppendOnlyGenericCommand(buf
,argc
,argv
);
261 /* Append to the AOF buffer. This will be flushed on disk just before
262 * of re-entering the event loop, so before the client will get a
263 * positive reply about the operation performed. */
264 if (server
.aof_state
== REDIS_AOF_ON
)
265 server
.aof_buf
= sdscatlen(server
.aof_buf
,buf
,sdslen(buf
));
267 /* If a background append only file rewriting is in progress we want to
268 * accumulate the differences between the child DB and the current one
269 * in a buffer, so that when the child process will do its work we
270 * can append the differences to the new append only file. */
271 if (server
.aof_child_pid
!= -1)
272 server
.aof_rewrite_buf
= sdscatlen(server
.aof_rewrite_buf
,buf
,sdslen(buf
));
277 /* In Redis commands are always executed in the context of a client, so in
278 * order to load the append only file we need to create a fake client. */
279 struct redisClient
*createFakeClient(void) {
280 struct redisClient
*c
= zmalloc(sizeof(*c
));
284 c
->querybuf
= sdsempty();
289 /* We set the fake client as a slave waiting for the synchronization
290 * so that Redis will not try to send replies to this client. */
291 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
292 c
->reply
= listCreate();
293 c
->watched_keys
= listCreate();
294 listSetFreeMethod(c
->reply
,decrRefCount
);
295 listSetDupMethod(c
->reply
,dupClientReplyValue
);
296 initClientMultiState(c
);
300 void freeFakeClient(struct redisClient
*c
) {
301 sdsfree(c
->querybuf
);
302 listRelease(c
->reply
);
303 listRelease(c
->watched_keys
);
304 freeClientMultiState(c
);
308 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
309 * error (the append only file is zero-length) REDIS_ERR is returned. On
310 * fatal error an error message is logged and the program exists. */
311 int loadAppendOnlyFile(char *filename
) {
312 struct redisClient
*fakeClient
;
313 FILE *fp
= fopen(filename
,"r");
314 struct redis_stat sb
;
315 int old_aof_state
= server
.aof_state
;
318 if (fp
&& redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0) {
319 server
.aof_current_size
= 0;
325 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
329 /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
330 * to the same file we're about to read. */
331 server
.aof_state
= REDIS_AOF_OFF
;
333 fakeClient
= createFakeClient();
342 struct redisCommand
*cmd
;
344 /* Serve the clients from time to time */
345 if (!(loops
++ % 1000)) {
346 loadingProgress(ftello(fp
));
347 aeProcessEvents(server
.el
, AE_FILE_EVENTS
|AE_DONT_WAIT
);
350 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
356 if (buf
[0] != '*') goto fmterr
;
358 if (argc
< 1) goto fmterr
;
360 argv
= zmalloc(sizeof(robj
*)*argc
);
361 for (j
= 0; j
< argc
; j
++) {
362 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
363 if (buf
[0] != '$') goto fmterr
;
364 len
= strtol(buf
+1,NULL
,10);
365 argsds
= sdsnewlen(NULL
,len
);
366 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
367 argv
[j
] = createObject(REDIS_STRING
,argsds
);
368 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
372 cmd
= lookupCommand(argv
[0]->ptr
);
374 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
377 /* Run the command in the context of a fake client */
378 fakeClient
->argc
= argc
;
379 fakeClient
->argv
= argv
;
380 cmd
->proc(fakeClient
);
382 /* The fake client should not have a reply */
383 redisAssert(fakeClient
->bufpos
== 0 && listLength(fakeClient
->reply
) == 0);
384 /* The fake client should never get blocked */
385 redisAssert((fakeClient
->flags
& REDIS_BLOCKED
) == 0);
387 /* Clean up. Command code may have changed argv/argc so we use the
388 * argv/argc of the client instead of the local variables. */
389 for (j
= 0; j
< fakeClient
->argc
; j
++)
390 decrRefCount(fakeClient
->argv
[j
]);
391 zfree(fakeClient
->argv
);
394 /* This point can only be reached when EOF is reached without errors.
395 * If the client is in the middle of a MULTI/EXEC, log error and quit. */
396 if (fakeClient
->flags
& REDIS_MULTI
) goto readerr
;
399 freeFakeClient(fakeClient
);
400 server
.aof_state
= old_aof_state
;
402 aofUpdateCurrentSize();
403 server
.aof_rewrite_base_size
= server
.aof_current_size
;
408 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
410 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
414 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>");
418 /* Delegate writing an object to writing a bulk string or bulk long long.
419 * This is not placed in rio.c since that adds the redis.h dependency. */
420 int rioWriteBulkObject(rio
*r
, robj
*obj
) {
421 /* Avoid using getDecodedObject to help copy-on-write (we are often
422 * in a child process when this function is called). */
423 if (obj
->encoding
== REDIS_ENCODING_INT
) {
424 return rioWriteBulkLongLong(r
,(long)obj
->ptr
);
425 } else if (obj
->encoding
== REDIS_ENCODING_RAW
) {
426 return rioWriteBulkString(r
,obj
->ptr
,sdslen(obj
->ptr
));
428 redisPanic("Unknown string encoding");
432 /* Emit the commands needed to rebuild a list object.
433 * The function returns 0 on error, 1 on success. */
434 int rewriteListObject(rio
*r
, robj
*key
, robj
*o
) {
435 long long count
= 0, items
= listTypeLength(o
);
437 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
438 unsigned char *zl
= o
->ptr
;
439 unsigned char *p
= ziplistIndex(zl
,0);
444 while(ziplistGet(p
,&vstr
,&vlen
,&vlong
)) {
446 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
447 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
449 if (rioWriteBulkCount(r
,'*',2+cmd_items
) == 0) return 0;
450 if (rioWriteBulkString(r
,"RPUSH",5) == 0) return 0;
451 if (rioWriteBulkObject(r
,key
) == 0) return 0;
454 if (rioWriteBulkString(r
,(char*)vstr
,vlen
) == 0) return 0;
456 if (rioWriteBulkLongLong(r
,vlong
) == 0) return 0;
458 p
= ziplistNext(zl
,p
);
459 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
462 } else if (o
->encoding
== REDIS_ENCODING_LINKEDLIST
) {
467 listRewind(list
,&li
);
468 while((ln
= listNext(&li
))) {
469 robj
*eleobj
= listNodeValue(ln
);
472 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
473 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
475 if (rioWriteBulkCount(r
,'*',2+cmd_items
) == 0) return 0;
476 if (rioWriteBulkString(r
,"RPUSH",5) == 0) return 0;
477 if (rioWriteBulkObject(r
,key
) == 0) return 0;
479 if (rioWriteBulkObject(r
,eleobj
) == 0) return 0;
480 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
484 redisPanic("Unknown list encoding");
489 /* Emit the commands needed to rebuild a set object.
490 * The function returns 0 on error, 1 on success. */
491 int rewriteSetObject(rio
*r
, robj
*key
, robj
*o
) {
492 long long count
= 0, items
= setTypeSize(o
);
494 if (o
->encoding
== REDIS_ENCODING_INTSET
) {
498 while(intsetGet(o
->ptr
,ii
++,&llval
)) {
500 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
501 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
503 if (rioWriteBulkCount(r
,'*',2+cmd_items
) == 0) return 0;
504 if (rioWriteBulkString(r
,"SADD",4) == 0) return 0;
505 if (rioWriteBulkObject(r
,key
) == 0) return 0;
507 if (rioWriteBulkLongLong(r
,llval
) == 0) return 0;
508 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
511 } else if (o
->encoding
== REDIS_ENCODING_HT
) {
512 dictIterator
*di
= dictGetIterator(o
->ptr
);
515 while((de
= dictNext(di
)) != NULL
) {
516 robj
*eleobj
= dictGetKey(de
);
518 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
519 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
521 if (rioWriteBulkCount(r
,'*',2+cmd_items
) == 0) return 0;
522 if (rioWriteBulkString(r
,"SADD",4) == 0) return 0;
523 if (rioWriteBulkObject(r
,key
) == 0) return 0;
525 if (rioWriteBulkObject(r
,eleobj
) == 0) return 0;
526 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
529 dictReleaseIterator(di
);
531 redisPanic("Unknown set encoding");
536 /* Emit the commands needed to rebuild a sorted set object.
537 * The function returns 0 on error, 1 on success. */
538 int rewriteSortedSetObject(rio
*r
, robj
*key
, robj
*o
) {
539 long long count
= 0, items
= zsetLength(o
);
541 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
542 unsigned char *zl
= o
->ptr
;
543 unsigned char *eptr
, *sptr
;
549 eptr
= ziplistIndex(zl
,0);
550 redisAssert(eptr
!= NULL
);
551 sptr
= ziplistNext(zl
,eptr
);
552 redisAssert(sptr
!= NULL
);
554 while (eptr
!= NULL
) {
555 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vll
));
556 score
= zzlGetScore(sptr
);
559 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
560 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
562 if (rioWriteBulkCount(r
,'*',2+cmd_items
*2) == 0) return 0;
563 if (rioWriteBulkString(r
,"ZADD",4) == 0) return 0;
564 if (rioWriteBulkObject(r
,key
) == 0) return 0;
566 if (rioWriteBulkDouble(r
,score
) == 0) return 0;
568 if (rioWriteBulkString(r
,(char*)vstr
,vlen
) == 0) return 0;
570 if (rioWriteBulkLongLong(r
,vll
) == 0) return 0;
572 zzlNext(zl
,&eptr
,&sptr
);
573 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
576 } else if (o
->encoding
== REDIS_ENCODING_SKIPLIST
) {
578 dictIterator
*di
= dictGetIterator(zs
->dict
);
581 while((de
= dictNext(di
)) != NULL
) {
582 robj
*eleobj
= dictGetKey(de
);
583 double *score
= dictGetVal(de
);
586 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
587 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
589 if (rioWriteBulkCount(r
,'*',2+cmd_items
*2) == 0) return 0;
590 if (rioWriteBulkString(r
,"ZADD",4) == 0) return 0;
591 if (rioWriteBulkObject(r
,key
) == 0) return 0;
593 if (rioWriteBulkDouble(r
,*score
) == 0) return 0;
594 if (rioWriteBulkObject(r
,eleobj
) == 0) return 0;
595 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
598 dictReleaseIterator(di
);
600 redisPanic("Unknown sorted zset encoding");
605 /* Emit the commands needed to rebuild a hash object.
606 * The function returns 0 on error, 1 on success. */
607 int rewriteHashObject(rio
*r
, robj
*key
, robj
*o
) {
608 long long count
= 0, items
= hashTypeLength(o
);
610 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
611 unsigned char *p
= zipmapRewind(o
->ptr
);
612 unsigned char *field
, *val
;
613 unsigned int flen
, vlen
;
615 while((p
= zipmapNext(p
,&field
,&flen
,&val
,&vlen
)) != NULL
) {
617 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
618 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
620 if (rioWriteBulkCount(r
,'*',2+cmd_items
*2) == 0) return 0;
621 if (rioWriteBulkString(r
,"HMSET",5) == 0) return 0;
622 if (rioWriteBulkObject(r
,key
) == 0) return 0;
624 if (rioWriteBulkString(r
,(char*)field
,flen
) == 0) return 0;
625 if (rioWriteBulkString(r
,(char*)val
,vlen
) == 0) return 0;
626 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
630 dictIterator
*di
= dictGetIterator(o
->ptr
);
633 while((de
= dictNext(di
)) != NULL
) {
634 robj
*field
= dictGetKey(de
);
635 robj
*val
= dictGetVal(de
);
638 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
639 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
641 if (rioWriteBulkCount(r
,'*',2+cmd_items
*2) == 0) return 0;
642 if (rioWriteBulkString(r
,"HMSET",5) == 0) return 0;
643 if (rioWriteBulkObject(r
,key
) == 0) return 0;
645 if (rioWriteBulkObject(r
,field
) == 0) return 0;
646 if (rioWriteBulkObject(r
,val
) == 0) return 0;
647 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
650 dictReleaseIterator(di
);
655 /* Write a sequence of commands able to fully rebuild the dataset into
656 * "filename". Used both by REWRITEAOF and BGREWRITEAOF.
658 * In order to minimize the number of commands needed in the rewritten
659 * log Redis uses variadic commands when possible, such as RPUSH, SADD
660 * and ZADD. However at max REDIS_AOF_REWRITE_ITEMS_PER_CMD items per time
661 * are inserted using a single command. */
662 int rewriteAppendOnlyFile(char *filename
) {
663 dictIterator
*di
= NULL
;
669 long long now
= mstime();
671 /* Note that we have to use a different temp name here compared to the
672 * one used by rewriteAppendOnlyFileBackground() function. */
673 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
674 fp
= fopen(tmpfile
,"w");
676 redisLog(REDIS_WARNING
, "Failed rewriting the append only file: %s", strerror(errno
));
680 rioInitWithFile(&aof
,fp
);
681 for (j
= 0; j
< server
.dbnum
; j
++) {
682 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
683 redisDb
*db
= server
.db
+j
;
685 if (dictSize(d
) == 0) continue;
686 di
= dictGetSafeIterator(d
);
692 /* SELECT the new DB */
693 if (rioWrite(&aof
,selectcmd
,sizeof(selectcmd
)-1) == 0) goto werr
;
694 if (rioWriteBulkLongLong(&aof
,j
) == 0) goto werr
;
696 /* Iterate this DB writing every entry */
697 while((de
= dictNext(di
)) != NULL
) {
700 long long expiretime
;
702 keystr
= dictGetKey(de
);
704 initStaticStringObject(key
,keystr
);
706 expiretime
= getExpire(db
,&key
);
708 /* Save the key and associated value */
709 if (o
->type
== REDIS_STRING
) {
710 /* Emit a SET command */
711 char cmd
[]="*3\r\n$3\r\nSET\r\n";
712 if (rioWrite(&aof
,cmd
,sizeof(cmd
)-1) == 0) goto werr
;
714 if (rioWriteBulkObject(&aof
,&key
) == 0) goto werr
;
715 if (rioWriteBulkObject(&aof
,o
) == 0) goto werr
;
716 } else if (o
->type
== REDIS_LIST
) {
717 if (rewriteListObject(&aof
,&key
,o
) == 0) goto werr
;
718 } else if (o
->type
== REDIS_SET
) {
719 if (rewriteSetObject(&aof
,&key
,o
) == 0) goto werr
;
720 } else if (o
->type
== REDIS_ZSET
) {
721 if (rewriteSortedSetObject(&aof
,&key
,o
) == 0) goto werr
;
722 } else if (o
->type
== REDIS_HASH
) {
723 if (rewriteHashObject(&aof
,&key
,o
) == 0) goto werr
;
725 redisPanic("Unknown object type");
727 /* Save the expire time */
728 if (expiretime
!= -1) {
729 char cmd
[]="*3\r\n$9\r\nPEXPIREAT\r\n";
730 /* If this key is already expired skip it */
731 if (expiretime
< now
) continue;
732 if (rioWrite(&aof
,cmd
,sizeof(cmd
)-1) == 0) goto werr
;
733 if (rioWriteBulkObject(&aof
,&key
) == 0) goto werr
;
734 if (rioWriteBulkLongLong(&aof
,expiretime
) == 0) goto werr
;
737 dictReleaseIterator(di
);
740 /* Make sure data will not remain on the OS's output buffers */
742 aof_fsync(fileno(fp
));
745 /* Use RENAME to make sure the DB file is changed atomically only
746 * if the generate DB file is ok. */
747 if (rename(tmpfile
,filename
) == -1) {
748 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
752 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
758 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
759 if (di
) dictReleaseIterator(di
);
763 /* This is how rewriting of the append only file in background works:
765 * 1) The user calls BGREWRITEAOF
766 * 2) Redis calls this function, that forks():
767 * 2a) the child rewrite the append only file in a temp file.
768 * 2b) the parent accumulates differences in server.aof_rewrite_buf.
769 * 3) When the child finished '2a' exists.
770 * 4) The parent will trap the exit code, if it's OK, will append the
771 * data accumulated into server.aof_rewrite_buf into the temp file, and
772 * finally will rename(2) the temp file in the actual file name.
773 * The the new file is reopened as the new append only file. Profit!
775 int rewriteAppendOnlyFileBackground(void) {
779 if (server
.aof_child_pid
!= -1) return REDIS_ERR
;
781 if ((childpid
= fork()) == 0) {
785 if (server
.ipfd
> 0) close(server
.ipfd
);
786 if (server
.sofd
> 0) close(server
.sofd
);
787 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
788 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
795 server
.stat_fork_time
= ustime()-start
;
796 if (childpid
== -1) {
797 redisLog(REDIS_WARNING
,
798 "Can't rewrite append only file in background: fork: %s",
802 redisLog(REDIS_NOTICE
,
803 "Background append only file rewriting started by pid %d",childpid
);
804 server
.aof_rewrite_scheduled
= 0;
805 server
.aof_child_pid
= childpid
;
806 updateDictResizePolicy();
807 /* We set appendseldb to -1 in order to force the next call to the
808 * feedAppendOnlyFile() to issue a SELECT command, so the differences
809 * accumulated by the parent into server.aof_rewrite_buf will start
810 * with a SELECT statement and it will be safe to merge. */
811 server
.aof_selected_db
= -1;
814 return REDIS_OK
; /* unreached */
817 void bgrewriteaofCommand(redisClient
*c
) {
818 if (server
.aof_child_pid
!= -1) {
819 addReplyError(c
,"Background append only file rewriting already in progress");
820 } else if (server
.rdb_child_pid
!= -1) {
821 server
.aof_rewrite_scheduled
= 1;
822 addReplyStatus(c
,"Background append only file rewriting scheduled");
823 } else if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
824 addReplyStatus(c
,"Background append only file rewriting started");
826 addReply(c
,shared
.err
);
830 void aofRemoveTempFile(pid_t childpid
) {
833 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
837 /* Update the server.aof_current_size filed explicitly using stat(2)
838 * to check the size of the file. This is useful after a rewrite or after
839 * a restart, normally the size is updated just adding the write length
840 * to the current lenght, that is much faster. */
841 void aofUpdateCurrentSize(void) {
842 struct redis_stat sb
;
844 if (redis_fstat(server
.aof_fd
,&sb
) == -1) {
845 redisLog(REDIS_WARNING
,"Unable to check the AOF length: %s",
848 server
.aof_current_size
= sb
.st_size
;
852 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
854 void backgroundRewriteDoneHandler(int exitcode
, int bysignal
) {
855 if (!bysignal
&& exitcode
== 0) {
859 long long now
= ustime();
861 redisLog(REDIS_NOTICE
,
862 "Background AOF rewrite terminated with success");
864 /* Flush the differences accumulated by the parent to the
866 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof",
867 (int)server
.aof_child_pid
);
868 newfd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
870 redisLog(REDIS_WARNING
,
871 "Unable to open the temporary AOF produced by the child: %s", strerror(errno
));
875 nwritten
= write(newfd
,server
.aof_rewrite_buf
,sdslen(server
.aof_rewrite_buf
));
876 if (nwritten
!= (signed)sdslen(server
.aof_rewrite_buf
)) {
877 if (nwritten
== -1) {
878 redisLog(REDIS_WARNING
,
879 "Error trying to flush the parent diff to the rewritten AOF: %s", strerror(errno
));
881 redisLog(REDIS_WARNING
,
882 "Short write trying to flush the parent diff to the rewritten AOF: %s", strerror(errno
));
888 redisLog(REDIS_NOTICE
,
889 "Parent diff successfully flushed to the rewritten AOF (%lu bytes)", nwritten
);
891 /* The only remaining thing to do is to rename the temporary file to
892 * the configured file and switch the file descriptor used to do AOF
893 * writes. We don't want close(2) or rename(2) calls to block the
894 * server on old file deletion.
896 * There are two possible scenarios:
898 * 1) AOF is DISABLED and this was a one time rewrite. The temporary
899 * file will be renamed to the configured file. When this file already
900 * exists, it will be unlinked, which may block the server.
902 * 2) AOF is ENABLED and the rewritten AOF will immediately start
903 * receiving writes. After the temporary file is renamed to the
904 * configured file, the original AOF file descriptor will be closed.
905 * Since this will be the last reference to that file, closing it
906 * causes the underlying file to be unlinked, which may block the
909 * To mitigate the blocking effect of the unlink operation (either
910 * caused by rename(2) in scenario 1, or by close(2) in scenario 2), we
911 * use a background thread to take care of this. First, we
912 * make scenario 1 identical to scenario 2 by opening the target file
913 * when it exists. The unlink operation after the rename(2) will then
914 * be executed upon calling close(2) for its descriptor. Everything to
915 * guarantee atomicity for this switch has already happened by then, so
916 * we don't care what the outcome or duration of that close operation
917 * is, as long as the file descriptor is released again. */
918 if (server
.aof_fd
== -1) {
921 /* Don't care if this fails: oldfd will be -1 and we handle that.
922 * One notable case of -1 return is if the old file does
924 oldfd
= open(server
.aof_filename
,O_RDONLY
|O_NONBLOCK
);
927 oldfd
= -1; /* We'll set this to the current AOF filedes later. */
930 /* Rename the temporary file. This will not unlink the target file if
931 * it exists, because we reference it with "oldfd". */
932 if (rename(tmpfile
,server
.aof_filename
) == -1) {
933 redisLog(REDIS_WARNING
,
934 "Error trying to rename the temporary AOF: %s", strerror(errno
));
936 if (oldfd
!= -1) close(oldfd
);
940 if (server
.aof_fd
== -1) {
941 /* AOF disabled, we don't need to set the AOF file descriptor
942 * to this new file, so we can close it. */
945 /* AOF enabled, replace the old fd with the new one. */
946 oldfd
= server
.aof_fd
;
947 server
.aof_fd
= newfd
;
948 if (server
.aof_fsync
== AOF_FSYNC_ALWAYS
)
950 else if (server
.aof_fsync
== AOF_FSYNC_EVERYSEC
)
951 aof_background_fsync(newfd
);
952 server
.aof_selected_db
= -1; /* Make sure SELECT is re-issued */
953 aofUpdateCurrentSize();
954 server
.aof_rewrite_base_size
= server
.aof_current_size
;
956 /* Clear regular AOF buffer since its contents was just written to
957 * the new AOF from the background rewrite buffer. */
958 sdsfree(server
.aof_buf
);
959 server
.aof_buf
= sdsempty();
962 redisLog(REDIS_NOTICE
, "Background AOF rewrite successful");
963 /* Change state from WAIT_REWRITE to ON if needed */
964 if (server
.aof_state
== REDIS_AOF_WAIT_REWRITE
)
965 server
.aof_state
= REDIS_AOF_ON
;
967 /* Asynchronously close the overwritten AOF. */
968 if (oldfd
!= -1) bioCreateBackgroundJob(REDIS_BIO_CLOSE_FILE
,(void*)(long)oldfd
,NULL
,NULL
);
970 redisLog(REDIS_VERBOSE
,
971 "Background AOF rewrite signal handler took %lldus", ustime()-now
);
972 } else if (!bysignal
&& exitcode
!= 0) {
973 redisLog(REDIS_WARNING
,
974 "Background AOF rewrite terminated with error");
976 redisLog(REDIS_WARNING
,
977 "Background AOF rewrite terminated by signal %d", bysignal
);
981 sdsfree(server
.aof_rewrite_buf
);
982 server
.aof_rewrite_buf
= sdsempty();
983 aofRemoveTempFile(server
.aof_child_pid
);
984 server
.aof_child_pid
= -1;
985 /* Schedule a new rewrite if we are waiting for it to switch the AOF ON. */
986 if (server
.aof_state
== REDIS_AOF_WAIT_REWRITE
)
987 server
.aof_rewrite_scheduled
= 1;