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 flushAppendOnlyFile(1);
23 aof_fsync(server
.appendfd
);
24 close(server
.appendfd
);
27 server
.appendseldb
= -1;
28 server
.appendonly
= 0;
29 server
.aof_wait_rewrite
= 0;
30 /* rewrite operation in progress? kill it, wait child exit */
31 if (server
.bgrewritechildpid
!= -1) {
34 if (kill(server
.bgrewritechildpid
,SIGKILL
) != -1)
35 wait3(&statloc
,0,NULL
);
36 /* reset the buffer accumulating changes while the child saves */
37 sdsfree(server
.bgrewritebuf
);
38 server
.bgrewritebuf
= sdsempty();
39 aofRemoveTempFile(server
.bgrewritechildpid
);
40 server
.bgrewritechildpid
= -1;
44 /* Called when the user switches from "appendonly no" to "appendonly yes"
45 * at runtime using the CONFIG command. */
46 int startAppendOnly(void) {
47 server
.lastfsync
= time(NULL
);
48 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
49 if (server
.appendfd
== -1) {
50 redisLog(REDIS_WARNING
,"Redis needs to enable the AOF but can't open the append only file: %s",strerror(errno
));
53 if (rewriteAppendOnlyFileBackground() == REDIS_ERR
) {
54 close(server
.appendfd
);
55 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.");
58 /* We correctly switched on AOF, now wait for the rerwite to be complete
59 * in order to append data on disk. */
60 server
.appendonly
= 1;
61 server
.aof_wait_rewrite
= 1;
65 /* Write the append only file buffer on disk.
67 * Since we are required to write the AOF before replying to the client,
68 * and the only way the client socket can get a write is entering when the
69 * the event loop, we accumulate all the AOF writes in a memory
70 * buffer and write it on disk using this function just before entering
71 * the event loop again.
73 * About the 'force' argument:
75 * When the fsync policy is set to 'everysec' we may delay the flush if there
76 * is still an fsync() going on in the background thread, since for instance
77 * on Linux write(2) will be blocked by the background fsync anyway.
78 * When this happens we remember that there is some aof buffer to be
79 * flushed ASAP, and will try to do that in the serverCron() function.
81 * However if force is set to 1 we'll write regardless of the background
83 void flushAppendOnlyFile(int force
) {
85 int sync_in_progress
= 0;
87 if (sdslen(server
.aofbuf
) == 0) return;
89 if (server
.appendfsync
== APPENDFSYNC_EVERYSEC
)
90 sync_in_progress
= bioPendingJobsOfType(REDIS_BIO_AOF_FSYNC
) != 0;
92 if (server
.appendfsync
== APPENDFSYNC_EVERYSEC
&& !force
) {
93 /* With this append fsync policy we do background fsyncing.
94 * If the fsync is still in progress we can try to delay
95 * the write for a couple of seconds. */
96 if (sync_in_progress
) {
97 if (server
.aof_flush_postponed_start
== 0) {
98 /* No previous write postponinig, remember that we are
99 * postponing the flush and return. */
100 server
.aof_flush_postponed_start
= server
.unixtime
;
102 } else if (server
.unixtime
- server
.aof_flush_postponed_start
< 2) {
103 /* We were already waiting for fsync to finish, but for less
104 * than two seconds this is still ok. Postpone again. */
107 /* Otherwise fall trough, and go write since we can't wait
108 * over two seconds. */
109 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.");
112 /* If you are following this code path, then we are going to write so
113 * set reset the postponed flush sentinel to zero. */
114 server
.aof_flush_postponed_start
= 0;
116 /* We want to perform a single write. This should be guaranteed atomic
117 * at least if the filesystem we are writing is a real physical one.
118 * While this will save us against the server being killed I don't think
119 * there is much to do about the whole server stopping for power problems
121 nwritten
= write(server
.appendfd
,server
.aofbuf
,sdslen(server
.aofbuf
));
122 if (nwritten
!= (signed)sdslen(server
.aofbuf
)) {
123 /* Ooops, we are in troubles. The best thing to do for now is
124 * aborting instead of giving the illusion that everything is
125 * working as expected. */
126 if (nwritten
== -1) {
127 redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
));
129 redisLog(REDIS_WARNING
,"Exiting on short write while writing to the append-only file: %s",strerror(errno
));
133 server
.appendonly_current_size
+= nwritten
;
135 /* Re-use AOF buffer when it is small enough. The maximum comes from the
136 * arena size of 4k minus some overhead (but is otherwise arbitrary). */
137 if ((sdslen(server
.aofbuf
)+sdsavail(server
.aofbuf
)) < 4000) {
138 sdsclear(server
.aofbuf
);
140 sdsfree(server
.aofbuf
);
141 server
.aofbuf
= sdsempty();
144 /* Don't fsync if no-appendfsync-on-rewrite is set to yes and there are
145 * children doing I/O in the background. */
146 if (server
.no_appendfsync_on_rewrite
&&
147 (server
.bgrewritechildpid
!= -1 || server
.bgsavechildpid
!= -1))
150 /* Perform the fsync if needed. */
151 if (server
.appendfsync
== APPENDFSYNC_ALWAYS
) {
152 /* aof_fsync is defined as fdatasync() for Linux in order to avoid
153 * flushing metadata. */
154 aof_fsync(server
.appendfd
); /* Let's try to get this data on the disk */
155 server
.lastfsync
= server
.unixtime
;
156 } else if ((server
.appendfsync
== APPENDFSYNC_EVERYSEC
&&
157 server
.unixtime
> server
.lastfsync
)) {
158 if (!sync_in_progress
) aof_background_fsync(server
.appendfd
);
159 server
.lastfsync
= server
.unixtime
;
163 sds
catAppendOnlyGenericCommand(sds dst
, int argc
, robj
**argv
) {
169 len
= 1+ll2string(buf
+1,sizeof(buf
)-1,argc
);
172 dst
= sdscatlen(dst
,buf
,len
);
174 for (j
= 0; j
< argc
; j
++) {
175 o
= getDecodedObject(argv
[j
]);
177 len
= 1+ll2string(buf
+1,sizeof(buf
)-1,sdslen(o
->ptr
));
180 dst
= sdscatlen(dst
,buf
,len
);
181 dst
= sdscatlen(dst
,o
->ptr
,sdslen(o
->ptr
));
182 dst
= sdscatlen(dst
,"\r\n",2);
188 /* Create the sds representation of an PEXPIREAT command, using
189 * 'seconds' as time to live and 'cmd' to understand what command
190 * we are translating into a PEXPIREAT.
192 * This command is used in order to translate EXPIRE and PEXPIRE commands
193 * into PEXPIREAT command so that we retain precision in the append only
194 * file, and the time is always absolute and not relative. */
195 sds
catAppendOnlyExpireAtCommand(sds buf
, struct redisCommand
*cmd
, robj
*key
, robj
*seconds
) {
199 /* Make sure we can use strtol */
200 seconds
= getDecodedObject(seconds
);
201 when
= strtoll(seconds
->ptr
,NULL
,10);
202 /* Convert argument into milliseconds for EXPIRE, SETEX, EXPIREAT */
203 if (cmd
->proc
== expireCommand
|| cmd
->proc
== setexCommand
||
204 cmd
->proc
== expireatCommand
)
208 /* Convert into absolute time for EXPIRE, PEXPIRE, SETEX, PSETEX */
209 if (cmd
->proc
== expireCommand
|| cmd
->proc
== pexpireCommand
||
210 cmd
->proc
== setexCommand
|| cmd
->proc
== psetexCommand
)
214 decrRefCount(seconds
);
216 argv
[0] = createStringObject("PEXPIREAT",9);
218 argv
[2] = createStringObjectFromLongLong(when
);
219 buf
= catAppendOnlyGenericCommand(buf
, 3, argv
);
220 decrRefCount(argv
[0]);
221 decrRefCount(argv
[2]);
225 void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
226 sds buf
= sdsempty();
229 /* The DB this command was targetting is not the same as the last command
230 * we appendend. To issue a SELECT command is needed. */
231 if (dictid
!= server
.appendseldb
) {
234 snprintf(seldb
,sizeof(seldb
),"%d",dictid
);
235 buf
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
236 (unsigned long)strlen(seldb
),seldb
);
237 server
.appendseldb
= dictid
;
240 if (cmd
->proc
== expireCommand
|| cmd
->proc
== pexpireCommand
||
241 cmd
->proc
== expireatCommand
) {
242 /* Translate EXPIRE/PEXPIRE/EXPIREAT into PEXPIREAT */
243 buf
= catAppendOnlyExpireAtCommand(buf
,cmd
,argv
[1],argv
[2]);
244 } else if (cmd
->proc
== setexCommand
|| cmd
->proc
== psetexCommand
) {
245 /* Translate SETEX/PSETEX to SET and PEXPIREAT */
246 tmpargv
[0] = createStringObject("SET",3);
247 tmpargv
[1] = argv
[1];
248 tmpargv
[2] = argv
[3];
249 buf
= catAppendOnlyGenericCommand(buf
,3,tmpargv
);
250 decrRefCount(tmpargv
[0]);
251 buf
= catAppendOnlyExpireAtCommand(buf
,cmd
,argv
[1],argv
[2]);
253 /* All the other commands don't need translation or need the
254 * same translation already operated in the command vector
255 * for the replication itself. */
256 buf
= catAppendOnlyGenericCommand(buf
,argc
,argv
);
259 /* Append to the AOF buffer. This will be flushed on disk just before
260 * of re-entering the event loop, so before the client will get a
261 * positive reply about the operation performed.
263 * Note, we don't add stuff in the AOF buffer if aof_wait_rewrite is
264 * non zero, as this means we are starting with a new AOF and the
265 * current one is meaningless (this happens for instance after
266 * a slave resyncs with its master). */
267 if (!server
.aof_wait_rewrite
) {
268 server
.aofbuf
= sdscatlen(server
.aofbuf
,buf
,sdslen(buf
));
271 /* If a background append only file rewriting is in progress we want to
272 * accumulate the differences between the child DB and the current one
273 * in a buffer, so that when the child process will do its work we
274 * can append the differences to the new append only file. */
275 if (server
.bgrewritechildpid
!= -1)
276 server
.bgrewritebuf
= sdscatlen(server
.bgrewritebuf
,buf
,sdslen(buf
));
281 /* In Redis commands are always executed in the context of a client, so in
282 * order to load the append only file we need to create a fake client. */
283 struct redisClient
*createFakeClient(void) {
284 struct redisClient
*c
= zmalloc(sizeof(*c
));
288 c
->querybuf
= sdsempty();
293 /* We set the fake client as a slave waiting for the synchronization
294 * so that Redis will not try to send replies to this client. */
295 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
296 c
->reply
= listCreate();
297 c
->watched_keys
= listCreate();
298 listSetFreeMethod(c
->reply
,decrRefCount
);
299 listSetDupMethod(c
->reply
,dupClientReplyValue
);
300 initClientMultiState(c
);
304 void freeFakeClient(struct redisClient
*c
) {
305 sdsfree(c
->querybuf
);
306 listRelease(c
->reply
);
307 listRelease(c
->watched_keys
);
308 freeClientMultiState(c
);
312 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
313 * error (the append only file is zero-length) REDIS_ERR is returned. On
314 * fatal error an error message is logged and the program exists. */
315 int loadAppendOnlyFile(char *filename
) {
316 struct redisClient
*fakeClient
;
317 FILE *fp
= fopen(filename
,"r");
318 struct redis_stat sb
;
319 int appendonly
= server
.appendonly
;
322 if (fp
&& redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0) {
323 server
.appendonly_current_size
= 0;
329 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
333 /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
334 * to the same file we're about to read. */
335 server
.appendonly
= 0;
337 fakeClient
= createFakeClient();
346 struct redisCommand
*cmd
;
348 /* Serve the clients from time to time */
349 if (!(loops
++ % 1000)) {
350 loadingProgress(ftello(fp
));
351 aeProcessEvents(server
.el
, AE_FILE_EVENTS
|AE_DONT_WAIT
);
354 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
360 if (buf
[0] != '*') goto fmterr
;
362 if (argc
< 1) goto fmterr
;
364 argv
= zmalloc(sizeof(robj
*)*argc
);
365 for (j
= 0; j
< argc
; j
++) {
366 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
367 if (buf
[0] != '$') goto fmterr
;
368 len
= strtol(buf
+1,NULL
,10);
369 argsds
= sdsnewlen(NULL
,len
);
370 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
371 argv
[j
] = createObject(REDIS_STRING
,argsds
);
372 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
376 cmd
= lookupCommand(argv
[0]->ptr
);
378 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
381 /* Run the command in the context of a fake client */
382 fakeClient
->argc
= argc
;
383 fakeClient
->argv
= argv
;
384 cmd
->proc(fakeClient
);
386 /* The fake client should not have a reply */
387 redisAssert(fakeClient
->bufpos
== 0 && listLength(fakeClient
->reply
) == 0);
388 /* The fake client should never get blocked */
389 redisAssert((fakeClient
->flags
& REDIS_BLOCKED
) == 0);
391 /* Clean up. Command code may have changed argv/argc so we use the
392 * argv/argc of the client instead of the local variables. */
393 for (j
= 0; j
< fakeClient
->argc
; j
++)
394 decrRefCount(fakeClient
->argv
[j
]);
395 zfree(fakeClient
->argv
);
398 /* This point can only be reached when EOF is reached without errors.
399 * If the client is in the middle of a MULTI/EXEC, log error and quit. */
400 if (fakeClient
->flags
& REDIS_MULTI
) goto readerr
;
403 freeFakeClient(fakeClient
);
404 server
.appendonly
= appendonly
;
406 aofUpdateCurrentSize();
407 server
.auto_aofrewrite_base_size
= server
.appendonly_current_size
;
412 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
414 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
418 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>");
422 /* Delegate writing an object to writing a bulk string or bulk long long.
423 * This is not placed in rio.c since that adds the redis.h dependency. */
424 int rioWriteBulkObject(rio
*r
, robj
*obj
) {
425 /* Avoid using getDecodedObject to help copy-on-write (we are often
426 * in a child process when this function is called). */
427 if (obj
->encoding
== REDIS_ENCODING_INT
) {
428 return rioWriteBulkLongLong(r
,(long)obj
->ptr
);
429 } else if (obj
->encoding
== REDIS_ENCODING_RAW
) {
430 return rioWriteBulkString(r
,obj
->ptr
,sdslen(obj
->ptr
));
432 redisPanic("Unknown string encoding");
436 /* Emit the commands needed to rebuild a list object.
437 * The function returns 0 on error, 1 on success. */
438 int rewriteListObject(rio
*r
, robj
*key
, robj
*o
) {
439 long long count
= 0, items
= listTypeLength(o
);
441 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
442 unsigned char *zl
= o
->ptr
;
443 unsigned char *p
= ziplistIndex(zl
,0);
448 while(ziplistGet(p
,&vstr
,&vlen
,&vlong
)) {
450 int cmd_items
= (items
> REDIS_AOFREWRITE_ITEMS_PER_CMD
) ?
451 REDIS_AOFREWRITE_ITEMS_PER_CMD
: items
;
453 if (rioWriteBulkCount(r
,'*',2+cmd_items
) == 0) return 0;
454 if (rioWriteBulkString(r
,"RPUSH",5) == 0) return 0;
455 if (rioWriteBulkObject(r
,key
) == 0) return 0;
458 if (rioWriteBulkString(r
,(char*)vstr
,vlen
) == 0) return 0;
460 if (rioWriteBulkLongLong(r
,vlong
) == 0) return 0;
462 p
= ziplistNext(zl
,p
);
463 if (++count
== REDIS_AOFREWRITE_ITEMS_PER_CMD
) count
= 0;
466 } else if (o
->encoding
== REDIS_ENCODING_LINKEDLIST
) {
471 listRewind(list
,&li
);
472 while((ln
= listNext(&li
))) {
473 robj
*eleobj
= listNodeValue(ln
);
476 int cmd_items
= (items
> REDIS_AOFREWRITE_ITEMS_PER_CMD
) ?
477 REDIS_AOFREWRITE_ITEMS_PER_CMD
: items
;
479 if (rioWriteBulkCount(r
,'*',2+cmd_items
) == 0) return 0;
480 if (rioWriteBulkString(r
,"RPUSH",5) == 0) return 0;
481 if (rioWriteBulkObject(r
,key
) == 0) return 0;
483 if (rioWriteBulkObject(r
,eleobj
) == 0) return 0;
484 if (++count
== REDIS_AOFREWRITE_ITEMS_PER_CMD
) count
= 0;
488 redisPanic("Unknown list encoding");
493 /* Emit the commands needed to rebuild a set object.
494 * The function returns 0 on error, 1 on success. */
495 int rewriteSetObject(rio
*r
, robj
*key
, robj
*o
) {
496 long long count
= 0, items
= setTypeSize(o
);
498 if (o
->encoding
== REDIS_ENCODING_INTSET
) {
502 while(intsetGet(o
->ptr
,ii
++,&llval
)) {
504 int cmd_items
= (items
> REDIS_AOFREWRITE_ITEMS_PER_CMD
) ?
505 REDIS_AOFREWRITE_ITEMS_PER_CMD
: items
;
507 if (rioWriteBulkCount(r
,'*',2+cmd_items
) == 0) return 0;
508 if (rioWriteBulkString(r
,"SADD",4) == 0) return 0;
509 if (rioWriteBulkObject(r
,key
) == 0) return 0;
511 if (rioWriteBulkLongLong(r
,llval
) == 0) return 0;
512 if (++count
== REDIS_AOFREWRITE_ITEMS_PER_CMD
) count
= 0;
515 } else if (o
->encoding
== REDIS_ENCODING_HT
) {
516 dictIterator
*di
= dictGetIterator(o
->ptr
);
519 while((de
= dictNext(di
)) != NULL
) {
520 robj
*eleobj
= dictGetKey(de
);
522 int cmd_items
= (items
> REDIS_AOFREWRITE_ITEMS_PER_CMD
) ?
523 REDIS_AOFREWRITE_ITEMS_PER_CMD
: items
;
525 if (rioWriteBulkCount(r
,'*',2+cmd_items
) == 0) return 0;
526 if (rioWriteBulkString(r
,"SADD",4) == 0) return 0;
527 if (rioWriteBulkObject(r
,key
) == 0) return 0;
529 if (rioWriteBulkObject(r
,eleobj
) == 0) return 0;
530 if (++count
== REDIS_AOFREWRITE_ITEMS_PER_CMD
) count
= 0;
533 dictReleaseIterator(di
);
535 redisPanic("Unknown set encoding");
540 /* Emit the commands needed to rebuild a sorted set object.
541 * The function returns 0 on error, 1 on success. */
542 int rewriteSortedSetObject(rio
*r
, robj
*key
, robj
*o
) {
543 long long count
= 0, items
= zsetLength(o
);
545 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
546 unsigned char *zl
= o
->ptr
;
547 unsigned char *eptr
, *sptr
;
553 eptr
= ziplistIndex(zl
,0);
554 redisAssert(eptr
!= NULL
);
555 sptr
= ziplistNext(zl
,eptr
);
556 redisAssert(sptr
!= NULL
);
558 while (eptr
!= NULL
) {
559 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vll
));
560 score
= zzlGetScore(sptr
);
563 int cmd_items
= (items
> REDIS_AOFREWRITE_ITEMS_PER_CMD
) ?
564 REDIS_AOFREWRITE_ITEMS_PER_CMD
: items
;
566 if (rioWriteBulkCount(r
,'*',2+cmd_items
*2) == 0) return 0;
567 if (rioWriteBulkString(r
,"ZADD",4) == 0) return 0;
568 if (rioWriteBulkObject(r
,key
) == 0) return 0;
570 if (rioWriteBulkDouble(r
,score
) == 0) return 0;
572 if (rioWriteBulkString(r
,(char*)vstr
,vlen
) == 0) return 0;
574 if (rioWriteBulkLongLong(r
,vll
) == 0) return 0;
576 zzlNext(zl
,&eptr
,&sptr
);
577 if (++count
== REDIS_AOFREWRITE_ITEMS_PER_CMD
) count
= 0;
580 } else if (o
->encoding
== REDIS_ENCODING_SKIPLIST
) {
582 dictIterator
*di
= dictGetIterator(zs
->dict
);
585 while((de
= dictNext(di
)) != NULL
) {
586 robj
*eleobj
= dictGetKey(de
);
587 double *score
= dictGetVal(de
);
590 int cmd_items
= (items
> REDIS_AOFREWRITE_ITEMS_PER_CMD
) ?
591 REDIS_AOFREWRITE_ITEMS_PER_CMD
: items
;
593 if (rioWriteBulkCount(r
,'*',2+cmd_items
*2) == 0) return 0;
594 if (rioWriteBulkString(r
,"ZADD",4) == 0) return 0;
595 if (rioWriteBulkObject(r
,key
) == 0) return 0;
597 if (rioWriteBulkDouble(r
,*score
) == 0) return 0;
598 if (rioWriteBulkObject(r
,eleobj
) == 0) return 0;
599 if (++count
== REDIS_AOFREWRITE_ITEMS_PER_CMD
) count
= 0;
602 dictReleaseIterator(di
);
604 redisPanic("Unknown sorted zset encoding");
609 /* Emit the commands needed to rebuild a hash object.
610 * The function returns 0 on error, 1 on success. */
611 int rewriteHashObject(rio
*r
, robj
*key
, robj
*o
) {
612 long long count
= 0, items
= hashTypeLength(o
);
614 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
615 unsigned char *p
= zipmapRewind(o
->ptr
);
616 unsigned char *field
, *val
;
617 unsigned int flen
, vlen
;
619 while((p
= zipmapNext(p
,&field
,&flen
,&val
,&vlen
)) != NULL
) {
621 int cmd_items
= (items
> REDIS_AOFREWRITE_ITEMS_PER_CMD
) ?
622 REDIS_AOFREWRITE_ITEMS_PER_CMD
: items
;
624 if (rioWriteBulkCount(r
,'*',2+cmd_items
*2) == 0) return 0;
625 if (rioWriteBulkString(r
,"HMSET",5) == 0) return 0;
626 if (rioWriteBulkObject(r
,key
) == 0) return 0;
628 if (rioWriteBulkString(r
,(char*)field
,flen
) == 0) return 0;
629 if (rioWriteBulkString(r
,(char*)val
,vlen
) == 0) return 0;
630 if (++count
== REDIS_AOFREWRITE_ITEMS_PER_CMD
) count
= 0;
634 dictIterator
*di
= dictGetIterator(o
->ptr
);
637 while((de
= dictNext(di
)) != NULL
) {
638 robj
*field
= dictGetKey(de
);
639 robj
*val
= dictGetVal(de
);
642 int cmd_items
= (items
> REDIS_AOFREWRITE_ITEMS_PER_CMD
) ?
643 REDIS_AOFREWRITE_ITEMS_PER_CMD
: items
;
645 if (rioWriteBulkCount(r
,'*',2+cmd_items
*2) == 0) return 0;
646 if (rioWriteBulkString(r
,"HMSET",5) == 0) return 0;
647 if (rioWriteBulkObject(r
,key
) == 0) return 0;
649 if (rioWriteBulkObject(r
,field
) == 0) return 0;
650 if (rioWriteBulkObject(r
,val
) == 0) return 0;
651 if (++count
== REDIS_AOFREWRITE_ITEMS_PER_CMD
) count
= 0;
654 dictReleaseIterator(di
);
659 /* Write a sequence of commands able to fully rebuild the dataset into
660 * "filename". Used both by REWRITEAOF and BGREWRITEAOF.
662 * In order to minimize the number of commands needed in the rewritten
663 * log Redis uses variadic commands when possible, such as RPUSH, SADD
664 * and ZADD. However at max REDIS_AOFREWRITE_ITEMS_PER_CMD items per time
665 * are inserted using a single command. */
666 int rewriteAppendOnlyFile(char *filename
) {
667 dictIterator
*di
= NULL
;
673 long long now
= mstime();
675 /* Note that we have to use a different temp name here compared to the
676 * one used by rewriteAppendOnlyFileBackground() function. */
677 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
678 fp
= fopen(tmpfile
,"w");
680 redisLog(REDIS_WARNING
, "Failed rewriting the append only file: %s", strerror(errno
));
684 rioInitWithFile(&aof
,fp
);
685 for (j
= 0; j
< server
.dbnum
; j
++) {
686 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
687 redisDb
*db
= server
.db
+j
;
689 if (dictSize(d
) == 0) continue;
690 di
= dictGetSafeIterator(d
);
696 /* SELECT the new DB */
697 if (rioWrite(&aof
,selectcmd
,sizeof(selectcmd
)-1) == 0) goto werr
;
698 if (rioWriteBulkLongLong(&aof
,j
) == 0) goto werr
;
700 /* Iterate this DB writing every entry */
701 while((de
= dictNext(di
)) != NULL
) {
704 long long expiretime
;
706 keystr
= dictGetKey(de
);
708 initStaticStringObject(key
,keystr
);
710 expiretime
= getExpire(db
,&key
);
712 /* Save the key and associated value */
713 if (o
->type
== REDIS_STRING
) {
714 /* Emit a SET command */
715 char cmd
[]="*3\r\n$3\r\nSET\r\n";
716 if (rioWrite(&aof
,cmd
,sizeof(cmd
)-1) == 0) goto werr
;
718 if (rioWriteBulkObject(&aof
,&key
) == 0) goto werr
;
719 if (rioWriteBulkObject(&aof
,o
) == 0) goto werr
;
720 } else if (o
->type
== REDIS_LIST
) {
721 if (rewriteListObject(&aof
,&key
,o
) == 0) goto werr
;
722 } else if (o
->type
== REDIS_SET
) {
723 if (rewriteSetObject(&aof
,&key
,o
) == 0) goto werr
;
724 } else if (o
->type
== REDIS_ZSET
) {
725 if (rewriteSortedSetObject(&aof
,&key
,o
) == 0) goto werr
;
726 } else if (o
->type
== REDIS_HASH
) {
727 if (rewriteHashObject(&aof
,&key
,o
) == 0) goto werr
;
729 redisPanic("Unknown object type");
731 /* Save the expire time */
732 if (expiretime
!= -1) {
733 char cmd
[]="*3\r\n$9\r\nPEXPIREAT\r\n";
734 /* If this key is already expired skip it */
735 if (expiretime
< now
) continue;
736 if (rioWrite(&aof
,cmd
,sizeof(cmd
)-1) == 0) goto werr
;
737 if (rioWriteBulkObject(&aof
,&key
) == 0) goto werr
;
738 if (rioWriteBulkLongLong(&aof
,expiretime
) == 0) goto werr
;
741 dictReleaseIterator(di
);
744 /* Make sure data will not remain on the OS's output buffers */
746 aof_fsync(fileno(fp
));
749 /* Use RENAME to make sure the DB file is changed atomically only
750 * if the generate DB file is ok. */
751 if (rename(tmpfile
,filename
) == -1) {
752 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
756 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
762 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
763 if (di
) dictReleaseIterator(di
);
767 /* This is how rewriting of the append only file in background works:
769 * 1) The user calls BGREWRITEAOF
770 * 2) Redis calls this function, that forks():
771 * 2a) the child rewrite the append only file in a temp file.
772 * 2b) the parent accumulates differences in server.bgrewritebuf.
773 * 3) When the child finished '2a' exists.
774 * 4) The parent will trap the exit code, if it's OK, will append the
775 * data accumulated into server.bgrewritebuf into the temp file, and
776 * finally will rename(2) the temp file in the actual file name.
777 * The the new file is reopened as the new append only file. Profit!
779 int rewriteAppendOnlyFileBackground(void) {
783 if (server
.bgrewritechildpid
!= -1) return REDIS_ERR
;
785 if ((childpid
= fork()) == 0) {
789 if (server
.ipfd
> 0) close(server
.ipfd
);
790 if (server
.sofd
> 0) close(server
.sofd
);
791 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
792 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
799 server
.stat_fork_time
= ustime()-start
;
800 if (childpid
== -1) {
801 redisLog(REDIS_WARNING
,
802 "Can't rewrite append only file in background: fork: %s",
806 redisLog(REDIS_NOTICE
,
807 "Background append only file rewriting started by pid %d",childpid
);
808 server
.aofrewrite_scheduled
= 0;
809 server
.bgrewritechildpid
= childpid
;
810 updateDictResizePolicy();
811 /* We set appendseldb to -1 in order to force the next call to the
812 * feedAppendOnlyFile() to issue a SELECT command, so the differences
813 * accumulated by the parent into server.bgrewritebuf will start
814 * with a SELECT statement and it will be safe to merge. */
815 server
.appendseldb
= -1;
818 return REDIS_OK
; /* unreached */
821 void bgrewriteaofCommand(redisClient
*c
) {
822 if (server
.bgrewritechildpid
!= -1) {
823 addReplyError(c
,"Background append only file rewriting already in progress");
824 } else if (server
.bgsavechildpid
!= -1) {
825 server
.aofrewrite_scheduled
= 1;
826 addReplyStatus(c
,"Background append only file rewriting scheduled");
827 } else if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
828 addReplyStatus(c
,"Background append only file rewriting started");
830 addReply(c
,shared
.err
);
834 void aofRemoveTempFile(pid_t childpid
) {
837 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
841 /* Update the server.appendonly_current_size filed explicitly using stat(2)
842 * to check the size of the file. This is useful after a rewrite or after
843 * a restart, normally the size is updated just adding the write length
844 * to the current lenght, that is much faster. */
845 void aofUpdateCurrentSize(void) {
846 struct redis_stat sb
;
848 if (redis_fstat(server
.appendfd
,&sb
) == -1) {
849 redisLog(REDIS_WARNING
,"Unable to check the AOF length: %s",
852 server
.appendonly_current_size
= sb
.st_size
;
856 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
858 void backgroundRewriteDoneHandler(int exitcode
, int bysignal
) {
859 if (!bysignal
&& exitcode
== 0) {
863 long long now
= ustime();
865 redisLog(REDIS_NOTICE
,
866 "Background AOF rewrite terminated with success");
868 /* Flush the differences accumulated by the parent to the
870 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof",
871 (int)server
.bgrewritechildpid
);
872 newfd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
874 redisLog(REDIS_WARNING
,
875 "Unable to open the temporary AOF produced by the child: %s", strerror(errno
));
879 nwritten
= write(newfd
,server
.bgrewritebuf
,sdslen(server
.bgrewritebuf
));
880 if (nwritten
!= (signed)sdslen(server
.bgrewritebuf
)) {
881 if (nwritten
== -1) {
882 redisLog(REDIS_WARNING
,
883 "Error trying to flush the parent diff to the rewritten AOF: %s", strerror(errno
));
885 redisLog(REDIS_WARNING
,
886 "Short write trying to flush the parent diff to the rewritten AOF: %s", strerror(errno
));
892 redisLog(REDIS_NOTICE
,
893 "Parent diff successfully flushed to the rewritten AOF (%lu bytes)", nwritten
);
895 /* The only remaining thing to do is to rename the temporary file to
896 * the configured file and switch the file descriptor used to do AOF
897 * writes. We don't want close(2) or rename(2) calls to block the
898 * server on old file deletion.
900 * There are two possible scenarios:
902 * 1) AOF is DISABLED and this was a one time rewrite. The temporary
903 * file will be renamed to the configured file. When this file already
904 * exists, it will be unlinked, which may block the server.
906 * 2) AOF is ENABLED and the rewritten AOF will immediately start
907 * receiving writes. After the temporary file is renamed to the
908 * configured file, the original AOF file descriptor will be closed.
909 * Since this will be the last reference to that file, closing it
910 * causes the underlying file to be unlinked, which may block the
913 * To mitigate the blocking effect of the unlink operation (either
914 * caused by rename(2) in scenario 1, or by close(2) in scenario 2), we
915 * use a background thread to take care of this. First, we
916 * make scenario 1 identical to scenario 2 by opening the target file
917 * when it exists. The unlink operation after the rename(2) will then
918 * be executed upon calling close(2) for its descriptor. Everything to
919 * guarantee atomicity for this switch has already happened by then, so
920 * we don't care what the outcome or duration of that close operation
921 * is, as long as the file descriptor is released again. */
922 if (server
.appendfd
== -1) {
925 /* Don't care if this fails: oldfd will be -1 and we handle that.
926 * One notable case of -1 return is if the old file does
928 oldfd
= open(server
.appendfilename
,O_RDONLY
|O_NONBLOCK
);
931 oldfd
= -1; /* We'll set this to the current AOF filedes later. */
934 /* Rename the temporary file. This will not unlink the target file if
935 * it exists, because we reference it with "oldfd". */
936 if (rename(tmpfile
,server
.appendfilename
) == -1) {
937 redisLog(REDIS_WARNING
,
938 "Error trying to rename the temporary AOF: %s", strerror(errno
));
940 if (oldfd
!= -1) close(oldfd
);
944 if (server
.appendfd
== -1) {
945 /* AOF disabled, we don't need to set the AOF file descriptor
946 * to this new file, so we can close it. */
949 /* AOF enabled, replace the old fd with the new one. */
950 oldfd
= server
.appendfd
;
951 server
.appendfd
= newfd
;
952 if (server
.appendfsync
== APPENDFSYNC_ALWAYS
)
954 else if (server
.appendfsync
== APPENDFSYNC_EVERYSEC
)
955 aof_background_fsync(newfd
);
956 server
.appendseldb
= -1; /* Make sure SELECT is re-issued */
957 aofUpdateCurrentSize();
958 server
.auto_aofrewrite_base_size
= server
.appendonly_current_size
;
960 /* Clear regular AOF buffer since its contents was just written to
961 * the new AOF from the background rewrite buffer. */
962 sdsfree(server
.aofbuf
);
963 server
.aofbuf
= sdsempty();
966 redisLog(REDIS_NOTICE
, "Background AOF rewrite successful");
967 server
.aof_wait_rewrite
= 0;
969 /* Asynchronously close the overwritten AOF. */
970 if (oldfd
!= -1) bioCreateBackgroundJob(REDIS_BIO_CLOSE_FILE
,(void*)(long)oldfd
,NULL
,NULL
);
972 redisLog(REDIS_VERBOSE
,
973 "Background AOF rewrite signal handler took %lldus", ustime()-now
);
974 } else if (!bysignal
&& exitcode
!= 0) {
975 redisLog(REDIS_WARNING
,
976 "Background AOF rewrite terminated with error");
978 redisLog(REDIS_WARNING
,
979 "Background AOF rewrite terminated by signal %d", bysignal
);
983 sdsfree(server
.bgrewritebuf
);
984 server
.bgrewritebuf
= sdsempty();
985 aofRemoveTempFile(server
.bgrewritechildpid
);
986 server
.bgrewritechildpid
= -1;
987 /* If we were waiting for an AOF rewrite before to start appending
988 * to the AOF again (this happens both when the user switches on
989 * AOF with CONFIG SET, and after a slave with AOF enabled syncs with
990 * the master), but the rewrite failed (otherwise aof_wait_rewrite
991 * would be zero), we need to schedule a new one. */
992 if (server
.aof_wait_rewrite
) server
.aofrewrite_scheduled
= 1;