1 /* 2 * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com> 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions are met: 7 * 8 * * Redistributions of source code must retain the above copyright notice, 9 * this list of conditions and the following disclaimer. 10 * * Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * * Neither the name of Redis nor the names of its contributors may be used 14 * to endorse or promote products derived from this software without 15 * specific prior written permission. 16 * 17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 18 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 20 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 21 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 27 * POSSIBILITY OF SUCH DAMAGE. 28 */ 29 30 #include "server.h" 31 #include "bio.h" 32 #include "rio.h" 33 34 #include <signal.h> 35 #include <fcntl.h> 36 #include <sys/stat.h> 37 #include <sys/types.h> 38 #include <sys/time.h> 39 #include <sys/resource.h> 40 #include <sys/wait.h> 41 42 void aofUpdateCurrentSize(void); 43 void aofClosePipes(void); 44 45 /* ---------------------------------------------------------------------------- 46 * AOF rewrite buffer implementation. 47 * 48 * The following code implement a simple buffer used in order to accumulate 49 * changes while the background process is rewriting the AOF file. 50 * 51 * We only need to append, but can't just use realloc with a large block 52 * because 'huge' reallocs are not always handled as one could expect 53 * (via remapping of pages at OS level) but may involve copying data. 54 * 55 * For this reason we use a list of blocks, every block is 56 * AOF_RW_BUF_BLOCK_SIZE bytes. 57 * ------------------------------------------------------------------------- */ 58 59 #define AOF_RW_BUF_BLOCK_SIZE (1024*1024*10) /* 10 MB per block */ 60 61 typedef struct aofrwblock { 62 unsigned long used, free; 63 char buf[AOF_RW_BUF_BLOCK_SIZE]; 64 } aofrwblock; 65 66 /* This function free the old AOF rewrite buffer if needed, and initialize 67 * a fresh new one. It tests for server.aof_rewrite_buf_blocks equal to NULL 68 * so can be used for the first initialization as well. */ 69 void aofRewriteBufferReset(void) { 70 if (server.aof_rewrite_buf_blocks) 71 listRelease(server.aof_rewrite_buf_blocks); 72 73 server.aof_rewrite_buf_blocks = listCreate(); 74 listSetFreeMethod(server.aof_rewrite_buf_blocks,zfree); 75 } 76 77 /* Return the current size of the AOF rewrite buffer. */ 78 unsigned long aofRewriteBufferSize(void) { 79 listNode *ln; 80 listIter li; 81 unsigned long size = 0; 82 83 listRewind(server.aof_rewrite_buf_blocks,&li); 84 while((ln = listNext(&li))) { 85 aofrwblock *block = listNodeValue(ln); 86 size += block->used; 87 } 88 return size; 89 } 90 91 /* Event handler used to send data to the child process doing the AOF 92 * rewrite. We send pieces of our AOF differences buffer so that the final 93 * write when the child finishes the rewrite will be small. */ 94 void aofChildWriteDiffData(aeEventLoop *el, int fd, void *privdata, int mask) { 95 listNode *ln; 96 aofrwblock *block; 97 ssize_t nwritten; 98 UNUSED(el); 99 UNUSED(fd); 100 UNUSED(privdata); 101 UNUSED(mask); 102 103 while(1) { 104 ln = listFirst(server.aof_rewrite_buf_blocks); 105 block = ln ? ln->value : NULL; 106 if (server.aof_stop_sending_diff || !block) { 107 aeDeleteFileEvent(server.el,server.aof_pipe_write_data_to_child, 108 AE_WRITABLE); 109 return; 110 } 111 if (block->used > 0) { 112 nwritten = write(server.aof_pipe_write_data_to_child, 113 block->buf,block->used); 114 if (nwritten <= 0) return; 115 memmove(block->buf,block->buf+nwritten,block->used-nwritten); 116 block->used -= nwritten; 117 } 118 if (block->used == 0) listDelNode(server.aof_rewrite_buf_blocks,ln); 119 } 120 } 121 122 /* Append data to the AOF rewrite buffer, allocating new blocks if needed. */ 123 void aofRewriteBufferAppend(unsigned char *s, unsigned long len) { 124 listNode *ln = listLast(server.aof_rewrite_buf_blocks); 125 aofrwblock *block = ln ? ln->value : NULL; 126 127 while(len) { 128 /* If we already got at least an allocated block, try appending 129 * at least some piece into it. */ 130 if (block) { 131 unsigned long thislen = (block->free < len) ? block->free : len; 132 if (thislen) { /* The current block is not already full. */ 133 memcpy(block->buf+block->used, s, thislen); 134 block->used += thislen; 135 block->free -= thislen; 136 s += thislen; 137 len -= thislen; 138 } 139 } 140 141 if (len) { /* First block to allocate, or need another block. */ 142 int numblocks; 143 144 block = zmalloc(sizeof(*block)); 145 block->free = AOF_RW_BUF_BLOCK_SIZE; 146 block->used = 0; 147 listAddNodeTail(server.aof_rewrite_buf_blocks,block); 148 149 /* Log every time we cross more 10 or 100 blocks, respectively 150 * as a notice or warning. */ 151 numblocks = listLength(server.aof_rewrite_buf_blocks); 152 if (((numblocks+1) % 10) == 0) { 153 int level = ((numblocks+1) % 100) == 0 ? LL_WARNING : 154 LL_NOTICE; 155 serverLog(level,"Background AOF buffer size: %lu MB", 156 aofRewriteBufferSize()/(1024*1024)); 157 } 158 } 159 } 160 161 /* Install a file event to send data to the rewrite child if there is 162 * not one already. */ 163 if (aeGetFileEvents(server.el,server.aof_pipe_write_data_to_child) == 0) { 164 aeCreateFileEvent(server.el, server.aof_pipe_write_data_to_child, 165 AE_WRITABLE, aofChildWriteDiffData, NULL); 166 } 167 } 168 169 /* Write the buffer (possibly composed of multiple blocks) into the specified 170 * fd. If a short write or any other error happens -1 is returned, 171 * otherwise the number of bytes written is returned. */ 172 ssize_t aofRewriteBufferWrite(int fd) { 173 listNode *ln; 174 listIter li; 175 ssize_t count = 0; 176 177 listRewind(server.aof_rewrite_buf_blocks,&li); 178 while((ln = listNext(&li))) { 179 aofrwblock *block = listNodeValue(ln); 180 ssize_t nwritten; 181 182 if (block->used) { 183 nwritten = write(fd,block->buf,block->used); 184 if (nwritten != (ssize_t)block->used) { 185 if (nwritten == 0) errno = EIO; 186 return -1; 187 } 188 count += nwritten; 189 } 190 } 191 return count; 192 } 193 194 /* ---------------------------------------------------------------------------- 195 * AOF file implementation 196 * ------------------------------------------------------------------------- */ 197 198 /* Starts a background task that performs fsync() against the specified 199 * file descriptor (the one of the AOF file) in another thread. */ 200 void aof_background_fsync(int fd) { 201 bioCreateBackgroundJob(BIO_AOF_FSYNC,(void*)(long)fd,NULL,NULL); 202 } 203 204 /* Called when the user switches from "appendonly yes" to "appendonly no" 205 * at runtime using the CONFIG command. */ 206 void stopAppendOnly(void) { 207 serverAssert(server.aof_state != AOF_OFF); 208 flushAppendOnlyFile(1); 209 aof_fsync(server.aof_fd); 210 close(server.aof_fd); 211 212 server.aof_fd = -1; 213 server.aof_selected_db = -1; 214 server.aof_state = AOF_OFF; 215 /* rewrite operation in progress? kill it, wait child exit */ 216 if (server.aof_child_pid != -1) { 217 int statloc; 218 219 serverLog(LL_NOTICE,"Killing running AOF rewrite child: %ld", 220 (long) server.aof_child_pid); 221 if (kill(server.aof_child_pid,SIGUSR1) != -1) { 222 while(wait3(&statloc,0,NULL) != server.aof_child_pid); 223 } 224 /* reset the buffer accumulating changes while the child saves */ 225 aofRewriteBufferReset(); 226 aofRemoveTempFile(server.aof_child_pid); 227 server.aof_child_pid = -1; 228 server.aof_rewrite_time_start = -1; 229 /* close pipes used for IPC between the two processes. */ 230 aofClosePipes(); 231 } 232 } 233 234 /* Called when the user switches from "appendonly no" to "appendonly yes" 235 * at runtime using the CONFIG command. */ 236 int startAppendOnly(void) { 237 server.aof_last_fsync = server.unixtime; 238 server.aof_fd = open(server.aof_filename,O_WRONLY|O_APPEND|O_CREAT,0644); 239 serverAssert(server.aof_state == AOF_OFF); 240 if (server.aof_fd == -1) { 241 serverLog(LL_WARNING,"Redis needs to enable the AOF but can't open the append only file: %s",strerror(errno)); 242 return C_ERR; 243 } 244 if (rewriteAppendOnlyFileBackground() == C_ERR) { 245 close(server.aof_fd); 246 serverLog(LL_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."); 247 return C_ERR; 248 } 249 /* We correctly switched on AOF, now wait for the rewrite to be complete 250 * in order to append data on disk. */ 251 server.aof_state = AOF_WAIT_REWRITE; 252 return C_OK; 253 } 254 255 /* Write the append only file buffer on disk. 256 * 257 * Since we are required to write the AOF before replying to the client, 258 * and the only way the client socket can get a write is entering when the 259 * the event loop, we accumulate all the AOF writes in a memory 260 * buffer and write it on disk using this function just before entering 261 * the event loop again. 262 * 263 * About the 'force' argument: 264 * 265 * When the fsync policy is set to 'everysec' we may delay the flush if there 266 * is still an fsync() going on in the background thread, since for instance 267 * on Linux write(2) will be blocked by the background fsync anyway. 268 * When this happens we remember that there is some aof buffer to be 269 * flushed ASAP, and will try to do that in the serverCron() function. 270 * 271 * However if force is set to 1 we'll write regardless of the background 272 * fsync. */ 273 #define AOF_WRITE_LOG_ERROR_RATE 30 /* Seconds between errors logging. */ 274 void flushAppendOnlyFile(int force) { 275 ssize_t nwritten; 276 int sync_in_progress = 0; 277 mstime_t latency; 278 279 if (sdslen(server.aof_buf) == 0) return; 280 281 if (server.aof_fsync == AOF_FSYNC_EVERYSEC) 282 sync_in_progress = bioPendingJobsOfType(BIO_AOF_FSYNC) != 0; 283 284 if (server.aof_fsync == AOF_FSYNC_EVERYSEC && !force) { 285 /* With this append fsync policy we do background fsyncing. 286 * If the fsync is still in progress we can try to delay 287 * the write for a couple of seconds. */ 288 if (sync_in_progress) { 289 if (server.aof_flush_postponed_start == 0) { 290 /* No previous write postponing, remember that we are 291 * postponing the flush and return. */ 292 server.aof_flush_postponed_start = server.unixtime; 293 return; 294 } else if (server.unixtime - server.aof_flush_postponed_start < 2) { 295 /* We were already waiting for fsync to finish, but for less 296 * than two seconds this is still ok. Postpone again. */ 297 return; 298 } 299 /* Otherwise fall trough, and go write since we can't wait 300 * over two seconds. */ 301 server.aof_delayed_fsync++; 302 serverLog(LL_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."); 303 } 304 } 305 /* We want to perform a single write. This should be guaranteed atomic 306 * at least if the filesystem we are writing is a real physical one. 307 * While this will save us against the server being killed I don't think 308 * there is much to do about the whole server stopping for power problems 309 * or alike */ 310 311 latencyStartMonitor(latency); 312 nwritten = write(server.aof_fd,server.aof_buf,sdslen(server.aof_buf)); 313 latencyEndMonitor(latency); 314 /* We want to capture different events for delayed writes: 315 * when the delay happens with a pending fsync, or with a saving child 316 * active, and when the above two conditions are missing. 317 * We also use an additional event name to save all samples which is 318 * useful for graphing / monitoring purposes. */ 319 if (sync_in_progress) { 320 latencyAddSampleIfNeeded("aof-write-pending-fsync",latency); 321 } else if (server.aof_child_pid != -1 || server.rdb_child_pid != -1) { 322 latencyAddSampleIfNeeded("aof-write-active-child",latency); 323 } else { 324 latencyAddSampleIfNeeded("aof-write-alone",latency); 325 } 326 latencyAddSampleIfNeeded("aof-write",latency); 327 328 /* We performed the write so reset the postponed flush sentinel to zero. */ 329 server.aof_flush_postponed_start = 0; 330 331 if (nwritten != (signed)sdslen(server.aof_buf)) { 332 static time_t last_write_error_log = 0; 333 int can_log = 0; 334 335 /* Limit logging rate to 1 line per AOF_WRITE_LOG_ERROR_RATE seconds. */ 336 if ((server.unixtime - last_write_error_log) > AOF_WRITE_LOG_ERROR_RATE) { 337 can_log = 1; 338 last_write_error_log = server.unixtime; 339 } 340 341 /* Log the AOF write error and record the error code. */ 342 if (nwritten == -1) { 343 if (can_log) { 344 serverLog(LL_WARNING,"Error writing to the AOF file: %s", 345 strerror(errno)); 346 server.aof_last_write_errno = errno; 347 } 348 } else { 349 if (can_log) { 350 serverLog(LL_WARNING,"Short write while writing to " 351 "the AOF file: (nwritten=%lld, " 352 "expected=%lld)", 353 (long long)nwritten, 354 (long long)sdslen(server.aof_buf)); 355 } 356 357 if (ftruncate(server.aof_fd, server.aof_current_size) == -1) { 358 if (can_log) { 359 serverLog(LL_WARNING, "Could not remove short write " 360 "from the append-only file. Redis may refuse " 361 "to load the AOF the next time it starts. " 362 "ftruncate: %s", strerror(errno)); 363 } 364 } else { 365 /* If the ftruncate() succeeded we can set nwritten to 366 * -1 since there is no longer partial data into the AOF. */ 367 nwritten = -1; 368 } 369 server.aof_last_write_errno = ENOSPC; 370 } 371 372 /* Handle the AOF write error. */ 373 if (server.aof_fsync == AOF_FSYNC_ALWAYS) { 374 /* We can't recover when the fsync policy is ALWAYS since the 375 * reply for the client is already in the output buffers, and we 376 * have the contract with the user that on acknowledged write data 377 * is synced on disk. */ 378 serverLog(LL_WARNING,"Can't recover from AOF write error when the AOF fsync policy is 'always'. Exiting..."); 379 exit(1); 380 } else { 381 /* Recover from failed write leaving data into the buffer. However 382 * set an error to stop accepting writes as long as the error 383 * condition is not cleared. */ 384 server.aof_last_write_status = C_ERR; 385 386 /* Trim the sds buffer if there was a partial write, and there 387 * was no way to undo it with ftruncate(2). */ 388 if (nwritten > 0) { 389 server.aof_current_size += nwritten; 390 sdsrange(server.aof_buf,nwritten,-1); 391 } 392 return; /* We'll try again on the next call... */ 393 } 394 } else { 395 /* Successful write(2). If AOF was in error state, restore the 396 * OK state and log the event. */ 397 if (server.aof_last_write_status == C_ERR) { 398 serverLog(LL_WARNING, 399 "AOF write error looks solved, Redis can write again."); 400 server.aof_last_write_status = C_OK; 401 } 402 } 403 server.aof_current_size += nwritten; 404 405 /* Re-use AOF buffer when it is small enough. The maximum comes from the 406 * arena size of 4k minus some overhead (but is otherwise arbitrary). */ 407 if ((sdslen(server.aof_buf)+sdsavail(server.aof_buf)) < 4000) { 408 sdsclear(server.aof_buf); 409 } else { 410 sdsfree(server.aof_buf); 411 server.aof_buf = sdsempty(); 412 } 413 414 /* Don't fsync if no-appendfsync-on-rewrite is set to yes and there are 415 * children doing I/O in the background. */ 416 if (server.aof_no_fsync_on_rewrite && 417 (server.aof_child_pid != -1 || server.rdb_child_pid != -1)) 418 return; 419 420 /* Perform the fsync if needed. */ 421 if (server.aof_fsync == AOF_FSYNC_ALWAYS) { 422 /* aof_fsync is defined as fdatasync() for Linux in order to avoid 423 * flushing metadata. */ 424 latencyStartMonitor(latency); 425 aof_fsync(server.aof_fd); /* Let's try to get this data on the disk */ 426 latencyEndMonitor(latency); 427 latencyAddSampleIfNeeded("aof-fsync-always",latency); 428 server.aof_last_fsync = server.unixtime; 429 } else if ((server.aof_fsync == AOF_FSYNC_EVERYSEC && 430 server.unixtime > server.aof_last_fsync)) { 431 if (!sync_in_progress) aof_background_fsync(server.aof_fd); 432 server.aof_last_fsync = server.unixtime; 433 } 434 } 435 436 sds catAppendOnlyGenericCommand(sds dst, int argc, robj **argv) { 437 char buf[32]; 438 int len, j; 439 robj *o; 440 441 buf[0] = '*'; 442 len = 1+ll2string(buf+1,sizeof(buf)-1,argc); 443 buf[len++] = '\r'; 444 buf[len++] = '\n'; 445 dst = sdscatlen(dst,buf,len); 446 447 for (j = 0; j < argc; j++) { 448 o = getDecodedObject(argv[j]); 449 buf[0] = '$'; 450 len = 1+ll2string(buf+1,sizeof(buf)-1,sdslen(o->ptr)); 451 buf[len++] = '\r'; 452 buf[len++] = '\n'; 453 dst = sdscatlen(dst,buf,len); 454 dst = sdscatlen(dst,o->ptr,sdslen(o->ptr)); 455 dst = sdscatlen(dst,"\r\n",2); 456 decrRefCount(o); 457 } 458 return dst; 459 } 460 461 /* Create the sds representation of an PEXPIREAT command, using 462 * 'seconds' as time to live and 'cmd' to understand what command 463 * we are translating into a PEXPIREAT. 464 * 465 * This command is used in order to translate EXPIRE and PEXPIRE commands 466 * into PEXPIREAT command so that we retain precision in the append only 467 * file, and the time is always absolute and not relative. */ 468 sds catAppendOnlyExpireAtCommand(sds buf, struct redisCommand *cmd, robj *key, robj *seconds) { 469 long long when; 470 robj *argv[3]; 471 472 /* Make sure we can use strtoll */ 473 seconds = getDecodedObject(seconds); 474 when = strtoll(seconds->ptr,NULL,10); 475 /* Convert argument into milliseconds for EXPIRE, SETEX, EXPIREAT */ 476 if (cmd->proc == expireCommand || cmd->proc == setexCommand || 477 cmd->proc == expireatCommand) 478 { 479 when *= 1000; 480 } 481 /* Convert into absolute time for EXPIRE, PEXPIRE, SETEX, PSETEX */ 482 if (cmd->proc == expireCommand || cmd->proc == pexpireCommand || 483 cmd->proc == setexCommand || cmd->proc == psetexCommand) 484 { 485 when += mstime(); 486 } 487 decrRefCount(seconds); 488 489 argv[0] = createStringObject("PEXPIREAT",9); 490 argv[1] = key; 491 argv[2] = createStringObjectFromLongLong(when); 492 buf = catAppendOnlyGenericCommand(buf, 3, argv); 493 decrRefCount(argv[0]); 494 decrRefCount(argv[2]); 495 return buf; 496 } 497 498 void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) { 499 sds buf = sdsempty(); 500 robj *tmpargv[3]; 501 502 /* The DB this command was targeting is not the same as the last command 503 * we appended. To issue a SELECT command is needed. */ 504 if (dictid != server.aof_selected_db) { 505 char seldb[64]; 506 507 snprintf(seldb,sizeof(seldb),"%d",dictid); 508 buf = sdscatprintf(buf,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n", 509 (unsigned long)strlen(seldb),seldb); 510 server.aof_selected_db = dictid; 511 } 512 513 if (cmd->proc == expireCommand || cmd->proc == pexpireCommand || 514 cmd->proc == expireatCommand) { 515 /* Translate EXPIRE/PEXPIRE/EXPIREAT into PEXPIREAT */ 516 buf = catAppendOnlyExpireAtCommand(buf,cmd,argv[1],argv[2]); 517 } else if (cmd->proc == setexCommand || cmd->proc == psetexCommand) { 518 /* Translate SETEX/PSETEX to SET and PEXPIREAT */ 519 tmpargv[0] = createStringObject("SET",3); 520 tmpargv[1] = argv[1]; 521 tmpargv[2] = argv[3]; 522 buf = catAppendOnlyGenericCommand(buf,3,tmpargv); 523 decrRefCount(tmpargv[0]); 524 buf = catAppendOnlyExpireAtCommand(buf,cmd,argv[1],argv[2]); 525 } else { 526 /* All the other commands don't need translation or need the 527 * same translation already operated in the command vector 528 * for the replication itself. */ 529 buf = catAppendOnlyGenericCommand(buf,argc,argv); 530 } 531 532 /* Append to the AOF buffer. This will be flushed on disk just before 533 * of re-entering the event loop, so before the client will get a 534 * positive reply about the operation performed. */ 535 if (server.aof_state == AOF_ON) 536 server.aof_buf = sdscatlen(server.aof_buf,buf,sdslen(buf)); 537 538 /* If a background append only file rewriting is in progress we want to 539 * accumulate the differences between the child DB and the current one 540 * in a buffer, so that when the child process will do its work we 541 * can append the differences to the new append only file. */ 542 if (server.aof_child_pid != -1) 543 aofRewriteBufferAppend((unsigned char*)buf,sdslen(buf)); 544 545 sdsfree(buf); 546 } 547 548 /* ---------------------------------------------------------------------------- 549 * AOF loading 550 * ------------------------------------------------------------------------- */ 551 552 /* In Redis commands are always executed in the context of a client, so in 553 * order to load the append only file we need to create a fake client. */ 554 struct client *createFakeClient(void) { 555 struct client *c = zmalloc(sizeof(*c)); 556 557 selectDb(c,0); 558 c->fd = -1; 559 c->name = NULL; 560 c->querybuf = sdsempty(); 561 c->querybuf_peak = 0; 562 c->argc = 0; 563 c->argv = NULL; 564 c->bufpos = 0; 565 c->flags = 0; 566 c->btype = BLOCKED_NONE; 567 /* We set the fake client as a slave waiting for the synchronization 568 * so that Redis will not try to send replies to this client. */ 569 c->replstate = SLAVE_STATE_WAIT_BGSAVE_START; 570 c->reply = listCreate(); 571 c->reply_bytes = 0; 572 c->obuf_soft_limit_reached_time = 0; 573 c->watched_keys = listCreate(); 574 c->peerid = NULL; 575 listSetFreeMethod(c->reply,decrRefCountVoid); 576 listSetDupMethod(c->reply,dupClientReplyValue); 577 initClientMultiState(c); 578 return c; 579 } 580 581 void freeFakeClientArgv(struct client *c) { 582 int j; 583 584 for (j = 0; j < c->argc; j++) 585 decrRefCount(c->argv[j]); 586 zfree(c->argv); 587 } 588 589 void freeFakeClient(struct client *c) { 590 sdsfree(c->querybuf); 591 listRelease(c->reply); 592 listRelease(c->watched_keys); 593 freeClientMultiState(c); 594 zfree(c); 595 } 596 597 /* Replay the append log file. On success C_OK is returned. On non fatal 598 * error (the append only file is zero-length) C_ERR is returned. On 599 * fatal error an error message is logged and the program exists. */ 600 int loadAppendOnlyFile(char *filename) { 601 struct client *fakeClient; 602 FILE *fp = fopen(filename,"r"); 603 struct redis_stat sb; 604 int old_aof_state = server.aof_state; 605 long loops = 0; 606 off_t valid_up_to = 0; /* Offset of the latest well-formed command loaded. */ 607 608 if (fp && redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0) { 609 server.aof_current_size = 0; 610 fclose(fp); 611 return C_ERR; 612 } 613 614 if (fp == NULL) { 615 serverLog(LL_WARNING,"Fatal error: can't open the append log file for reading: %s",strerror(errno)); 616 exit(1); 617 } 618 619 /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI 620 * to the same file we're about to read. */ 621 server.aof_state = AOF_OFF; 622 623 fakeClient = createFakeClient(); 624 startLoading(fp); 625 626 while(1) { 627 int argc, j; 628 unsigned long len; 629 robj **argv; 630 char buf[128]; 631 sds argsds; 632 struct redisCommand *cmd; 633 634 /* Serve the clients from time to time */ 635 if (!(loops++ % 1000)) { 636 loadingProgress(ftello(fp)); 637 processEventsWhileBlocked(); 638 } 639 640 if (fgets(buf,sizeof(buf),fp) == NULL) { 641 if (feof(fp)) 642 break; 643 else 644 goto readerr; 645 } 646 if (buf[0] != '*') goto fmterr; 647 if (buf[1] == '\0') goto readerr; 648 argc = atoi(buf+1); 649 if (argc < 1) goto fmterr; 650 651 argv = zmalloc(sizeof(robj*)*argc); 652 fakeClient->argc = argc; 653 fakeClient->argv = argv; 654 655 for (j = 0; j < argc; j++) { 656 if (fgets(buf,sizeof(buf),fp) == NULL) { 657 fakeClient->argc = j; /* Free up to j-1. */ 658 freeFakeClientArgv(fakeClient); 659 goto readerr; 660 } 661 if (buf[0] != '$') goto fmterr; 662 len = strtol(buf+1,NULL,10); 663 argsds = sdsnewlen(NULL,len); 664 if (len && fread(argsds,len,1,fp) == 0) { 665 sdsfree(argsds); 666 fakeClient->argc = j; /* Free up to j-1. */ 667 freeFakeClientArgv(fakeClient); 668 goto readerr; 669 } 670 argv[j] = createObject(OBJ_STRING,argsds); 671 if (fread(buf,2,1,fp) == 0) { 672 fakeClient->argc = j+1; /* Free up to j. */ 673 freeFakeClientArgv(fakeClient); 674 goto readerr; /* discard CRLF */ 675 } 676 } 677 678 /* Command lookup */ 679 cmd = lookupCommand(argv[0]->ptr); 680 if (!cmd) { 681 serverLog(LL_WARNING,"Unknown command '%s' reading the append only file", (char*)argv[0]->ptr); 682 exit(1); 683 } 684 685 /* Run the command in the context of a fake client */ 686 cmd->proc(fakeClient); 687 688 /* The fake client should not have a reply */ 689 serverAssert(fakeClient->bufpos == 0 && listLength(fakeClient->reply) == 0); 690 /* The fake client should never get blocked */ 691 serverAssert((fakeClient->flags & CLIENT_BLOCKED) == 0); 692 693 /* Clean up. Command code may have changed argv/argc so we use the 694 * argv/argc of the client instead of the local variables. */ 695 freeFakeClientArgv(fakeClient); 696 if (server.aof_load_truncated) valid_up_to = ftello(fp); 697 } 698 699 /* This point can only be reached when EOF is reached without errors. 700 * If the client is in the middle of a MULTI/EXEC, log error and quit. */ 701 if (fakeClient->flags & CLIENT_MULTI) goto uxeof; 702 703 loaded_ok: /* DB loaded, cleanup and return C_OK to the caller. */ 704 fclose(fp); 705 freeFakeClient(fakeClient); 706 server.aof_state = old_aof_state; 707 stopLoading(); 708 aofUpdateCurrentSize(); 709 server.aof_rewrite_base_size = server.aof_current_size; 710 return C_OK; 711 712 readerr: /* Read error. If feof(fp) is true, fall through to unexpected EOF. */ 713 if (!feof(fp)) { 714 serverLog(LL_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno)); 715 exit(1); 716 } 717 718 uxeof: /* Unexpected AOF end of file. */ 719 if (server.aof_load_truncated) { 720 serverLog(LL_WARNING,"!!! Warning: short read while loading the AOF file !!!"); 721 serverLog(LL_WARNING,"!!! Truncating the AOF at offset %llu !!!", 722 (unsigned long long) valid_up_to); 723 if (valid_up_to == -1 || truncate(filename,valid_up_to) == -1) { 724 if (valid_up_to == -1) { 725 serverLog(LL_WARNING,"Last valid command offset is invalid"); 726 } else { 727 serverLog(LL_WARNING,"Error truncating the AOF file: %s", 728 strerror(errno)); 729 } 730 } else { 731 /* Make sure the AOF file descriptor points to the end of the 732 * file after the truncate call. */ 733 if (server.aof_fd != -1 && lseek(server.aof_fd,0,SEEK_END) == -1) { 734 serverLog(LL_WARNING,"Can't seek the end of the AOF file: %s", 735 strerror(errno)); 736 } else { 737 serverLog(LL_WARNING, 738 "AOF loaded anyway because aof-load-truncated is enabled"); 739 goto loaded_ok; 740 } 741 } 742 } 743 serverLog(LL_WARNING,"Unexpected end of file reading the append only file. You can: 1) Make a backup of your AOF file, then use ./redis-check-aof --fix <filename>. 2) Alternatively you can set the 'aof-load-truncated' configuration option to yes and restart the server."); 744 exit(1); 745 746 fmterr: /* Format error. */ 747 serverLog(LL_WARNING,"Bad file format reading the append only file: make a backup of your AOF file, then use ./redis-check-aof --fix <filename>"); 748 exit(1); 749 } 750 751 /* ---------------------------------------------------------------------------- 752 * AOF rewrite 753 * ------------------------------------------------------------------------- */ 754 755 /* Delegate writing an object to writing a bulk string or bulk long long. 756 * This is not placed in rio.c since that adds the redis.h dependency. */ 757 int rioWriteBulkObject(rio *r, robj *obj) { 758 /* Avoid using getDecodedObject to help copy-on-write (we are often 759 * in a child process when this function is called). */ 760 if (obj->encoding == OBJ_ENCODING_INT) { 761 return rioWriteBulkLongLong(r,(long)obj->ptr); 762 } else if (sdsEncodedObject(obj)) { 763 return rioWriteBulkString(r,obj->ptr,sdslen(obj->ptr)); 764 } else { 765 serverPanic("Unknown string encoding"); 766 } 767 } 768 769 /* Emit the commands needed to rebuild a list object. 770 * The function returns 0 on error, 1 on success. */ 771 int rewriteListObject(rio *r, robj *key, robj *o) { 772 long long count = 0, items = listTypeLength(o); 773 774 if (o->encoding == OBJ_ENCODING_QUICKLIST) { 775 quicklist *list = o->ptr; 776 quicklistIter *li = quicklistGetIterator(list, AL_START_HEAD); 777 quicklistEntry entry; 778 779 while (quicklistNext(li,&entry)) { 780 if (count == 0) { 781 int cmd_items = (items > AOF_REWRITE_ITEMS_PER_CMD) ? 782 AOF_REWRITE_ITEMS_PER_CMD : items; 783 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0; 784 if (rioWriteBulkString(r,"RPUSH",5) == 0) return 0; 785 if (rioWriteBulkObject(r,key) == 0) return 0; 786 } 787 788 if (entry.value) { 789 if (rioWriteBulkString(r,(char*)entry.value,entry.sz) == 0) return 0; 790 } else { 791 if (rioWriteBulkLongLong(r,entry.longval) == 0) return 0; 792 } 793 if (++count == AOF_REWRITE_ITEMS_PER_CMD) count = 0; 794 items--; 795 } 796 quicklistReleaseIterator(li); 797 } else { 798 serverPanic("Unknown list encoding"); 799 } 800 return 1; 801 } 802 803 /* Emit the commands needed to rebuild a set object. 804 * The function returns 0 on error, 1 on success. */ 805 int rewriteSetObject(rio *r, robj *key, robj *o) { 806 long long count = 0, items = setTypeSize(o); 807 808 if (o->encoding == OBJ_ENCODING_INTSET) { 809 int ii = 0; 810 int64_t llval; 811 812 while(intsetGet(o->ptr,ii++,&llval)) { 813 if (count == 0) { 814 int cmd_items = (items > AOF_REWRITE_ITEMS_PER_CMD) ? 815 AOF_REWRITE_ITEMS_PER_CMD : items; 816 817 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0; 818 if (rioWriteBulkString(r,"SADD",4) == 0) return 0; 819 if (rioWriteBulkObject(r,key) == 0) return 0; 820 } 821 if (rioWriteBulkLongLong(r,llval) == 0) return 0; 822 if (++count == AOF_REWRITE_ITEMS_PER_CMD) count = 0; 823 items--; 824 } 825 } else if (o->encoding == OBJ_ENCODING_HT) { 826 dictIterator *di = dictGetIterator(o->ptr); 827 dictEntry *de; 828 829 while((de = dictNext(di)) != NULL) { 830 robj *eleobj = dictGetKey(de); 831 if (count == 0) { 832 int cmd_items = (items > AOF_REWRITE_ITEMS_PER_CMD) ? 833 AOF_REWRITE_ITEMS_PER_CMD : items; 834 835 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0; 836 if (rioWriteBulkString(r,"SADD",4) == 0) return 0; 837 if (rioWriteBulkObject(r,key) == 0) return 0; 838 } 839 if (rioWriteBulkObject(r,eleobj) == 0) return 0; 840 if (++count == AOF_REWRITE_ITEMS_PER_CMD) count = 0; 841 items--; 842 } 843 dictReleaseIterator(di); 844 } else { 845 serverPanic("Unknown set encoding"); 846 } 847 return 1; 848 } 849 850 /* Emit the commands needed to rebuild a sorted set object. 851 * The function returns 0 on error, 1 on success. */ 852 int rewriteSortedSetObject(rio *r, robj *key, robj *o) { 853 long long count = 0, items = zsetLength(o); 854 855 if (o->encoding == OBJ_ENCODING_ZIPLIST) { 856 unsigned char *zl = o->ptr; 857 unsigned char *eptr, *sptr; 858 unsigned char *vstr; 859 unsigned int vlen; 860 long long vll; 861 double score; 862 863 eptr = ziplistIndex(zl,0); 864 serverAssert(eptr != NULL); 865 sptr = ziplistNext(zl,eptr); 866 serverAssert(sptr != NULL); 867 868 while (eptr != NULL) { 869 serverAssert(ziplistGet(eptr,&vstr,&vlen,&vll)); 870 score = zzlGetScore(sptr); 871 872 if (count == 0) { 873 int cmd_items = (items > AOF_REWRITE_ITEMS_PER_CMD) ? 874 AOF_REWRITE_ITEMS_PER_CMD : items; 875 876 if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0; 877 if (rioWriteBulkString(r,"ZADD",4) == 0) return 0; 878 if (rioWriteBulkObject(r,key) == 0) return 0; 879 } 880 if (rioWriteBulkDouble(r,score) == 0) return 0; 881 if (vstr != NULL) { 882 if (rioWriteBulkString(r,(char*)vstr,vlen) == 0) return 0; 883 } else { 884 if (rioWriteBulkLongLong(r,vll) == 0) return 0; 885 } 886 zzlNext(zl,&eptr,&sptr); 887 if (++count == AOF_REWRITE_ITEMS_PER_CMD) count = 0; 888 items--; 889 } 890 } else if (o->encoding == OBJ_ENCODING_SKIPLIST) { 891 zset *zs = o->ptr; 892 dictIterator *di = dictGetIterator(zs->dict); 893 dictEntry *de; 894 895 while((de = dictNext(di)) != NULL) { 896 robj *eleobj = dictGetKey(de); 897 double *score = dictGetVal(de); 898 899 if (count == 0) { 900 int cmd_items = (items > AOF_REWRITE_ITEMS_PER_CMD) ? 901 AOF_REWRITE_ITEMS_PER_CMD : items; 902 903 if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0; 904 if (rioWriteBulkString(r,"ZADD",4) == 0) return 0; 905 if (rioWriteBulkObject(r,key) == 0) return 0; 906 } 907 if (rioWriteBulkDouble(r,*score) == 0) return 0; 908 if (rioWriteBulkObject(r,eleobj) == 0) return 0; 909 if (++count == AOF_REWRITE_ITEMS_PER_CMD) count = 0; 910 items--; 911 } 912 dictReleaseIterator(di); 913 } else { 914 serverPanic("Unknown sorted zset encoding"); 915 } 916 return 1; 917 } 918 919 /* Write either the key or the value of the currently selected item of a hash. 920 * The 'hi' argument passes a valid Redis hash iterator. 921 * The 'what' filed specifies if to write a key or a value and can be 922 * either OBJ_HASH_KEY or OBJ_HASH_VALUE. 923 * 924 * The function returns 0 on error, non-zero on success. */ 925 static int rioWriteHashIteratorCursor(rio *r, hashTypeIterator *hi, int what) { 926 if (hi->encoding == OBJ_ENCODING_ZIPLIST) { 927 unsigned char *vstr = NULL; 928 unsigned int vlen = UINT_MAX; 929 long long vll = LLONG_MAX; 930 931 hashTypeCurrentFromZiplist(hi, what, &vstr, &vlen, &vll); 932 if (vstr) { 933 return rioWriteBulkString(r, (char*)vstr, vlen); 934 } else { 935 return rioWriteBulkLongLong(r, vll); 936 } 937 938 } else if (hi->encoding == OBJ_ENCODING_HT) { 939 robj *value; 940 941 hashTypeCurrentFromHashTable(hi, what, &value); 942 return rioWriteBulkObject(r, value); 943 } 944 945 serverPanic("Unknown hash encoding"); 946 return 0; 947 } 948 949 /* Emit the commands needed to rebuild a hash object. 950 * The function returns 0 on error, 1 on success. */ 951 int rewriteHashObject(rio *r, robj *key, robj *o) { 952 hashTypeIterator *hi; 953 long long count = 0, items = hashTypeLength(o); 954 955 hi = hashTypeInitIterator(o); 956 while (hashTypeNext(hi) != C_ERR) { 957 if (count == 0) { 958 int cmd_items = (items > AOF_REWRITE_ITEMS_PER_CMD) ? 959 AOF_REWRITE_ITEMS_PER_CMD : items; 960 961 if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0; 962 if (rioWriteBulkString(r,"HMSET",5) == 0) return 0; 963 if (rioWriteBulkObject(r,key) == 0) return 0; 964 } 965 966 if (rioWriteHashIteratorCursor(r, hi, OBJ_HASH_KEY) == 0) return 0; 967 if (rioWriteHashIteratorCursor(r, hi, OBJ_HASH_VALUE) == 0) return 0; 968 if (++count == AOF_REWRITE_ITEMS_PER_CMD) count = 0; 969 items--; 970 } 971 972 hashTypeReleaseIterator(hi); 973 974 return 1; 975 } 976 977 /* This function is called by the child rewriting the AOF file to read 978 * the difference accumulated from the parent into a buffer, that is 979 * concatenated at the end of the rewrite. */ 980 ssize_t aofReadDiffFromParent(void) { 981 char buf[65536]; /* Default pipe buffer size on most Linux systems. */ 982 ssize_t nread, total = 0; 983 984 while ((nread = 985 read(server.aof_pipe_read_data_from_parent,buf,sizeof(buf))) > 0) { 986 server.aof_child_diff = sdscatlen(server.aof_child_diff,buf,nread); 987 total += nread; 988 } 989 return total; 990 } 991 992 /* Write a sequence of commands able to fully rebuild the dataset into 993 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. 994 * 995 * In order to minimize the number of commands needed in the rewritten 996 * log Redis uses variadic commands when possible, such as RPUSH, SADD 997 * and ZADD. However at max AOF_REWRITE_ITEMS_PER_CMD items per time 998 * are inserted using a single command. */ 999 int rewriteAppendOnlyFile(char *filename) { 1000 dictIterator *di = NULL; 1001 dictEntry *de; 1002 rio aof; 1003 FILE *fp; 1004 char tmpfile[256]; 1005 int j; 1006 long long now = mstime(); 1007 char byte; 1008 size_t processed = 0; 1009 1010 /* Note that we have to use a different temp name here compared to the 1011 * one used by rewriteAppendOnlyFileBackground() function. */ 1012 snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid()); 1013 fp = fopen(tmpfile,"w"); 1014 if (!fp) { 1015 serverLog(LL_WARNING, "Opening the temp file for AOF rewrite in rewriteAppendOnlyFile(): %s", strerror(errno)); 1016 return C_ERR; 1017 } 1018 1019 server.aof_child_diff = sdsempty(); 1020 rioInitWithFile(&aof,fp); 1021 if (server.aof_rewrite_incremental_fsync) 1022 rioSetAutoSync(&aof,AOF_AUTOSYNC_BYTES); 1023 for (j = 0; j < server.dbnum; j++) { 1024 char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n"; 1025 redisDb *db = server.db+j; 1026 dict *d = db->dict; 1027 if (dictSize(d) == 0) continue; 1028 di = dictGetSafeIterator(d); 1029 if (!di) { 1030 fclose(fp); 1031 return C_ERR; 1032 } 1033 1034 /* SELECT the new DB */ 1035 if (rioWrite(&aof,selectcmd,sizeof(selectcmd)-1) == 0) goto werr; 1036 if (rioWriteBulkLongLong(&aof,j) == 0) goto werr; 1037 1038 /* Iterate this DB writing every entry */ 1039 while((de = dictNext(di)) != NULL) { 1040 sds keystr; 1041 robj key, *o; 1042 long long expiretime; 1043 1044 keystr = dictGetKey(de); 1045 o = dictGetVal(de); 1046 initStaticStringObject(key,keystr); 1047 1048 expiretime = getExpire(db,&key); 1049 1050 /* If this key is already expired skip it */ 1051 if (expiretime != -1 && expiretime < now) continue; 1052 1053 /* Save the key and associated value */ 1054 if (o->type == OBJ_STRING) { 1055 /* Emit a SET command */ 1056 char cmd[]="*3\r\n$3\r\nSET\r\n"; 1057 if (rioWrite(&aof,cmd,sizeof(cmd)-1) == 0) goto werr; 1058 /* Key and value */ 1059 if (rioWriteBulkObject(&aof,&key) == 0) goto werr; 1060 if (rioWriteBulkObject(&aof,o) == 0) goto werr; 1061 } else if (o->type == OBJ_LIST) { 1062 if (rewriteListObject(&aof,&key,o) == 0) goto werr; 1063 } else if (o->type == OBJ_SET) { 1064 if (rewriteSetObject(&aof,&key,o) == 0) goto werr; 1065 } else if (o->type == OBJ_ZSET) { 1066 if (rewriteSortedSetObject(&aof,&key,o) == 0) goto werr; 1067 } else if (o->type == OBJ_HASH) { 1068 if (rewriteHashObject(&aof,&key,o) == 0) goto werr; 1069 } else { 1070 serverPanic("Unknown object type"); 1071 } 1072 /* Save the expire time */ 1073 if (expiretime != -1) { 1074 char cmd[]="*3\r\n$9\r\nPEXPIREAT\r\n"; 1075 if (rioWrite(&aof,cmd,sizeof(cmd)-1) == 0) goto werr; 1076 if (rioWriteBulkObject(&aof,&key) == 0) goto werr; 1077 if (rioWriteBulkLongLong(&aof,expiretime) == 0) goto werr; 1078 } 1079 /* Read some diff from the parent process from time to time. */ 1080 if (aof.processed_bytes > processed+1024*10) { 1081 processed = aof.processed_bytes; 1082 aofReadDiffFromParent(); 1083 } 1084 } 1085 dictReleaseIterator(di); 1086 di = NULL; 1087 } 1088 1089 /* Do an initial slow fsync here while the parent is still sending 1090 * data, in order to make the next final fsync faster. */ 1091 if (fflush(fp) == EOF) goto werr; 1092 if (fsync(fileno(fp)) == -1) goto werr; 1093 1094 /* Read again a few times to get more data from the parent. 1095 * We can't read forever (the server may receive data from clients 1096 * faster than it is able to send data to the child), so we try to read 1097 * some more data in a loop as soon as there is a good chance more data 1098 * will come. If it looks like we are wasting time, we abort (this 1099 * happens after 20 ms without new data). */ 1100 int nodata = 0; 1101 mstime_t start = mstime(); 1102 while(mstime()-start < 1000 && nodata < 20) { 1103 if (aeWait(server.aof_pipe_read_data_from_parent, AE_READABLE, 1) <= 0) 1104 { 1105 nodata++; 1106 continue; 1107 } 1108 nodata = 0; /* Start counting from zero, we stop on N *contiguous* 1109 timeouts. */ 1110 aofReadDiffFromParent(); 1111 } 1112 1113 /* Ask the master to stop sending diffs. */ 1114 if (write(server.aof_pipe_write_ack_to_parent,"!",1) != 1) goto werr; 1115 if (anetNonBlock(NULL,server.aof_pipe_read_ack_from_parent) != ANET_OK) 1116 goto werr; 1117 /* We read the ACK from the server using a 10 seconds timeout. Normally 1118 * it should reply ASAP, but just in case we lose its reply, we are sure 1119 * the child will eventually get terminated. */ 1120 if (syncRead(server.aof_pipe_read_ack_from_parent,&byte,1,5000) != 1 || 1121 byte != '!') goto werr; 1122 serverLog(LL_NOTICE,"Parent agreed to stop sending diffs. Finalizing AOF..."); 1123 1124 /* Read the final diff if any. */ 1125 aofReadDiffFromParent(); 1126 1127 /* Write the received diff to the file. */ 1128 serverLog(LL_NOTICE, 1129 "Concatenating %.2f MB of AOF diff received from parent.", 1130 (double) sdslen(server.aof_child_diff) / (1024*1024)); 1131 if (rioWrite(&aof,server.aof_child_diff,sdslen(server.aof_child_diff)) == 0) 1132 goto werr; 1133 1134 /* Make sure data will not remain on the OS's output buffers */ 1135 if (fflush(fp) == EOF) goto werr; 1136 if (fsync(fileno(fp)) == -1) goto werr; 1137 if (fclose(fp) == EOF) goto werr; 1138 1139 /* Use RENAME to make sure the DB file is changed atomically only 1140 * if the generate DB file is ok. */ 1141 if (rename(tmpfile,filename) == -1) { 1142 serverLog(LL_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno)); 1143 unlink(tmpfile); 1144 return C_ERR; 1145 } 1146 serverLog(LL_NOTICE,"SYNC append only file rewrite performed"); 1147 return C_OK; 1148 1149 werr: 1150 serverLog(LL_WARNING,"Write error writing append only file on disk: %s", strerror(errno)); 1151 fclose(fp); 1152 unlink(tmpfile); 1153 if (di) dictReleaseIterator(di); 1154 return C_ERR; 1155 } 1156 1157 /* ---------------------------------------------------------------------------- 1158 * AOF rewrite pipes for IPC 1159 * -------------------------------------------------------------------------- */ 1160 1161 /* This event handler is called when the AOF rewriting child sends us a 1162 * single '!' char to signal we should stop sending buffer diffs. The 1163 * parent sends a '!' as well to acknowledge. */ 1164 void aofChildPipeReadable(aeEventLoop *el, int fd, void *privdata, int mask) { 1165 char byte; 1166 UNUSED(el); 1167 UNUSED(privdata); 1168 UNUSED(mask); 1169 1170 if (read(fd,&byte,1) == 1 && byte == '!') { 1171 serverLog(LL_NOTICE,"AOF rewrite child asks to stop sending diffs."); 1172 server.aof_stop_sending_diff = 1; 1173 if (write(server.aof_pipe_write_ack_to_child,"!",1) != 1) { 1174 /* If we can't send the ack, inform the user, but don't try again 1175 * since in the other side the children will use a timeout if the 1176 * kernel can't buffer our write, or, the children was 1177 * terminated. */ 1178 serverLog(LL_WARNING,"Can't send ACK to AOF child: %s", 1179 strerror(errno)); 1180 } 1181 } 1182 /* Remove the handler since this can be called only one time during a 1183 * rewrite. */ 1184 aeDeleteFileEvent(server.el,server.aof_pipe_read_ack_from_child,AE_READABLE); 1185 } 1186 1187 /* Create the pipes used for parent - child process IPC during rewrite. 1188 * We have a data pipe used to send AOF incremental diffs to the child, 1189 * and two other pipes used by the children to signal it finished with 1190 * the rewrite so no more data should be written, and another for the 1191 * parent to acknowledge it understood this new condition. */ 1192 int aofCreatePipes(void) { 1193 int fds[6] = {-1, -1, -1, -1, -1, -1}; 1194 int j; 1195 1196 if (pipe(fds) == -1) goto error; /* parent -> children data. */ 1197 if (pipe(fds+2) == -1) goto error; /* children -> parent ack. */ 1198 if (pipe(fds+4) == -1) goto error; /* children -> parent ack. */ 1199 /* Parent -> children data is non blocking. */ 1200 if (anetNonBlock(NULL,fds[0]) != ANET_OK) goto error; 1201 if (anetNonBlock(NULL,fds[1]) != ANET_OK) goto error; 1202 if (aeCreateFileEvent(server.el, fds[2], AE_READABLE, aofChildPipeReadable, NULL) == AE_ERR) goto error; 1203 1204 server.aof_pipe_write_data_to_child = fds[1]; 1205 server.aof_pipe_read_data_from_parent = fds[0]; 1206 server.aof_pipe_write_ack_to_parent = fds[3]; 1207 server.aof_pipe_read_ack_from_child = fds[2]; 1208 server.aof_pipe_write_ack_to_child = fds[5]; 1209 server.aof_pipe_read_ack_from_parent = fds[4]; 1210 server.aof_stop_sending_diff = 0; 1211 return C_OK; 1212 1213 error: 1214 serverLog(LL_WARNING,"Error opening /setting AOF rewrite IPC pipes: %s", 1215 strerror(errno)); 1216 for (j = 0; j < 6; j++) if(fds[j] != -1) close(fds[j]); 1217 return C_ERR; 1218 } 1219 1220 void aofClosePipes(void) { 1221 aeDeleteFileEvent(server.el,server.aof_pipe_read_ack_from_child,AE_READABLE); 1222 aeDeleteFileEvent(server.el,server.aof_pipe_write_data_to_child,AE_WRITABLE); 1223 close(server.aof_pipe_write_data_to_child); 1224 close(server.aof_pipe_read_data_from_parent); 1225 close(server.aof_pipe_write_ack_to_parent); 1226 close(server.aof_pipe_read_ack_from_child); 1227 close(server.aof_pipe_write_ack_to_child); 1228 close(server.aof_pipe_read_ack_from_parent); 1229 } 1230 1231 /* ---------------------------------------------------------------------------- 1232 * AOF background rewrite 1233 * ------------------------------------------------------------------------- */ 1234 1235 /* This is how rewriting of the append only file in background works: 1236 * 1237 * 1) The user calls BGREWRITEAOF 1238 * 2) Redis calls this function, that forks(): 1239 * 2a) the child rewrite the append only file in a temp file. 1240 * 2b) the parent accumulates differences in server.aof_rewrite_buf. 1241 * 3) When the child finished '2a' exists. 1242 * 4) The parent will trap the exit code, if it's OK, will append the 1243 * data accumulated into server.aof_rewrite_buf into the temp file, and 1244 * finally will rename(2) the temp file in the actual file name. 1245 * The the new file is reopened as the new append only file. Profit! 1246 */ 1247 int rewriteAppendOnlyFileBackground(void) { 1248 pid_t childpid; 1249 long long start; 1250 1251 if (server.aof_child_pid != -1) return C_ERR; 1252 if (aofCreatePipes() != C_OK) return C_ERR; 1253 start = ustime(); 1254 if ((childpid = fork()) == 0) { 1255 char tmpfile[256]; 1256 1257 /* Child */ 1258 closeListeningSockets(0); 1259 redisSetProcTitle("redis-aof-rewrite"); 1260 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid()); 1261 if (rewriteAppendOnlyFile(tmpfile) == C_OK) { 1262 size_t private_dirty = zmalloc_get_private_dirty(); 1263 1264 if (private_dirty) { 1265 serverLog(LL_NOTICE, 1266 "AOF rewrite: %zu MB of memory used by copy-on-write", 1267 private_dirty/(1024*1024)); 1268 } 1269 exitFromChild(0); 1270 } else { 1271 exitFromChild(1); 1272 } 1273 } else { 1274 /* Parent */ 1275 server.stat_fork_time = ustime()-start; 1276 server.stat_fork_rate = (double) zmalloc_used_memory() * 1000000 / server.stat_fork_time / (1024*1024*1024); /* GB per second. */ 1277 latencyAddSampleIfNeeded("fork",server.stat_fork_time/1000); 1278 if (childpid == -1) { 1279 serverLog(LL_WARNING, 1280 "Can't rewrite append only file in background: fork: %s", 1281 strerror(errno)); 1282 return C_ERR; 1283 } 1284 serverLog(LL_NOTICE, 1285 "Background append only file rewriting started by pid %d",childpid); 1286 server.aof_rewrite_scheduled = 0; 1287 server.aof_rewrite_time_start = time(NULL); 1288 server.aof_child_pid = childpid; 1289 updateDictResizePolicy(); 1290 /* We set appendseldb to -1 in order to force the next call to the 1291 * feedAppendOnlyFile() to issue a SELECT command, so the differences 1292 * accumulated by the parent into server.aof_rewrite_buf will start 1293 * with a SELECT statement and it will be safe to merge. */ 1294 server.aof_selected_db = -1; 1295 replicationScriptCacheFlush(); 1296 return C_OK; 1297 } 1298 return C_OK; /* unreached */ 1299 } 1300 1301 void bgrewriteaofCommand(client *c) { 1302 if (server.aof_child_pid != -1) { 1303 addReplyError(c,"Background append only file rewriting already in progress"); 1304 } else if (server.rdb_child_pid != -1) { 1305 server.aof_rewrite_scheduled = 1; 1306 addReplyStatus(c,"Background append only file rewriting scheduled"); 1307 } else if (rewriteAppendOnlyFileBackground() == C_OK) { 1308 addReplyStatus(c,"Background append only file rewriting started"); 1309 } else { 1310 addReply(c,shared.err); 1311 } 1312 } 1313 1314 void aofRemoveTempFile(pid_t childpid) { 1315 char tmpfile[256]; 1316 1317 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid); 1318 unlink(tmpfile); 1319 } 1320 1321 /* Update the server.aof_current_size field explicitly using stat(2) 1322 * to check the size of the file. This is useful after a rewrite or after 1323 * a restart, normally the size is updated just adding the write length 1324 * to the current length, that is much faster. */ 1325 void aofUpdateCurrentSize(void) { 1326 struct redis_stat sb; 1327 mstime_t latency; 1328 1329 latencyStartMonitor(latency); 1330 if (redis_fstat(server.aof_fd,&sb) == -1) { 1331 serverLog(LL_WARNING,"Unable to obtain the AOF file length. stat: %s", 1332 strerror(errno)); 1333 } else { 1334 server.aof_current_size = sb.st_size; 1335 } 1336 latencyEndMonitor(latency); 1337 latencyAddSampleIfNeeded("aof-fstat",latency); 1338 } 1339 1340 /* A background append only file rewriting (BGREWRITEAOF) terminated its work. 1341 * Handle this. */ 1342 void backgroundRewriteDoneHandler(int exitcode, int bysignal) { 1343 if (!bysignal && exitcode == 0) { 1344 int newfd, oldfd; 1345 char tmpfile[256]; 1346 long long now = ustime(); 1347 mstime_t latency; 1348 1349 serverLog(LL_NOTICE, 1350 "Background AOF rewrite terminated with success"); 1351 1352 /* Flush the differences accumulated by the parent to the 1353 * rewritten AOF. */ 1354 latencyStartMonitor(latency); 1355 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", 1356 (int)server.aof_child_pid); 1357 newfd = open(tmpfile,O_WRONLY|O_APPEND); 1358 if (newfd == -1) { 1359 serverLog(LL_WARNING, 1360 "Unable to open the temporary AOF produced by the child: %s", strerror(errno)); 1361 goto cleanup; 1362 } 1363 1364 if (aofRewriteBufferWrite(newfd) == -1) { 1365 serverLog(LL_WARNING, 1366 "Error trying to flush the parent diff to the rewritten AOF: %s", strerror(errno)); 1367 close(newfd); 1368 goto cleanup; 1369 } 1370 latencyEndMonitor(latency); 1371 latencyAddSampleIfNeeded("aof-rewrite-diff-write",latency); 1372 1373 serverLog(LL_NOTICE, 1374 "Residual parent diff successfully flushed to the rewritten AOF (%.2f MB)", (double) aofRewriteBufferSize() / (1024*1024)); 1375 1376 /* The only remaining thing to do is to rename the temporary file to 1377 * the configured file and switch the file descriptor used to do AOF 1378 * writes. We don't want close(2) or rename(2) calls to block the 1379 * server on old file deletion. 1380 * 1381 * There are two possible scenarios: 1382 * 1383 * 1) AOF is DISABLED and this was a one time rewrite. The temporary 1384 * file will be renamed to the configured file. When this file already 1385 * exists, it will be unlinked, which may block the server. 1386 * 1387 * 2) AOF is ENABLED and the rewritten AOF will immediately start 1388 * receiving writes. After the temporary file is renamed to the 1389 * configured file, the original AOF file descriptor will be closed. 1390 * Since this will be the last reference to that file, closing it 1391 * causes the underlying file to be unlinked, which may block the 1392 * server. 1393 * 1394 * To mitigate the blocking effect of the unlink operation (either 1395 * caused by rename(2) in scenario 1, or by close(2) in scenario 2), we 1396 * use a background thread to take care of this. First, we 1397 * make scenario 1 identical to scenario 2 by opening the target file 1398 * when it exists. The unlink operation after the rename(2) will then 1399 * be executed upon calling close(2) for its descriptor. Everything to 1400 * guarantee atomicity for this switch has already happened by then, so 1401 * we don't care what the outcome or duration of that close operation 1402 * is, as long as the file descriptor is released again. */ 1403 if (server.aof_fd == -1) { 1404 /* AOF disabled */ 1405 1406 /* Don't care if this fails: oldfd will be -1 and we handle that. 1407 * One notable case of -1 return is if the old file does 1408 * not exist. */ 1409 oldfd = open(server.aof_filename,O_RDONLY|O_NONBLOCK); 1410 } else { 1411 /* AOF enabled */ 1412 oldfd = -1; /* We'll set this to the current AOF filedes later. */ 1413 } 1414 1415 /* Rename the temporary file. This will not unlink the target file if 1416 * it exists, because we reference it with "oldfd". */ 1417 latencyStartMonitor(latency); 1418 if (rename(tmpfile,server.aof_filename) == -1) { 1419 serverLog(LL_WARNING, 1420 "Error trying to rename the temporary AOF file: %s", strerror(errno)); 1421 close(newfd); 1422 if (oldfd != -1) close(oldfd); 1423 goto cleanup; 1424 } 1425 latencyEndMonitor(latency); 1426 latencyAddSampleIfNeeded("aof-rename",latency); 1427 1428 if (server.aof_fd == -1) { 1429 /* AOF disabled, we don't need to set the AOF file descriptor 1430 * to this new file, so we can close it. */ 1431 close(newfd); 1432 } else { 1433 /* AOF enabled, replace the old fd with the new one. */ 1434 oldfd = server.aof_fd; 1435 server.aof_fd = newfd; 1436 if (server.aof_fsync == AOF_FSYNC_ALWAYS) 1437 aof_fsync(newfd); 1438 else if (server.aof_fsync == AOF_FSYNC_EVERYSEC) 1439 aof_background_fsync(newfd); 1440 server.aof_selected_db = -1; /* Make sure SELECT is re-issued */ 1441 aofUpdateCurrentSize(); 1442 server.aof_rewrite_base_size = server.aof_current_size; 1443 1444 /* Clear regular AOF buffer since its contents was just written to 1445 * the new AOF from the background rewrite buffer. */ 1446 sdsfree(server.aof_buf); 1447 server.aof_buf = sdsempty(); 1448 } 1449 1450 server.aof_lastbgrewrite_status = C_OK; 1451 1452 serverLog(LL_NOTICE, "Background AOF rewrite finished successfully"); 1453 /* Change state from WAIT_REWRITE to ON if needed */ 1454 if (server.aof_state == AOF_WAIT_REWRITE) 1455 server.aof_state = AOF_ON; 1456 1457 /* Asynchronously close the overwritten AOF. */ 1458 if (oldfd != -1) bioCreateBackgroundJob(BIO_CLOSE_FILE,(void*)(long)oldfd,NULL,NULL); 1459 1460 serverLog(LL_VERBOSE, 1461 "Background AOF rewrite signal handler took %lldus", ustime()-now); 1462 } else if (!bysignal && exitcode != 0) { 1463 /* SIGUSR1 is whitelisted, so we have a way to kill a child without 1464 * tirggering an error conditon. */ 1465 if (bysignal != SIGUSR1) 1466 server.aof_lastbgrewrite_status = C_ERR; 1467 serverLog(LL_WARNING, 1468 "Background AOF rewrite terminated with error"); 1469 } else { 1470 server.aof_lastbgrewrite_status = C_ERR; 1471 1472 serverLog(LL_WARNING, 1473 "Background AOF rewrite terminated by signal %d", bysignal); 1474 } 1475 1476 cleanup: 1477 aofClosePipes(); 1478 aofRewriteBufferReset(); 1479 aofRemoveTempFile(server.aof_child_pid); 1480 server.aof_child_pid = -1; 1481 server.aof_rewrite_time_last = time(NULL)-server.aof_rewrite_time_start; 1482 server.aof_rewrite_time_start = -1; 1483 /* Schedule a new rewrite if we are waiting for it to switch the AOF ON. */ 1484 if (server.aof_state == AOF_WAIT_REWRITE) 1485 server.aof_rewrite_scheduled = 1; 1486 } 1487