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 
= server
.unixtime
; 
  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             server
.aof_delayed_fsync
++; 
 112             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."); 
 115     /* If you are following this code path, then we are going to write so 
 116      * set reset the postponed flush sentinel to zero. */ 
 117     server
.aof_flush_postponed_start 
= 0; 
 119     /* We want to perform a single write. This should be guaranteed atomic 
 120      * at least if the filesystem we are writing is a real physical one. 
 121      * While this will save us against the server being killed I don't think 
 122      * there is much to do about the whole server stopping for power problems 
 124     nwritten 
= write(server
.aof_fd
,server
.aof_buf
,sdslen(server
.aof_buf
)); 
 125     if (nwritten 
!= (signed)sdslen(server
.aof_buf
)) { 
 126         /* Ooops, we are in troubles. The best thing to do for now is 
 127          * aborting instead of giving the illusion that everything is 
 128          * working as expected. */ 
 129         if (nwritten 
== -1) { 
 130             redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
)); 
 132             redisLog(REDIS_WARNING
,"Exiting on short write while writing to " 
 133                                    "the append-only file: %s (nwritten=%ld, " 
 137                                    (long)sdslen(server
.aof_buf
)); 
 141     server
.aof_current_size 
+= nwritten
; 
 143     /* Re-use AOF buffer when it is small enough. The maximum comes from the 
 144      * arena size of 4k minus some overhead (but is otherwise arbitrary). */ 
 145     if ((sdslen(server
.aof_buf
)+sdsavail(server
.aof_buf
)) < 4000) { 
 146         sdsclear(server
.aof_buf
); 
 148         sdsfree(server
.aof_buf
); 
 149         server
.aof_buf 
= sdsempty(); 
 152     /* Don't fsync if no-appendfsync-on-rewrite is set to yes and there are 
 153      * children doing I/O in the background. */ 
 154     if (server
.aof_no_fsync_on_rewrite 
&& 
 155         (server
.aof_child_pid 
!= -1 || server
.rdb_child_pid 
!= -1)) 
 158     /* Perform the fsync if needed. */ 
 159     if (server
.aof_fsync 
== AOF_FSYNC_ALWAYS
) { 
 160         /* aof_fsync is defined as fdatasync() for Linux in order to avoid 
 161          * flushing metadata. */ 
 162         aof_fsync(server
.aof_fd
); /* Let's try to get this data on the disk */ 
 163         server
.aof_last_fsync 
= server
.unixtime
; 
 164     } else if ((server
.aof_fsync 
== AOF_FSYNC_EVERYSEC 
&& 
 165                 server
.unixtime 
> server
.aof_last_fsync
)) { 
 166         if (!sync_in_progress
) aof_background_fsync(server
.aof_fd
); 
 167         server
.aof_last_fsync 
= server
.unixtime
; 
 171 sds 
catAppendOnlyGenericCommand(sds dst
, int argc
, robj 
**argv
) { 
 177     len 
= 1+ll2string(buf
+1,sizeof(buf
)-1,argc
); 
 180     dst 
= sdscatlen(dst
,buf
,len
); 
 182     for (j 
= 0; j 
< argc
; j
++) { 
 183         o 
= getDecodedObject(argv
[j
]); 
 185         len 
= 1+ll2string(buf
+1,sizeof(buf
)-1,sdslen(o
->ptr
)); 
 188         dst 
= sdscatlen(dst
,buf
,len
); 
 189         dst 
= sdscatlen(dst
,o
->ptr
,sdslen(o
->ptr
)); 
 190         dst 
= sdscatlen(dst
,"\r\n",2); 
 196 /* Create the sds representation of an PEXPIREAT command, using 
 197  * 'seconds' as time to live and 'cmd' to understand what command 
 198  * we are translating into a PEXPIREAT. 
 200  * This command is used in order to translate EXPIRE and PEXPIRE commands 
 201  * into PEXPIREAT command so that we retain precision in the append only 
 202  * file, and the time is always absolute and not relative. */ 
 203 sds 
catAppendOnlyExpireAtCommand(sds buf
, struct redisCommand 
*cmd
, robj 
*key
, robj 
*seconds
) { 
 207     /* Make sure we can use strtol */ 
 208     seconds 
= getDecodedObject(seconds
); 
 209     when 
= strtoll(seconds
->ptr
,NULL
,10); 
 210     /* Convert argument into milliseconds for EXPIRE, SETEX, EXPIREAT */ 
 211     if (cmd
->proc 
== expireCommand 
|| cmd
->proc 
== setexCommand 
|| 
 212         cmd
->proc 
== expireatCommand
) 
 216     /* Convert into absolute time for EXPIRE, PEXPIRE, SETEX, PSETEX */ 
 217     if (cmd
->proc 
== expireCommand 
|| cmd
->proc 
== pexpireCommand 
|| 
 218         cmd
->proc 
== setexCommand 
|| cmd
->proc 
== psetexCommand
) 
 222     decrRefCount(seconds
); 
 224     argv
[0] = createStringObject("PEXPIREAT",9); 
 226     argv
[2] = createStringObjectFromLongLong(when
); 
 227     buf 
= catAppendOnlyGenericCommand(buf
, 3, argv
); 
 228     decrRefCount(argv
[0]); 
 229     decrRefCount(argv
[2]); 
 233 void feedAppendOnlyFile(struct redisCommand 
*cmd
, int dictid
, robj 
**argv
, int argc
) { 
 234     sds buf 
= sdsempty(); 
 237     /* The DB this command was targetting is not the same as the last command 
 238      * we appendend. To issue a SELECT command is needed. */ 
 239     if (dictid 
!= server
.aof_selected_db
) { 
 242         snprintf(seldb
,sizeof(seldb
),"%d",dictid
); 
 243         buf 
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n", 
 244             (unsigned long)strlen(seldb
),seldb
); 
 245         server
.aof_selected_db 
= dictid
; 
 248     if (cmd
->proc 
== expireCommand 
|| cmd
->proc 
== pexpireCommand 
|| 
 249         cmd
->proc 
== expireatCommand
) { 
 250         /* Translate EXPIRE/PEXPIRE/EXPIREAT into PEXPIREAT */ 
 251         buf 
= catAppendOnlyExpireAtCommand(buf
,cmd
,argv
[1],argv
[2]); 
 252     } else if (cmd
->proc 
== setexCommand 
|| cmd
->proc 
== psetexCommand
) { 
 253         /* Translate SETEX/PSETEX to SET and PEXPIREAT */ 
 254         tmpargv
[0] = createStringObject("SET",3); 
 255         tmpargv
[1] = argv
[1]; 
 256         tmpargv
[2] = argv
[3]; 
 257         buf 
= catAppendOnlyGenericCommand(buf
,3,tmpargv
); 
 258         decrRefCount(tmpargv
[0]); 
 259         buf 
= catAppendOnlyExpireAtCommand(buf
,cmd
,argv
[1],argv
[2]); 
 261         /* All the other commands don't need translation or need the 
 262          * same translation already operated in the command vector 
 263          * for the replication itself. */ 
 264         buf 
= catAppendOnlyGenericCommand(buf
,argc
,argv
); 
 267     /* Append to the AOF buffer. This will be flushed on disk just before 
 268      * of re-entering the event loop, so before the client will get a 
 269      * positive reply about the operation performed. */ 
 270     if (server
.aof_state 
== REDIS_AOF_ON
) 
 271         server
.aof_buf 
= sdscatlen(server
.aof_buf
,buf
,sdslen(buf
)); 
 273     /* If a background append only file rewriting is in progress we want to 
 274      * accumulate the differences between the child DB and the current one 
 275      * in a buffer, so that when the child process will do its work we 
 276      * can append the differences to the new append only file. */ 
 277     if (server
.aof_child_pid 
!= -1) 
 278         server
.aof_rewrite_buf 
= sdscatlen(server
.aof_rewrite_buf
,buf
,sdslen(buf
)); 
 283 /* In Redis commands are always executed in the context of a client, so in 
 284  * order to load the append only file we need to create a fake client. */ 
 285 struct redisClient 
*createFakeClient(void) { 
 286     struct redisClient 
*c 
= zmalloc(sizeof(*c
)); 
 290     c
->querybuf 
= sdsempty(); 
 291     c
->querybuf_peak 
= 0; 
 296     /* We set the fake client as a slave waiting for the synchronization 
 297      * so that Redis will not try to send replies to this client. */ 
 298     c
->replstate 
= REDIS_REPL_WAIT_BGSAVE_START
; 
 299     c
->reply 
= listCreate(); 
 301     c
->obuf_soft_limit_reached_time 
= 0; 
 302     c
->watched_keys 
= listCreate(); 
 303     listSetFreeMethod(c
->reply
,decrRefCount
); 
 304     listSetDupMethod(c
->reply
,dupClientReplyValue
); 
 305     initClientMultiState(c
); 
 309 void freeFakeClient(struct redisClient 
*c
) { 
 310     sdsfree(c
->querybuf
); 
 311     listRelease(c
->reply
); 
 312     listRelease(c
->watched_keys
); 
 313     freeClientMultiState(c
); 
 317 /* Replay the append log file. On error REDIS_OK is returned. On non fatal 
 318  * error (the append only file is zero-length) REDIS_ERR is returned. On 
 319  * fatal error an error message is logged and the program exists. */ 
 320 int loadAppendOnlyFile(char *filename
) { 
 321     struct redisClient 
*fakeClient
; 
 322     FILE *fp 
= fopen(filename
,"r"); 
 323     struct redis_stat sb
; 
 324     int old_aof_state 
= server
.aof_state
; 
 327     if (fp 
&& redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size 
== 0) { 
 328         server
.aof_current_size 
= 0; 
 334         redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
)); 
 338     /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI 
 339      * to the same file we're about to read. */ 
 340     server
.aof_state 
= REDIS_AOF_OFF
; 
 342     fakeClient 
= createFakeClient(); 
 351         struct redisCommand 
*cmd
; 
 353         /* Serve the clients from time to time */ 
 354         if (!(loops
++ % 1000)) { 
 355             loadingProgress(ftello(fp
)); 
 356             aeProcessEvents(server
.el
, AE_FILE_EVENTS
|AE_DONT_WAIT
); 
 359         if (fgets(buf
,sizeof(buf
),fp
) == NULL
) { 
 365         if (buf
[0] != '*') goto fmterr
; 
 367         if (argc 
< 1) goto fmterr
; 
 369         argv 
= zmalloc(sizeof(robj
*)*argc
); 
 370         for (j 
= 0; j 
< argc
; j
++) { 
 371             if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
; 
 372             if (buf
[0] != '$') goto fmterr
; 
 373             len 
= strtol(buf
+1,NULL
,10); 
 374             argsds 
= sdsnewlen(NULL
,len
); 
 375             if (len 
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
; 
 376             argv
[j
] = createObject(REDIS_STRING
,argsds
); 
 377             if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */ 
 381         cmd 
= lookupCommand(argv
[0]->ptr
); 
 383             redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
); 
 386         /* Run the command in the context of a fake client */ 
 387         fakeClient
->argc 
= argc
; 
 388         fakeClient
->argv 
= argv
; 
 389         cmd
->proc(fakeClient
); 
 391         /* The fake client should not have a reply */ 
 392         redisAssert(fakeClient
->bufpos 
== 0 && listLength(fakeClient
->reply
) == 0); 
 393         /* The fake client should never get blocked */ 
 394         redisAssert((fakeClient
->flags 
& REDIS_BLOCKED
) == 0); 
 396         /* Clean up. Command code may have changed argv/argc so we use the 
 397          * argv/argc of the client instead of the local variables. */ 
 398         for (j 
= 0; j 
< fakeClient
->argc
; j
++) 
 399             decrRefCount(fakeClient
->argv
[j
]); 
 400         zfree(fakeClient
->argv
); 
 403     /* This point can only be reached when EOF is reached without errors. 
 404      * If the client is in the middle of a MULTI/EXEC, log error and quit. */ 
 405     if (fakeClient
->flags 
& REDIS_MULTI
) goto readerr
; 
 408     freeFakeClient(fakeClient
); 
 409     server
.aof_state 
= old_aof_state
; 
 411     aofUpdateCurrentSize(); 
 412     server
.aof_rewrite_base_size 
= server
.aof_current_size
; 
 417         redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file"); 
 419         redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
)); 
 423     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>"); 
 427 /* Delegate writing an object to writing a bulk string or bulk long long. 
 428  * This is not placed in rio.c since that adds the redis.h dependency. */ 
 429 int rioWriteBulkObject(rio 
*r
, robj 
*obj
) { 
 430     /* Avoid using getDecodedObject to help copy-on-write (we are often 
 431      * in a child process when this function is called). */ 
 432     if (obj
->encoding 
== REDIS_ENCODING_INT
) { 
 433         return rioWriteBulkLongLong(r
,(long)obj
->ptr
); 
 434     } else if (obj
->encoding 
== REDIS_ENCODING_RAW
) { 
 435         return rioWriteBulkString(r
,obj
->ptr
,sdslen(obj
->ptr
)); 
 437         redisPanic("Unknown string encoding"); 
 441 /* Emit the commands needed to rebuild a list object. 
 442  * The function returns 0 on error, 1 on success. */ 
 443 int rewriteListObject(rio 
*r
, robj 
*key
, robj 
*o
) { 
 444     long long count 
= 0, items 
= listTypeLength(o
); 
 446     if (o
->encoding 
== REDIS_ENCODING_ZIPLIST
) { 
 447         unsigned char *zl 
= o
->ptr
; 
 448         unsigned char *p 
= ziplistIndex(zl
,0); 
 453         while(ziplistGet(p
,&vstr
,&vlen
,&vlong
)) { 
 455                 int cmd_items 
= (items 
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ? 
 456                     REDIS_AOF_REWRITE_ITEMS_PER_CMD 
: items
; 
 458                 if (rioWriteBulkCount(r
,'*',2+cmd_items
) == 0) return 0; 
 459                 if (rioWriteBulkString(r
,"RPUSH",5) == 0) return 0; 
 460                 if (rioWriteBulkObject(r
,key
) == 0) return 0; 
 463                 if (rioWriteBulkString(r
,(char*)vstr
,vlen
) == 0) return 0; 
 465                 if (rioWriteBulkLongLong(r
,vlong
) == 0) return 0; 
 467             p 
= ziplistNext(zl
,p
); 
 468             if (++count 
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count 
= 0; 
 471     } else if (o
->encoding 
== REDIS_ENCODING_LINKEDLIST
) { 
 476         listRewind(list
,&li
); 
 477         while((ln 
= listNext(&li
))) { 
 478             robj 
*eleobj 
= listNodeValue(ln
); 
 481                 int cmd_items 
= (items 
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ? 
 482                     REDIS_AOF_REWRITE_ITEMS_PER_CMD 
: items
; 
 484                 if (rioWriteBulkCount(r
,'*',2+cmd_items
) == 0) return 0; 
 485                 if (rioWriteBulkString(r
,"RPUSH",5) == 0) return 0; 
 486                 if (rioWriteBulkObject(r
,key
) == 0) return 0; 
 488             if (rioWriteBulkObject(r
,eleobj
) == 0) return 0; 
 489             if (++count 
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count 
= 0; 
 493         redisPanic("Unknown list encoding"); 
 498 /* Emit the commands needed to rebuild a set object. 
 499  * The function returns 0 on error, 1 on success. */ 
 500 int rewriteSetObject(rio 
*r
, robj 
*key
, robj 
*o
) { 
 501     long long count 
= 0, items 
= setTypeSize(o
); 
 503     if (o
->encoding 
== REDIS_ENCODING_INTSET
) { 
 507         while(intsetGet(o
->ptr
,ii
++,&llval
)) { 
 509                 int cmd_items 
= (items 
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ? 
 510                     REDIS_AOF_REWRITE_ITEMS_PER_CMD 
: items
; 
 512                 if (rioWriteBulkCount(r
,'*',2+cmd_items
) == 0) return 0; 
 513                 if (rioWriteBulkString(r
,"SADD",4) == 0) return 0; 
 514                 if (rioWriteBulkObject(r
,key
) == 0) return 0; 
 516             if (rioWriteBulkLongLong(r
,llval
) == 0) return 0; 
 517             if (++count 
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count 
= 0; 
 520     } else if (o
->encoding 
== REDIS_ENCODING_HT
) { 
 521         dictIterator 
*di 
= dictGetIterator(o
->ptr
); 
 524         while((de 
= dictNext(di
)) != NULL
) { 
 525             robj 
*eleobj 
= dictGetKey(de
); 
 527                 int cmd_items 
= (items 
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ? 
 528                     REDIS_AOF_REWRITE_ITEMS_PER_CMD 
: items
; 
 530                 if (rioWriteBulkCount(r
,'*',2+cmd_items
) == 0) return 0; 
 531                 if (rioWriteBulkString(r
,"SADD",4) == 0) return 0; 
 532                 if (rioWriteBulkObject(r
,key
) == 0) return 0; 
 534             if (rioWriteBulkObject(r
,eleobj
) == 0) return 0; 
 535             if (++count 
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count 
= 0; 
 538         dictReleaseIterator(di
); 
 540         redisPanic("Unknown set encoding"); 
 545 /* Emit the commands needed to rebuild a sorted set object. 
 546  * The function returns 0 on error, 1 on success. */ 
 547 int rewriteSortedSetObject(rio 
*r
, robj 
*key
, robj 
*o
) { 
 548     long long count 
= 0, items 
= zsetLength(o
); 
 550     if (o
->encoding 
== REDIS_ENCODING_ZIPLIST
) { 
 551         unsigned char *zl 
= o
->ptr
; 
 552         unsigned char *eptr
, *sptr
; 
 558         eptr 
= ziplistIndex(zl
,0); 
 559         redisAssert(eptr 
!= NULL
); 
 560         sptr 
= ziplistNext(zl
,eptr
); 
 561         redisAssert(sptr 
!= NULL
); 
 563         while (eptr 
!= NULL
) { 
 564             redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vll
)); 
 565             score 
= zzlGetScore(sptr
); 
 568                 int cmd_items 
= (items 
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ? 
 569                     REDIS_AOF_REWRITE_ITEMS_PER_CMD 
: items
; 
 571                 if (rioWriteBulkCount(r
,'*',2+cmd_items
*2) == 0) return 0; 
 572                 if (rioWriteBulkString(r
,"ZADD",4) == 0) return 0; 
 573                 if (rioWriteBulkObject(r
,key
) == 0) return 0; 
 575             if (rioWriteBulkDouble(r
,score
) == 0) return 0; 
 577                 if (rioWriteBulkString(r
,(char*)vstr
,vlen
) == 0) return 0; 
 579                 if (rioWriteBulkLongLong(r
,vll
) == 0) return 0; 
 581             zzlNext(zl
,&eptr
,&sptr
); 
 582             if (++count 
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count 
= 0; 
 585     } else if (o
->encoding 
== REDIS_ENCODING_SKIPLIST
) { 
 587         dictIterator 
*di 
= dictGetIterator(zs
->dict
); 
 590         while((de 
= dictNext(di
)) != NULL
) { 
 591             robj 
*eleobj 
= dictGetKey(de
); 
 592             double *score 
= dictGetVal(de
); 
 595                 int cmd_items 
= (items 
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ? 
 596                     REDIS_AOF_REWRITE_ITEMS_PER_CMD 
: items
; 
 598                 if (rioWriteBulkCount(r
,'*',2+cmd_items
*2) == 0) return 0; 
 599                 if (rioWriteBulkString(r
,"ZADD",4) == 0) return 0; 
 600                 if (rioWriteBulkObject(r
,key
) == 0) return 0; 
 602             if (rioWriteBulkDouble(r
,*score
) == 0) return 0; 
 603             if (rioWriteBulkObject(r
,eleobj
) == 0) return 0; 
 604             if (++count 
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count 
= 0; 
 607         dictReleaseIterator(di
); 
 609         redisPanic("Unknown sorted zset encoding"); 
 614 /* Write either the key or the value of the currently selected item of an hash. 
 615  * The 'hi' argument passes a valid Redis hash iterator. 
 616  * The 'what' filed specifies if to write a key or a value and can be 
 617  * either REDIS_HASH_KEY or REDIS_HASH_VALUE. 
 619  * The function returns 0 on error, non-zero on success. */ 
 620 static int rioWriteHashIteratorCursor(rio 
*r
, hashTypeIterator 
*hi
, int what
) { 
 621     if (hi
->encoding 
== REDIS_ENCODING_ZIPLIST
) { 
 622         unsigned char *vstr 
= NULL
; 
 623         unsigned int vlen 
= UINT_MAX
; 
 624         long long vll 
= LLONG_MAX
; 
 626         hashTypeCurrentFromZiplist(hi
, what
, &vstr
, &vlen
, &vll
); 
 628             return rioWriteBulkString(r
, (char*)vstr
, vlen
); 
 630             return rioWriteBulkLongLong(r
, vll
); 
 633     } else if (hi
->encoding 
== REDIS_ENCODING_HT
) { 
 636         hashTypeCurrentFromHashTable(hi
, what
, &value
); 
 637         return rioWriteBulkObject(r
, value
); 
 640     redisPanic("Unknown hash encoding"); 
 644 /* Emit the commands needed to rebuild a hash object. 
 645  * The function returns 0 on error, 1 on success. */ 
 646 int rewriteHashObject(rio 
*r
, robj 
*key
, robj 
*o
) { 
 647     hashTypeIterator 
*hi
; 
 648     long long count 
= 0, items 
= hashTypeLength(o
); 
 650     hi 
= hashTypeInitIterator(o
); 
 651     while (hashTypeNext(hi
) != REDIS_ERR
) { 
 653             int cmd_items 
= (items 
> REDIS_AOF_REWRITE_ITEMS_PER_CMD
) ? 
 654                 REDIS_AOF_REWRITE_ITEMS_PER_CMD 
: items
; 
 656             if (rioWriteBulkCount(r
,'*',2+cmd_items
*2) == 0) return 0; 
 657             if (rioWriteBulkString(r
,"HMSET",5) == 0) return 0; 
 658             if (rioWriteBulkObject(r
,key
) == 0) return 0; 
 661         if (rioWriteHashIteratorCursor(r
, hi
, REDIS_HASH_KEY
) == 0) return 0; 
 662         if (rioWriteHashIteratorCursor(r
, hi
, REDIS_HASH_VALUE
) == 0) return 0; 
 663         if (++count 
== REDIS_AOF_REWRITE_ITEMS_PER_CMD
) count 
= 0; 
 667     hashTypeReleaseIterator(hi
); 
 672 /* Write a sequence of commands able to fully rebuild the dataset into 
 673  * "filename". Used both by REWRITEAOF and BGREWRITEAOF. 
 675  * In order to minimize the number of commands needed in the rewritten 
 676  * log Redis uses variadic commands when possible, such as RPUSH, SADD 
 677  * and ZADD. However at max REDIS_AOF_REWRITE_ITEMS_PER_CMD items per time 
 678  * are inserted using a single command. */ 
 679 int rewriteAppendOnlyFile(char *filename
) { 
 680     dictIterator 
*di 
= NULL
; 
 686     long long now 
= mstime(); 
 688     /* Note that we have to use a different temp name here compared to the 
 689      * one used by rewriteAppendOnlyFileBackground() function. */ 
 690     snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid()); 
 691     fp 
= fopen(tmpfile
,"w"); 
 693         redisLog(REDIS_WARNING
, "Opening the temp file for AOF rewrite in rewriteAppendOnlyFile(): %s", strerror(errno
)); 
 697     rioInitWithFile(&aof
,fp
); 
 698     for (j 
= 0; j 
< server
.dbnum
; j
++) { 
 699         char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n"; 
 700         redisDb 
*db 
= server
.db
+j
; 
 702         if (dictSize(d
) == 0) continue; 
 703         di 
= dictGetSafeIterator(d
); 
 709         /* SELECT the new DB */ 
 710         if (rioWrite(&aof
,selectcmd
,sizeof(selectcmd
)-1) == 0) goto werr
; 
 711         if (rioWriteBulkLongLong(&aof
,j
) == 0) goto werr
; 
 713         /* Iterate this DB writing every entry */ 
 714         while((de 
= dictNext(di
)) != NULL
) { 
 717             long long expiretime
; 
 719             keystr 
= dictGetKey(de
); 
 721             initStaticStringObject(key
,keystr
); 
 723             expiretime 
= getExpire(db
,&key
); 
 725             /* Save the key and associated value */ 
 726             if (o
->type 
== REDIS_STRING
) { 
 727                 /* Emit a SET command */ 
 728                 char cmd
[]="*3\r\n$3\r\nSET\r\n"; 
 729                 if (rioWrite(&aof
,cmd
,sizeof(cmd
)-1) == 0) goto werr
; 
 731                 if (rioWriteBulkObject(&aof
,&key
) == 0) goto werr
; 
 732                 if (rioWriteBulkObject(&aof
,o
) == 0) goto werr
; 
 733             } else if (o
->type 
== REDIS_LIST
) { 
 734                 if (rewriteListObject(&aof
,&key
,o
) == 0) goto werr
; 
 735             } else if (o
->type 
== REDIS_SET
) { 
 736                 if (rewriteSetObject(&aof
,&key
,o
) == 0) goto werr
; 
 737             } else if (o
->type 
== REDIS_ZSET
) { 
 738                 if (rewriteSortedSetObject(&aof
,&key
,o
) == 0) goto werr
; 
 739             } else if (o
->type 
== REDIS_HASH
) { 
 740                 if (rewriteHashObject(&aof
,&key
,o
) == 0) goto werr
; 
 742                 redisPanic("Unknown object type"); 
 744             /* Save the expire time */ 
 745             if (expiretime 
!= -1) { 
 746                 char cmd
[]="*3\r\n$9\r\nPEXPIREAT\r\n"; 
 747                 /* If this key is already expired skip it */ 
 748                 if (expiretime 
< now
) continue; 
 749                 if (rioWrite(&aof
,cmd
,sizeof(cmd
)-1) == 0) goto werr
; 
 750                 if (rioWriteBulkObject(&aof
,&key
) == 0) goto werr
; 
 751                 if (rioWriteBulkLongLong(&aof
,expiretime
) == 0) goto werr
; 
 754         dictReleaseIterator(di
); 
 757     /* Make sure data will not remain on the OS's output buffers */ 
 759     aof_fsync(fileno(fp
)); 
 762     /* Use RENAME to make sure the DB file is changed atomically only 
 763      * if the generate DB file is ok. */ 
 764     if (rename(tmpfile
,filename
) == -1) { 
 765         redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
)); 
 769     redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed"); 
 775     redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
)); 
 776     if (di
) dictReleaseIterator(di
); 
 780 /* This is how rewriting of the append only file in background works: 
 782  * 1) The user calls BGREWRITEAOF 
 783  * 2) Redis calls this function, that forks(): 
 784  *    2a) the child rewrite the append only file in a temp file. 
 785  *    2b) the parent accumulates differences in server.aof_rewrite_buf. 
 786  * 3) When the child finished '2a' exists. 
 787  * 4) The parent will trap the exit code, if it's OK, will append the 
 788  *    data accumulated into server.aof_rewrite_buf into the temp file, and 
 789  *    finally will rename(2) the temp file in the actual file name. 
 790  *    The the new file is reopened as the new append only file. Profit! 
 792 int rewriteAppendOnlyFileBackground(void) { 
 796     if (server
.aof_child_pid 
!= -1) return REDIS_ERR
; 
 798     if ((childpid 
= fork()) == 0) { 
 802         if (server
.ipfd 
> 0) close(server
.ipfd
); 
 803         if (server
.sofd 
> 0) close(server
.sofd
); 
 804         snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid()); 
 805         if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) { 
 812         server
.stat_fork_time 
= ustime()-start
; 
 813         if (childpid 
== -1) { 
 814             redisLog(REDIS_WARNING
, 
 815                 "Can't rewrite append only file in background: fork: %s", 
 819         redisLog(REDIS_NOTICE
, 
 820             "Background append only file rewriting started by pid %d",childpid
); 
 821         server
.aof_rewrite_scheduled 
= 0; 
 822         server
.aof_child_pid 
= childpid
; 
 823         updateDictResizePolicy(); 
 824         /* We set appendseldb to -1 in order to force the next call to the 
 825          * feedAppendOnlyFile() to issue a SELECT command, so the differences 
 826          * accumulated by the parent into server.aof_rewrite_buf will start 
 827          * with a SELECT statement and it will be safe to merge. */ 
 828         server
.aof_selected_db 
= -1; 
 831     return REDIS_OK
; /* unreached */ 
 834 void bgrewriteaofCommand(redisClient 
*c
) { 
 835     if (server
.aof_child_pid 
!= -1) { 
 836         addReplyError(c
,"Background append only file rewriting already in progress"); 
 837     } else if (server
.rdb_child_pid 
!= -1) { 
 838         server
.aof_rewrite_scheduled 
= 1; 
 839         addReplyStatus(c
,"Background append only file rewriting scheduled"); 
 840     } else if (rewriteAppendOnlyFileBackground() == REDIS_OK
) { 
 841         addReplyStatus(c
,"Background append only file rewriting started"); 
 843         addReply(c
,shared
.err
); 
 847 void aofRemoveTempFile(pid_t childpid
) { 
 850     snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
); 
 854 /* Update the server.aof_current_size filed explicitly using stat(2) 
 855  * to check the size of the file. This is useful after a rewrite or after 
 856  * a restart, normally the size is updated just adding the write length 
 857  * to the current length, that is much faster. */ 
 858 void aofUpdateCurrentSize(void) { 
 859     struct redis_stat sb
; 
 861     if (redis_fstat(server
.aof_fd
,&sb
) == -1) { 
 862         redisLog(REDIS_WARNING
,"Unable to obtain the AOF file length. stat: %s", 
 865         server
.aof_current_size 
= sb
.st_size
; 
 869 /* A background append only file rewriting (BGREWRITEAOF) terminated its work. 
 871 void backgroundRewriteDoneHandler(int exitcode
, int bysignal
) { 
 872     if (!bysignal 
&& exitcode 
== 0) { 
 876         long long now 
= ustime(); 
 878         redisLog(REDIS_NOTICE
, 
 879             "Background AOF rewrite terminated with success"); 
 881         /* Flush the differences accumulated by the parent to the 
 883         snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", 
 884             (int)server
.aof_child_pid
); 
 885         newfd 
= open(tmpfile
,O_WRONLY
|O_APPEND
); 
 887             redisLog(REDIS_WARNING
, 
 888                 "Unable to open the temporary AOF produced by the child: %s", strerror(errno
)); 
 892         nwritten 
= write(newfd
,server
.aof_rewrite_buf
,sdslen(server
.aof_rewrite_buf
)); 
 893         if (nwritten 
!= (signed)sdslen(server
.aof_rewrite_buf
)) { 
 894             if (nwritten 
== -1) { 
 895                 redisLog(REDIS_WARNING
, 
 896                     "Error trying to flush the parent diff to the rewritten AOF: %s", strerror(errno
)); 
 898                 redisLog(REDIS_WARNING
, 
 899                     "Short write trying to flush the parent diff to the rewritten AOF: %s", strerror(errno
)); 
 905         redisLog(REDIS_NOTICE
, 
 906             "Parent diff successfully flushed to the rewritten AOF (%lu bytes)", nwritten
); 
 908         /* The only remaining thing to do is to rename the temporary file to 
 909          * the configured file and switch the file descriptor used to do AOF 
 910          * writes. We don't want close(2) or rename(2) calls to block the 
 911          * server on old file deletion. 
 913          * There are two possible scenarios: 
 915          * 1) AOF is DISABLED and this was a one time rewrite. The temporary 
 916          * file will be renamed to the configured file. When this file already 
 917          * exists, it will be unlinked, which may block the server. 
 919          * 2) AOF is ENABLED and the rewritten AOF will immediately start 
 920          * receiving writes. After the temporary file is renamed to the 
 921          * configured file, the original AOF file descriptor will be closed. 
 922          * Since this will be the last reference to that file, closing it 
 923          * causes the underlying file to be unlinked, which may block the 
 926          * To mitigate the blocking effect of the unlink operation (either 
 927          * caused by rename(2) in scenario 1, or by close(2) in scenario 2), we 
 928          * use a background thread to take care of this. First, we 
 929          * make scenario 1 identical to scenario 2 by opening the target file 
 930          * when it exists. The unlink operation after the rename(2) will then 
 931          * be executed upon calling close(2) for its descriptor. Everything to 
 932          * guarantee atomicity for this switch has already happened by then, so 
 933          * we don't care what the outcome or duration of that close operation 
 934          * is, as long as the file descriptor is released again. */ 
 935         if (server
.aof_fd 
== -1) { 
 938              /* Don't care if this fails: oldfd will be -1 and we handle that. 
 939               * One notable case of -1 return is if the old file does 
 941              oldfd 
= open(server
.aof_filename
,O_RDONLY
|O_NONBLOCK
); 
 944             oldfd 
= -1; /* We'll set this to the current AOF filedes later. */ 
 947         /* Rename the temporary file. This will not unlink the target file if 
 948          * it exists, because we reference it with "oldfd". */ 
 949         if (rename(tmpfile
,server
.aof_filename
) == -1) { 
 950             redisLog(REDIS_WARNING
, 
 951                 "Error trying to rename the temporary AOF file: %s", strerror(errno
)); 
 953             if (oldfd 
!= -1) close(oldfd
); 
 957         if (server
.aof_fd 
== -1) { 
 958             /* AOF disabled, we don't need to set the AOF file descriptor 
 959              * to this new file, so we can close it. */ 
 962             /* AOF enabled, replace the old fd with the new one. */ 
 963             oldfd 
= server
.aof_fd
; 
 964             server
.aof_fd 
= newfd
; 
 965             if (server
.aof_fsync 
== AOF_FSYNC_ALWAYS
) 
 967             else if (server
.aof_fsync 
== AOF_FSYNC_EVERYSEC
) 
 968                 aof_background_fsync(newfd
); 
 969             server
.aof_selected_db 
= -1; /* Make sure SELECT is re-issued */ 
 970             aofUpdateCurrentSize(); 
 971             server
.aof_rewrite_base_size 
= server
.aof_current_size
; 
 973             /* Clear regular AOF buffer since its contents was just written to 
 974              * the new AOF from the background rewrite buffer. */ 
 975             sdsfree(server
.aof_buf
); 
 976             server
.aof_buf 
= sdsempty(); 
 979         redisLog(REDIS_NOTICE
, "Background AOF rewrite finished successfully"); 
 980         /* Change state from WAIT_REWRITE to ON if needed */ 
 981         if (server
.aof_state 
== REDIS_AOF_WAIT_REWRITE
) 
 982             server
.aof_state 
= REDIS_AOF_ON
; 
 984         /* Asynchronously close the overwritten AOF. */ 
 985         if (oldfd 
!= -1) bioCreateBackgroundJob(REDIS_BIO_CLOSE_FILE
,(void*)(long)oldfd
,NULL
,NULL
); 
 987         redisLog(REDIS_VERBOSE
, 
 988             "Background AOF rewrite signal handler took %lldus", ustime()-now
); 
 989     } else if (!bysignal 
&& exitcode 
!= 0) { 
 990         redisLog(REDIS_WARNING
, 
 991             "Background AOF rewrite terminated with error"); 
 993         redisLog(REDIS_WARNING
, 
 994             "Background AOF rewrite terminated by signal %d", bysignal
); 
 998     sdsfree(server
.aof_rewrite_buf
); 
 999     server
.aof_rewrite_buf 
= sdsempty(); 
1000     aofRemoveTempFile(server
.aof_child_pid
); 
1001     server
.aof_child_pid 
= -1; 
1002     /* Schedule a new rewrite if we are waiting for it to switch the AOF ON. */ 
1003     if (server
.aof_state 
== REDIS_AOF_WAIT_REWRITE
) 
1004         server
.aof_rewrite_scheduled 
= 1;