10 #include <sys/resource.h>
13 void aofUpdateCurrentSize(void);
15 /* ----------------------------------------------------------------------------
16 * AOF file implementation
17 * ------------------------------------------------------------------------- */
19 /* Starts a background task that performs fsync() against the specified
20 * file descriptor (the one of the AOF file) in another thread. */
21 void aof_background_fsync(int fd
) {
22 bioCreateBackgroundJob(REDIS_BIO_AOF_FSYNC
,(void*)(long)fd
,NULL
,NULL
);
25 /* Called when the user switches from "appendonly yes" to "appendonly no"
26 * at runtime using the CONFIG command. */
27 void stopAppendOnly(void) {
28 redisAssert(server
.aof_state
!= REDIS_AOF_OFF
);
29 flushAppendOnlyFile(1);
30 aof_fsync(server
.aof_fd
);
34 server
.aof_selected_db
= -1;
35 server
.aof_state
= REDIS_AOF_OFF
;
36 /* rewrite operation in progress? kill it, wait child exit */
37 if (server
.aof_child_pid
!= -1) {
40 redisLog(REDIS_NOTICE
,"Killing running AOF rewrite child: %ld",
41 (long) server
.aof_child_pid
);
42 if (kill(server
.aof_child_pid
,SIGKILL
) != -1)
43 wait3(&statloc
,0,NULL
);
44 /* reset the buffer accumulating changes while the child saves */
45 sdsfree(server
.aof_rewrite_buf
);
46 server
.aof_rewrite_buf
= sdsempty();
47 aofRemoveTempFile(server
.aof_child_pid
);
48 server
.aof_child_pid
= -1;
52 /* Called when the user switches from "appendonly no" to "appendonly yes"
53 * at runtime using the CONFIG command. */
54 int startAppendOnly(void) {
55 server
.aof_last_fsync
= server
.unixtime
;
56 server
.aof_fd
= open(server
.aof_filename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
57 redisAssert(server
.aof_state
== REDIS_AOF_OFF
);
58 if (server
.aof_fd
== -1) {
59 redisLog(REDIS_WARNING
,"Redis needs to enable the AOF but can't open the append only file: %s",strerror(errno
));
62 if (rewriteAppendOnlyFileBackground() == REDIS_ERR
) {
64 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.");
67 /* We correctly switched on AOF, now wait for the rerwite to be complete
68 * in order to append data on disk. */
69 server
.aof_state
= REDIS_AOF_WAIT_REWRITE
;
73 /* Write the append only file buffer on disk.
75 * Since we are required to write the AOF before replying to the client,
76 * and the only way the client socket can get a write is entering when the
77 * the event loop, we accumulate all the AOF writes in a memory
78 * buffer and write it on disk using this function just before entering
79 * the event loop again.
81 * About the 'force' argument:
83 * When the fsync policy is set to 'everysec' we may delay the flush if there
84 * is still an fsync() going on in the background thread, since for instance
85 * on Linux write(2) will be blocked by the background fsync anyway.
86 * When this happens we remember that there is some aof buffer to be
87 * flushed ASAP, and will try to do that in the serverCron() function.
89 * However if force is set to 1 we'll write regardless of the background
91 void flushAppendOnlyFile(int force
) {
93 int sync_in_progress
= 0;
95 if (sdslen(server
.aof_buf
) == 0) return;
97 if (server
.aof_fsync
== AOF_FSYNC_EVERYSEC
)
98 sync_in_progress
= bioPendingJobsOfType(REDIS_BIO_AOF_FSYNC
) != 0;
100 if (server
.aof_fsync
== AOF_FSYNC_EVERYSEC
&& !force
) {
101 /* With this append fsync policy we do background fsyncing.
102 * If the fsync is still in progress we can try to delay
103 * the write for a couple of seconds. */
104 if (sync_in_progress
) {
105 if (server
.aof_flush_postponed_start
== 0) {
106 /* No previous write postponinig, remember that we are
107 * postponing the flush and return. */
108 server
.aof_flush_postponed_start
= server
.unixtime
;
110 } else if (server
.unixtime
- server
.aof_flush_postponed_start
< 2) {
111 /* We were already waiting for fsync to finish, but for less
112 * than two seconds this is still ok. Postpone again. */
115 /* Otherwise fall trough, and go write since we can't wait
116 * over two seconds. */
117 server
.aof_delayed_fsync
++;
118 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.");
121 /* If you are following this code path, then we are going to write so
122 * set reset the postponed flush sentinel to zero. */
123 server
.aof_flush_postponed_start
= 0;
125 /* We want to perform a single write. This should be guaranteed atomic
126 * at least if the filesystem we are writing is a real physical one.
127 * While this will save us against the server being killed I don't think
128 * there is much to do about the whole server stopping for power problems
130 nwritten
= write(server
.aof_fd
,server
.aof_buf
,sdslen(server
.aof_buf
));
131 if (nwritten
!= (signed)sdslen(server
.aof_buf
)) {
132 /* Ooops, we are in troubles. The best thing to do for now is
133 * aborting instead of giving the illusion that everything is
134 * working as expected. */
135 if (nwritten
== -1) {
136 redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
));
138 redisLog(REDIS_WARNING
,"Exiting on short write while writing to "
139 "the append-only file: %s (nwritten=%ld, "
143 (long)sdslen(server
.aof_buf
));
147 server
.aof_current_size
+= nwritten
;
149 /* Re-use AOF buffer when it is small enough. The maximum comes from the
150 * arena size of 4k minus some overhead (but is otherwise arbitrary). */
151 if ((sdslen(server
.aof_buf
)+sdsavail(server
.aof_buf
)) < 4000) {
152 sdsclear(server
.aof_buf
);
154 sdsfree(server
.aof_buf
);
155 server
.aof_buf
= sdsempty();
158 /* Don't fsync if no-appendfsync-on-rewrite is set to yes and there are
159 * children doing I/O in the background. */
160 if (server
.aof_no_fsync_on_rewrite
&&
161 (server
.aof_child_pid
!= -1 || server
.rdb_child_pid
!= -1))
164 /* Perform the fsync if needed. */
165 if (server
.aof_fsync
== AOF_FSYNC_ALWAYS
) {
166 /* aof_fsync is defined as fdatasync() for Linux in order to avoid
167 * flushing metadata. */
168 aof_fsync(server
.aof_fd
); /* Let's try to get this data on the disk */
169 server
.aof_last_fsync
= server
.unixtime
;
170 } else if ((server
.aof_fsync
== AOF_FSYNC_EVERYSEC
&&
171 server
.unixtime
> server
.aof_last_fsync
)) {
172 if (!sync_in_progress
) aof_background_fsync(server
.aof_fd
);
173 server
.aof_last_fsync
= server
.unixtime
;
177 sds
catAppendOnlyGenericCommand(sds dst
, int argc
, robj
**argv
) {
183 len
= 1+ll2string(buf
+1,sizeof(buf
)-1,argc
);
186 dst
= sdscatlen(dst
,buf
,len
);
188 for (j
= 0; j
< argc
; j
++) {
189 o
= getDecodedObject(argv
[j
]);
191 len
= 1+ll2string(buf
+1,sizeof(buf
)-1,sdslen(o
->ptr
));
194 dst
= sdscatlen(dst
,buf
,len
);
195 dst
= sdscatlen(dst
,o
->ptr
,sdslen(o
->ptr
));
196 dst
= sdscatlen(dst
,"\r\n",2);
202 /* Create the sds representation of an PEXPIREAT command, using
203 * 'seconds' as time to live and 'cmd' to understand what command
204 * we are translating into a PEXPIREAT.
206 * This command is used in order to translate EXPIRE and PEXPIRE commands
207 * into PEXPIREAT command so that we retain precision in the append only
208 * file, and the time is always absolute and not relative. */
209 sds
catAppendOnlyExpireAtCommand(sds buf
, struct redisCommand
*cmd
, robj
*key
, robj
*seconds
) {
213 /* Make sure we can use strtol */
214 seconds
= getDecodedObject(seconds
);
215 when
= strtoll(seconds
->ptr
,NULL
,10);
216 /* Convert argument into milliseconds for EXPIRE, SETEX, EXPIREAT */
217 if (cmd
->proc
== expireCommand
|| cmd
->proc
== setexCommand
||
218 cmd
->proc
== expireatCommand
)
222 /* Convert into absolute time for EXPIRE, PEXPIRE, SETEX, PSETEX */
223 if (cmd
->proc
== expireCommand
|| cmd
->proc
== pexpireCommand
||
224 cmd
->proc
== setexCommand
|| cmd
->proc
== psetexCommand
)
228 decrRefCount(seconds
);
230 argv
[0] = createStringObject("PEXPIREAT",9);
232 argv
[2] = createStringObjectFromLongLong(when
);
233 buf
= catAppendOnlyGenericCommand(buf
, 3, argv
);
234 decrRefCount(argv
[0]);
235 decrRefCount(argv
[2]);
239 void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
240 sds buf
= sdsempty();
243 /* The DB this command was targetting is not the same as the last command
244 * we appendend. To issue a SELECT command is needed. */
245 if (dictid
!= server
.aof_selected_db
) {
248 snprintf(seldb
,sizeof(seldb
),"%d",dictid
);
249 buf
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
250 (unsigned long)strlen(seldb
),seldb
);
251 server
.aof_selected_db
= dictid
;
254 if (cmd
->proc
== expireCommand
|| cmd
->proc
== pexpireCommand
||
255 cmd
->proc
== expireatCommand
) {
256 /* Translate EXPIRE/PEXPIRE/EXPIREAT into PEXPIREAT */
257 buf
= catAppendOnlyExpireAtCommand(buf
,cmd
,argv
[1],argv
[2]);
258 } else if (cmd
->proc
== setexCommand
|| cmd
->proc
== psetexCommand
) {
259 /* Translate SETEX/PSETEX to SET and PEXPIREAT */
260 tmpargv
[0] = createStringObject("SET",3);
261 tmpargv
[1] = argv
[1];
262 tmpargv
[2] = argv
[3];
263 buf
= catAppendOnlyGenericCommand(buf
,3,tmpargv
);
264 decrRefCount(tmpargv
[0]);
265 buf
= catAppendOnlyExpireAtCommand(buf
,cmd
,argv
[1],argv
[2]);
267 /* All the other commands don't need translation or need the
268 * same translation already operated in the command vector
269 * for the replication itself. */
270 buf
= catAppendOnlyGenericCommand(buf
,argc
,argv
);
273 /* Append to the AOF buffer. This will be flushed on disk just before
274 * of re-entering the event loop, so before the client will get a
275 * positive reply about the operation performed. */
276 if (server
.aof_state
== REDIS_AOF_ON
)
277 server
.aof_buf
= sdscatlen(server
.aof_buf
,buf
,sdslen(buf
));
279 /* If a background append only file rewriting is in progress we want to
280 * accumulate the differences between the child DB and the current one
281 * in a buffer, so that when the child process will do its work we
282 * can append the differences to the new append only file. */
283 if (server
.aof_child_pid
!= -1)
284 server
.aof_rewrite_buf
= sdscatlen(server
.aof_rewrite_buf
,buf
,sdslen(buf
));
289 /* ----------------------------------------------------------------------------
291 * ------------------------------------------------------------------------- */
293 /* In Redis commands are always executed in the context of a client, so in
294 * order to load the append only file we need to create a fake client. */
295 struct redisClient
*createFakeClient(void) {
296 struct redisClient
*c
= zmalloc(sizeof(*c
));
300 c
->querybuf
= sdsempty();
301 c
->querybuf_peak
= 0;
306 /* We set the fake client as a slave waiting for the synchronization
307 * so that Redis will not try to send replies to this client. */
308 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
309 c
->reply
= listCreate();
311 c
->obuf_soft_limit_reached_time
= 0;
312 c
->watched_keys
= listCreate();
313 listSetFreeMethod(c
->reply
,decrRefCount
);
314 listSetDupMethod(c
->reply
,dupClientReplyValue
);
315 initClientMultiState(c
);
319 void freeFakeClient(struct redisClient
*c
) {
320 sdsfree(c
->querybuf
);
321 listRelease(c
->reply
);
322 listRelease(c
->watched_keys
);
323 freeClientMultiState(c
);
327 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
328 * error (the append only file is zero-length) REDIS_ERR is returned. On
329 * fatal error an error message is logged and the program exists. */
330 int loadAppendOnlyFile(char *filename
) {
331 struct redisClient
*fakeClient
;
332 FILE *fp
= fopen(filename
,"r");
333 struct redis_stat sb
;
334 int old_aof_state
= server
.aof_state
;
337 if (fp
&& redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0) {
338 server
.aof_current_size
= 0;
344 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
348 /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
349 * to the same file we're about to read. */
350 server
.aof_state
= REDIS_AOF_OFF
;
352 fakeClient
= createFakeClient();
361 struct redisCommand
*cmd
;
363 /* Serve the clients from time to time */
364 if (!(loops
++ % 1000)) {
365 loadingProgress(ftello(fp
));
366 aeProcessEvents(server
.el
, AE_FILE_EVENTS
|AE_DONT_WAIT
);
369 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
375 if (buf
[0] != '*') goto fmterr
;
377 if (argc
< 1) goto fmterr
;
379 argv
= zmalloc(sizeof(robj
*)*argc
);
380 for (j
= 0; j
< argc
; j
++) {
381 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
382 if (buf
[0] != '$') goto fmterr
;
383 len
= strtol(buf
+1,NULL
,10);
384 argsds
= sdsnewlen(NULL
,len
);
385 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
386 argv
[j
] = createObject(REDIS_STRING
,argsds
);
387 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
391 cmd
= lookupCommand(argv
[0]->ptr
);
393 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
396 /* Run the command in the context of a fake client */
397 fakeClient
->argc
= argc
;
398 fakeClient
->argv
= argv
;
399 cmd
->proc(fakeClient
);
401 /* The fake client should not have a reply */
402 redisAssert(fakeClient
->bufpos
== 0 && listLength(fakeClient
->reply
) == 0);
403 /* The fake client should never get blocked */
404 redisAssert((fakeClient
->flags
& REDIS_BLOCKED
) == 0);
406 /* Clean up. Command code may have changed argv/argc so we use the
407 * argv/argc of the client instead of the local variables. */
408 for (j
= 0; j
< fakeClient
->argc
; j
++)
409 decrRefCount(fakeClient
->argv
[j
]);
410 zfree(fakeClient
->argv
);
413 /* This point can only be reached when EOF is reached without errors.
414 * If the client is in the middle of a MULTI/EXEC, log error and quit. */
415 if (fakeClient
->flags
& REDIS_MULTI
) goto readerr
;
418 freeFakeClient(fakeClient
);
419 server
.aof_state
= old_aof_state
;
421 aofUpdateCurrentSize();
422 server
.aof_rewrite_base_size
= server
.aof_current_size
;
427 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
429 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
433 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>");
437 /* ----------------------------------------------------------------------------
439 * ------------------------------------------------------------------------- */
441 /* Delegate writing an object to writing a bulk string or bulk long long.
442 * This is not placed in rio.c since that adds the redis.h dependency. */
443 int rioWriteBulkObject(rio
*r
, robj
*obj
) {
444 /* Avoid using getDecodedObject to help copy-on-write (we are often
445 * in a child process when this function is called). */
446 if (obj
->encoding
== REDIS_ENCODING_INT
) {
447 return rioWriteBulkLongLong(r
,(long)obj
->ptr
);
448 } else if (obj
->encoding
== REDIS_ENCODING_RAW
) {
449 return rioWriteBulkString(r
,obj
->ptr
,sdslen(obj
->ptr
));
451 redisPanic("Unknown string encoding");
455 /* Emit the commands needed to rebuild a list object.
456 * The function returns 0 on error, 1 on success. */
457 int rewriteListObject(rio
*r
, robj
*key
, robj
*o
) {
458 long long count
= 0, items
= listTypeLength(o
);
460 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
461 unsigned char *zl
= o
->ptr
;
462 unsigned char *p
= ziplistIndex(zl
,0);
467 while(ziplistGet(p
,&vstr
,&vlen
,&vlong
)) {
469 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
470 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
472 if (rioWriteBulkCount(r
,'*',2+cmd_items
) == 0) return 0;
473 if (rioWriteBulkString(r
,"RPUSH",5) == 0) return 0;
474 if (rioWriteBulkObject(r
,key
) == 0) return 0;
477 if (rioWriteBulkString(r
,(char*)vstr
,vlen
) == 0) return 0;
479 if (rioWriteBulkLongLong(r
,vlong
) == 0) return 0;
481 p
= ziplistNext(zl
,p
);
482 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
485 } else if (o
->encoding
== REDIS_ENCODING_LINKEDLIST
) {
490 listRewind(list
,&li
);
491 while((ln
= listNext(&li
))) {
492 robj
*eleobj
= listNodeValue(ln
);
495 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
496 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
498 if (rioWriteBulkCount(r
,'*',2+cmd_items
) == 0) return 0;
499 if (rioWriteBulkString(r
,"RPUSH",5) == 0) return 0;
500 if (rioWriteBulkObject(r
,key
) == 0) return 0;
502 if (rioWriteBulkObject(r
,eleobj
) == 0) return 0;
503 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
507 redisPanic("Unknown list encoding");
512 /* Emit the commands needed to rebuild a set object.
513 * The function returns 0 on error, 1 on success. */
514 int rewriteSetObject(rio
*r
, robj
*key
, robj
*o
) {
515 long long count
= 0, items
= setTypeSize(o
);
517 if (o
->encoding
== REDIS_ENCODING_INTSET
) {
521 while(intsetGet(o
->ptr
,ii
++,&llval
)) {
523 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
524 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
526 if (rioWriteBulkCount(r
,'*',2+cmd_items
) == 0) return 0;
527 if (rioWriteBulkString(r
,"SADD",4) == 0) return 0;
528 if (rioWriteBulkObject(r
,key
) == 0) return 0;
530 if (rioWriteBulkLongLong(r
,llval
) == 0) return 0;
531 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
534 } else if (o
->encoding
== REDIS_ENCODING_HT
) {
535 dictIterator
*di
= dictGetIterator(o
->ptr
);
538 while((de
= dictNext(di
)) != NULL
) {
539 robj
*eleobj
= dictGetKey(de
);
541 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
542 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
544 if (rioWriteBulkCount(r
,'*',2+cmd_items
) == 0) return 0;
545 if (rioWriteBulkString(r
,"SADD",4) == 0) return 0;
546 if (rioWriteBulkObject(r
,key
) == 0) return 0;
548 if (rioWriteBulkObject(r
,eleobj
) == 0) return 0;
549 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
552 dictReleaseIterator(di
);
554 redisPanic("Unknown set encoding");
559 /* Emit the commands needed to rebuild a sorted set object.
560 * The function returns 0 on error, 1 on success. */
561 int rewriteSortedSetObject(rio
*r
, robj
*key
, robj
*o
) {
562 long long count
= 0, items
= zsetLength(o
);
564 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
565 unsigned char *zl
= o
->ptr
;
566 unsigned char *eptr
, *sptr
;
572 eptr
= ziplistIndex(zl
,0);
573 redisAssert(eptr
!= NULL
);
574 sptr
= ziplistNext(zl
,eptr
);
575 redisAssert(sptr
!= NULL
);
577 while (eptr
!= NULL
) {
578 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vll
));
579 score
= zzlGetScore(sptr
);
582 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
583 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
585 if (rioWriteBulkCount(r
,'*',2+cmd_items
*2) == 0) return 0;
586 if (rioWriteBulkString(r
,"ZADD",4) == 0) return 0;
587 if (rioWriteBulkObject(r
,key
) == 0) return 0;
589 if (rioWriteBulkDouble(r
,score
) == 0) return 0;
591 if (rioWriteBulkString(r
,(char*)vstr
,vlen
) == 0) return 0;
593 if (rioWriteBulkLongLong(r
,vll
) == 0) return 0;
595 zzlNext(zl
,&eptr
,&sptr
);
596 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
599 } else if (o
->encoding
== REDIS_ENCODING_SKIPLIST
) {
601 dictIterator
*di
= dictGetIterator(zs
->dict
);
604 while((de
= dictNext(di
)) != NULL
) {
605 robj
*eleobj
= dictGetKey(de
);
606 double *score
= dictGetVal(de
);
609 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
610 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
612 if (rioWriteBulkCount(r
,'*',2+cmd_items
*2) == 0) return 0;
613 if (rioWriteBulkString(r
,"ZADD",4) == 0) return 0;
614 if (rioWriteBulkObject(r
,key
) == 0) return 0;
616 if (rioWriteBulkDouble(r
,*score
) == 0) return 0;
617 if (rioWriteBulkObject(r
,eleobj
) == 0) return 0;
618 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
621 dictReleaseIterator(di
);
623 redisPanic("Unknown sorted zset encoding");
628 /* Write either the key or the value of the currently selected item of an hash.
629 * The 'hi' argument passes a valid Redis hash iterator.
630 * The 'what' filed specifies if to write a key or a value and can be
631 * either REDIS_HASH_KEY or REDIS_HASH_VALUE.
633 * The function returns 0 on error, non-zero on success. */
634 static int rioWriteHashIteratorCursor(rio
*r
, hashTypeIterator
*hi
, int what
) {
635 if (hi
->encoding
== REDIS_ENCODING_ZIPLIST
) {
636 unsigned char *vstr
= NULL
;
637 unsigned int vlen
= UINT_MAX
;
638 long long vll
= LLONG_MAX
;
640 hashTypeCurrentFromZiplist(hi
, what
, &vstr
, &vlen
, &vll
);
642 return rioWriteBulkString(r
, (char*)vstr
, vlen
);
644 return rioWriteBulkLongLong(r
, vll
);
647 } else if (hi
->encoding
== REDIS_ENCODING_HT
) {
650 hashTypeCurrentFromHashTable(hi
, what
, &value
);
651 return rioWriteBulkObject(r
, value
);
654 redisPanic("Unknown hash encoding");
658 /* Emit the commands needed to rebuild a hash object.
659 * The function returns 0 on error, 1 on success. */
660 int rewriteHashObject(rio
*r
, robj
*key
, robj
*o
) {
661 hashTypeIterator
*hi
;
662 long long count
= 0, items
= hashTypeLength(o
);
664 hi
= hashTypeInitIterator(o
);
665 while (hashTypeNext(hi
) != REDIS_ERR
) {
667 int cmd_items
= (items
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ?
668 REDIS_AOF_REWRITE_ITEMS_PER_CMD
: items
;
670 if (rioWriteBulkCount(r
,'*',2+cmd_items
*2) == 0) return 0;
671 if (rioWriteBulkString(r
,"HMSET",5) == 0) return 0;
672 if (rioWriteBulkObject(r
,key
) == 0) return 0;
675 if (rioWriteHashIteratorCursor(r
, hi
, REDIS_HASH_KEY
) == 0) return 0;
676 if (rioWriteHashIteratorCursor(r
, hi
, REDIS_HASH_VALUE
) == 0) return 0;
677 if (++count
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count
= 0;
681 hashTypeReleaseIterator(hi
);
686 /* Write a sequence of commands able to fully rebuild the dataset into
687 * "filename". Used both by REWRITEAOF and BGREWRITEAOF.
689 * In order to minimize the number of commands needed in the rewritten
690 * log Redis uses variadic commands when possible, such as RPUSH, SADD
691 * and ZADD. However at max REDIS_AOF_REWRITE_ITEMS_PER_CMD items per time
692 * are inserted using a single command. */
693 int rewriteAppendOnlyFile(char *filename
) {
694 dictIterator
*di
= NULL
;
700 long long now
= mstime();
702 /* Note that we have to use a different temp name here compared to the
703 * one used by rewriteAppendOnlyFileBackground() function. */
704 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
705 fp
= fopen(tmpfile
,"w");
707 redisLog(REDIS_WARNING
, "Opening the temp file for AOF rewrite in rewriteAppendOnlyFile(): %s", strerror(errno
));
711 rioInitWithFile(&aof
,fp
);
712 for (j
= 0; j
< server
.dbnum
; j
++) {
713 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
714 redisDb
*db
= server
.db
+j
;
716 if (dictSize(d
) == 0) continue;
717 di
= dictGetSafeIterator(d
);
723 /* SELECT the new DB */
724 if (rioWrite(&aof
,selectcmd
,sizeof(selectcmd
)-1) == 0) goto werr
;
725 if (rioWriteBulkLongLong(&aof
,j
) == 0) goto werr
;
727 /* Iterate this DB writing every entry */
728 while((de
= dictNext(di
)) != NULL
) {
731 long long expiretime
;
733 keystr
= dictGetKey(de
);
735 initStaticStringObject(key
,keystr
);
737 expiretime
= getExpire(db
,&key
);
739 /* Save the key and associated value */
740 if (o
->type
== REDIS_STRING
) {
741 /* Emit a SET command */
742 char cmd
[]="*3\r\n$3\r\nSET\r\n";
743 if (rioWrite(&aof
,cmd
,sizeof(cmd
)-1) == 0) goto werr
;
745 if (rioWriteBulkObject(&aof
,&key
) == 0) goto werr
;
746 if (rioWriteBulkObject(&aof
,o
) == 0) goto werr
;
747 } else if (o
->type
== REDIS_LIST
) {
748 if (rewriteListObject(&aof
,&key
,o
) == 0) goto werr
;
749 } else if (o
->type
== REDIS_SET
) {
750 if (rewriteSetObject(&aof
,&key
,o
) == 0) goto werr
;
751 } else if (o
->type
== REDIS_ZSET
) {
752 if (rewriteSortedSetObject(&aof
,&key
,o
) == 0) goto werr
;
753 } else if (o
->type
== REDIS_HASH
) {
754 if (rewriteHashObject(&aof
,&key
,o
) == 0) goto werr
;
756 redisPanic("Unknown object type");
758 /* Save the expire time */
759 if (expiretime
!= -1) {
760 char cmd
[]="*3\r\n$9\r\nPEXPIREAT\r\n";
761 /* If this key is already expired skip it */
762 if (expiretime
< now
) continue;
763 if (rioWrite(&aof
,cmd
,sizeof(cmd
)-1) == 0) goto werr
;
764 if (rioWriteBulkObject(&aof
,&key
) == 0) goto werr
;
765 if (rioWriteBulkLongLong(&aof
,expiretime
) == 0) goto werr
;
768 dictReleaseIterator(di
);
771 /* Make sure data will not remain on the OS's output buffers */
773 aof_fsync(fileno(fp
));
776 /* Use RENAME to make sure the DB file is changed atomically only
777 * if the generate DB file is ok. */
778 if (rename(tmpfile
,filename
) == -1) {
779 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
783 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
789 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
790 if (di
) dictReleaseIterator(di
);
794 /* This is how rewriting of the append only file in background works:
796 * 1) The user calls BGREWRITEAOF
797 * 2) Redis calls this function, that forks():
798 * 2a) the child rewrite the append only file in a temp file.
799 * 2b) the parent accumulates differences in server.aof_rewrite_buf.
800 * 3) When the child finished '2a' exists.
801 * 4) The parent will trap the exit code, if it's OK, will append the
802 * data accumulated into server.aof_rewrite_buf into the temp file, and
803 * finally will rename(2) the temp file in the actual file name.
804 * The the new file is reopened as the new append only file. Profit!
806 int rewriteAppendOnlyFileBackground(void) {
810 if (server
.aof_child_pid
!= -1) return REDIS_ERR
;
812 if ((childpid
= fork()) == 0) {
816 if (server
.ipfd
> 0) close(server
.ipfd
);
817 if (server
.sofd
> 0) close(server
.sofd
);
818 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
819 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
826 server
.stat_fork_time
= ustime()-start
;
827 if (childpid
== -1) {
828 redisLog(REDIS_WARNING
,
829 "Can't rewrite append only file in background: fork: %s",
833 redisLog(REDIS_NOTICE
,
834 "Background append only file rewriting started by pid %d",childpid
);
835 server
.aof_rewrite_scheduled
= 0;
836 server
.aof_child_pid
= childpid
;
837 updateDictResizePolicy();
838 /* We set appendseldb to -1 in order to force the next call to the
839 * feedAppendOnlyFile() to issue a SELECT command, so the differences
840 * accumulated by the parent into server.aof_rewrite_buf will start
841 * with a SELECT statement and it will be safe to merge. */
842 server
.aof_selected_db
= -1;
845 return REDIS_OK
; /* unreached */
848 void bgrewriteaofCommand(redisClient
*c
) {
849 if (server
.aof_child_pid
!= -1) {
850 addReplyError(c
,"Background append only file rewriting already in progress");
851 } else if (server
.rdb_child_pid
!= -1) {
852 server
.aof_rewrite_scheduled
= 1;
853 addReplyStatus(c
,"Background append only file rewriting scheduled");
854 } else if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
855 addReplyStatus(c
,"Background append only file rewriting started");
857 addReply(c
,shared
.err
);
861 void aofRemoveTempFile(pid_t childpid
) {
864 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
868 /* Update the server.aof_current_size filed explicitly using stat(2)
869 * to check the size of the file. This is useful after a rewrite or after
870 * a restart, normally the size is updated just adding the write length
871 * to the current length, that is much faster. */
872 void aofUpdateCurrentSize(void) {
873 struct redis_stat sb
;
875 if (redis_fstat(server
.aof_fd
,&sb
) == -1) {
876 redisLog(REDIS_WARNING
,"Unable to obtain the AOF file length. stat: %s",
879 server
.aof_current_size
= sb
.st_size
;
883 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
885 void backgroundRewriteDoneHandler(int exitcode
, int bysignal
) {
886 if (!bysignal
&& exitcode
== 0) {
890 long long now
= ustime();
892 redisLog(REDIS_NOTICE
,
893 "Background AOF rewrite terminated with success");
895 /* Flush the differences accumulated by the parent to the
897 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof",
898 (int)server
.aof_child_pid
);
899 newfd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
901 redisLog(REDIS_WARNING
,
902 "Unable to open the temporary AOF produced by the child: %s", strerror(errno
));
906 nwritten
= write(newfd
,server
.aof_rewrite_buf
,sdslen(server
.aof_rewrite_buf
));
907 if (nwritten
!= (signed)sdslen(server
.aof_rewrite_buf
)) {
908 if (nwritten
== -1) {
909 redisLog(REDIS_WARNING
,
910 "Error trying to flush the parent diff to the rewritten AOF: %s", strerror(errno
));
912 redisLog(REDIS_WARNING
,
913 "Short write trying to flush the parent diff to the rewritten AOF: %s", strerror(errno
));
919 redisLog(REDIS_NOTICE
,
920 "Parent diff successfully flushed to the rewritten AOF (%lu bytes)", nwritten
);
922 /* The only remaining thing to do is to rename the temporary file to
923 * the configured file and switch the file descriptor used to do AOF
924 * writes. We don't want close(2) or rename(2) calls to block the
925 * server on old file deletion.
927 * There are two possible scenarios:
929 * 1) AOF is DISABLED and this was a one time rewrite. The temporary
930 * file will be renamed to the configured file. When this file already
931 * exists, it will be unlinked, which may block the server.
933 * 2) AOF is ENABLED and the rewritten AOF will immediately start
934 * receiving writes. After the temporary file is renamed to the
935 * configured file, the original AOF file descriptor will be closed.
936 * Since this will be the last reference to that file, closing it
937 * causes the underlying file to be unlinked, which may block the
940 * To mitigate the blocking effect of the unlink operation (either
941 * caused by rename(2) in scenario 1, or by close(2) in scenario 2), we
942 * use a background thread to take care of this. First, we
943 * make scenario 1 identical to scenario 2 by opening the target file
944 * when it exists. The unlink operation after the rename(2) will then
945 * be executed upon calling close(2) for its descriptor. Everything to
946 * guarantee atomicity for this switch has already happened by then, so
947 * we don't care what the outcome or duration of that close operation
948 * is, as long as the file descriptor is released again. */
949 if (server
.aof_fd
== -1) {
952 /* Don't care if this fails: oldfd will be -1 and we handle that.
953 * One notable case of -1 return is if the old file does
955 oldfd
= open(server
.aof_filename
,O_RDONLY
|O_NONBLOCK
);
958 oldfd
= -1; /* We'll set this to the current AOF filedes later. */
961 /* Rename the temporary file. This will not unlink the target file if
962 * it exists, because we reference it with "oldfd". */
963 if (rename(tmpfile
,server
.aof_filename
) == -1) {
964 redisLog(REDIS_WARNING
,
965 "Error trying to rename the temporary AOF file: %s", strerror(errno
));
967 if (oldfd
!= -1) close(oldfd
);
971 if (server
.aof_fd
== -1) {
972 /* AOF disabled, we don't need to set the AOF file descriptor
973 * to this new file, so we can close it. */
976 /* AOF enabled, replace the old fd with the new one. */
977 oldfd
= server
.aof_fd
;
978 server
.aof_fd
= newfd
;
979 if (server
.aof_fsync
== AOF_FSYNC_ALWAYS
)
981 else if (server
.aof_fsync
== AOF_FSYNC_EVERYSEC
)
982 aof_background_fsync(newfd
);
983 server
.aof_selected_db
= -1; /* Make sure SELECT is re-issued */
984 aofUpdateCurrentSize();
985 server
.aof_rewrite_base_size
= server
.aof_current_size
;
987 /* Clear regular AOF buffer since its contents was just written to
988 * the new AOF from the background rewrite buffer. */
989 sdsfree(server
.aof_buf
);
990 server
.aof_buf
= sdsempty();
993 redisLog(REDIS_NOTICE
, "Background AOF rewrite finished successfully");
994 /* Change state from WAIT_REWRITE to ON if needed */
995 if (server
.aof_state
== REDIS_AOF_WAIT_REWRITE
)
996 server
.aof_state
= REDIS_AOF_ON
;
998 /* Asynchronously close the overwritten AOF. */
999 if (oldfd
!= -1) bioCreateBackgroundJob(REDIS_BIO_CLOSE_FILE
,(void*)(long)oldfd
,NULL
,NULL
);
1001 redisLog(REDIS_VERBOSE
,
1002 "Background AOF rewrite signal handler took %lldus", ustime()-now
);
1003 } else if (!bysignal
&& exitcode
!= 0) {
1004 redisLog(REDIS_WARNING
,
1005 "Background AOF rewrite terminated with error");
1007 redisLog(REDIS_WARNING
,
1008 "Background AOF rewrite terminated by signal %d", bysignal
);
1012 sdsfree(server
.aof_rewrite_buf
);
1013 server
.aof_rewrite_buf
= sdsempty();
1014 aofRemoveTempFile(server
.aof_child_pid
);
1015 server
.aof_child_pid
= -1;
1016 /* Schedule a new rewrite if we are waiting for it to switch the AOF ON. */
1017 if (server
.aof_state
== REDIS_AOF_WAIT_REWRITE
)
1018 server
.aof_rewrite_scheduled
= 1;