1 #include "redis.h" 2 #include "bio.h" 3 #include "rio.h" 4 5 #include <signal.h> 6 #include <fcntl.h> 7 #include <sys/stat.h> 8 #include <sys/types.h> 9 #include <sys/time.h> 10 #include <sys/resource.h> 11 #include <sys/wait.h> 12 13 void aofUpdateCurrentSize(void); 14 15 void aof_background_fsync(int fd) { 16 bioCreateBackgroundJob(REDIS_BIO_AOF_FSYNC,(void*)(long)fd,NULL,NULL); 17 } 18 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); 25 close(server.aof_fd); 26 27 server.aof_fd = -1; 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) { 32 int statloc; 33 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; 43 } 44 } 45 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)); 54 return REDIS_ERR; 55 } 56 if (rewriteAppendOnlyFileBackground() == REDIS_ERR) { 57 close(server.aof_fd); 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."); 59 return REDIS_ERR; 60 } 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; 64 return REDIS_OK; 65 } 66 67 /* Write the append only file buffer on disk. 68 * 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. 74 * 75 * About the 'force' argument: 76 * 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. 82 * 83 * However if force is set to 1 we'll write regardless of the background 84 * fsync. */ 85 void flushAppendOnlyFile(int force) { 86 ssize_t nwritten; 87 int sync_in_progress = 0; 88 89 if (sdslen(server.aof_buf) == 0) return; 90 91 if (server.aof_fsync == AOF_FSYNC_EVERYSEC) 92 sync_in_progress = bioPendingJobsOfType(REDIS_BIO_AOF_FSYNC) != 0; 93 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; 103 return; 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. */ 107 return; 108 } 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."); 113 } 114 } 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; 118 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 123 * or alike */ 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)); 131 } else { 132 redisLog(REDIS_WARNING,"Exiting on short write while writing to " 133 "the append-only file: %s (nwritten=%ld, " 134 "expected=%ld)", 135 strerror(errno), 136 (long)nwritten, 137 (long)sdslen(server.aof_buf)); 138 } 139 exit(1); 140 } 141 server.aof_current_size += nwritten; 142 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); 147 } else { 148 sdsfree(server.aof_buf); 149 server.aof_buf = sdsempty(); 150 } 151 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)) 156 return; 157 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; 168 } 169 } 170 171 sds catAppendOnlyGenericCommand(sds dst, int argc, robj **argv) { 172 char buf[32]; 173 int len, j; 174 robj *o; 175 176 buf[0] = '*'; 177 len = 1+ll2string(buf+1,sizeof(buf)-1,argc); 178 buf[len++] = '\r'; 179 buf[len++] = '\n'; 180 dst = sdscatlen(dst,buf,len); 181 182 for (j = 0; j < argc; j++) { 183 o = getDecodedObject(argv[j]); 184 buf[0] = '$'; 185 len = 1+ll2string(buf+1,sizeof(buf)-1,sdslen(o->ptr)); 186 buf[len++] = '\r'; 187 buf[len++] = '\n'; 188 dst = sdscatlen(dst,buf,len); 189 dst = sdscatlen(dst,o->ptr,sdslen(o->ptr)); 190 dst = sdscatlen(dst,"\r\n",2); 191 decrRefCount(o); 192 } 193 return dst; 194 } 195 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. 199 * 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) { 204 long long when; 205 robj *argv[3]; 206 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) 213 { 214 when *= 1000; 215 } 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) 219 { 220 when += mstime(); 221 } 222 decrRefCount(seconds); 223 224 argv[0] = createStringObject("PEXPIREAT",9); 225 argv[1] = key; 226 argv[2] = createStringObjectFromLongLong(when); 227 buf = catAppendOnlyGenericCommand(buf, 3, argv); 228 decrRefCount(argv[0]); 229 decrRefCount(argv[2]); 230 return buf; 231 } 232 233 void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) { 234 sds buf = sdsempty(); 235 robj *tmpargv[3]; 236 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) { 240 char seldb[64]; 241 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; 246 } 247 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]); 260 } else { 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); 265 } 266 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)); 272 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)); 279 280 sdsfree(buf); 281 } 282 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)); 287 288 selectDb(c,0); 289 c->fd = -1; 290 c->querybuf = sdsempty(); 291 c->querybuf_peak = 0; 292 c->argc = 0; 293 c->argv = NULL; 294 c->bufpos = 0; 295 c->flags = 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(); 300 c->reply_bytes = 0; 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); 306 return c; 307 } 308 309 void freeFakeClient(struct redisClient *c) { 310 sdsfree(c->querybuf); 311 listRelease(c->reply); 312 listRelease(c->watched_keys); 313 freeClientMultiState(c); 314 zfree(c); 315 } 316 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; 325 long loops = 0; 326 327 if (fp && redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0) { 328 server.aof_current_size = 0; 329 fclose(fp); 330 return REDIS_ERR; 331 } 332 333 if (fp == NULL) { 334 redisLog(REDIS_WARNING,"Fatal error: can't open the append log file for reading: %s",strerror(errno)); 335 exit(1); 336 } 337 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; 341 342 fakeClient = createFakeClient(); 343 startLoading(fp); 344 345 while(1) { 346 int argc, j; 347 unsigned long len; 348 robj **argv; 349 char buf[128]; 350 sds argsds; 351 struct redisCommand *cmd; 352 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); 357 } 358 359 if (fgets(buf,sizeof(buf),fp) == NULL) { 360 if (feof(fp)) 361 break; 362 else 363 goto readerr; 364 } 365 if (buf[0] != '*') goto fmterr; 366 argc = atoi(buf+1); 367 if (argc < 1) goto fmterr; 368 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 */ 378 } 379 380 /* Command lookup */ 381 cmd = lookupCommand(argv[0]->ptr); 382 if (!cmd) { 383 redisLog(REDIS_WARNING,"Unknown command '%s' reading the append only file", argv[0]->ptr); 384 exit(1); 385 } 386 /* Run the command in the context of a fake client */ 387 fakeClient->argc = argc; 388 fakeClient->argv = argv; 389 cmd->proc(fakeClient); 390 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); 395 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); 401 } 402 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; 406 407 fclose(fp); 408 freeFakeClient(fakeClient); 409 server.aof_state = old_aof_state; 410 stopLoading(); 411 aofUpdateCurrentSize(); 412 server.aof_rewrite_base_size = server.aof_current_size; 413 return REDIS_OK; 414 415 readerr: 416 if (feof(fp)) { 417 redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file"); 418 } else { 419 redisLog(REDIS_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno)); 420 } 421 exit(1); 422 fmterr: 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>"); 424 exit(1); 425 } 426 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)); 436 } else { 437 redisPanic("Unknown string encoding"); 438 } 439 } 440 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); 445 446 if (o->encoding == REDIS_ENCODING_ZIPLIST) { 447 unsigned char *zl = o->ptr; 448 unsigned char *p = ziplistIndex(zl,0); 449 unsigned char *vstr; 450 unsigned int vlen; 451 long long vlong; 452 453 while(ziplistGet(p,&vstr,&vlen,&vlong)) { 454 if (count == 0) { 455 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ? 456 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items; 457 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; 461 } 462 if (vstr) { 463 if (rioWriteBulkString(r,(char*)vstr,vlen) == 0) return 0; 464 } else { 465 if (rioWriteBulkLongLong(r,vlong) == 0) return 0; 466 } 467 p = ziplistNext(zl,p); 468 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0; 469 items--; 470 } 471 } else if (o->encoding == REDIS_ENCODING_LINKEDLIST) { 472 list *list = o->ptr; 473 listNode *ln; 474 listIter li; 475 476 listRewind(list,&li); 477 while((ln = listNext(&li))) { 478 robj *eleobj = listNodeValue(ln); 479 480 if (count == 0) { 481 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ? 482 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items; 483 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; 487 } 488 if (rioWriteBulkObject(r,eleobj) == 0) return 0; 489 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0; 490 items--; 491 } 492 } else { 493 redisPanic("Unknown list encoding"); 494 } 495 return 1; 496 } 497 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); 502 503 if (o->encoding == REDIS_ENCODING_INTSET) { 504 int ii = 0; 505 int64_t llval; 506 507 while(intsetGet(o->ptr,ii++,&llval)) { 508 if (count == 0) { 509 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ? 510 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items; 511 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; 515 } 516 if (rioWriteBulkLongLong(r,llval) == 0) return 0; 517 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0; 518 items--; 519 } 520 } else if (o->encoding == REDIS_ENCODING_HT) { 521 dictIterator *di = dictGetIterator(o->ptr); 522 dictEntry *de; 523 524 while((de = dictNext(di)) != NULL) { 525 robj *eleobj = dictGetKey(de); 526 if (count == 0) { 527 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ? 528 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items; 529 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; 533 } 534 if (rioWriteBulkObject(r,eleobj) == 0) return 0; 535 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0; 536 items--; 537 } 538 dictReleaseIterator(di); 539 } else { 540 redisPanic("Unknown set encoding"); 541 } 542 return 1; 543 } 544 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); 549 550 if (o->encoding == REDIS_ENCODING_ZIPLIST) { 551 unsigned char *zl = o->ptr; 552 unsigned char *eptr, *sptr; 553 unsigned char *vstr; 554 unsigned int vlen; 555 long long vll; 556 double score; 557 558 eptr = ziplistIndex(zl,0); 559 redisAssert(eptr != NULL); 560 sptr = ziplistNext(zl,eptr); 561 redisAssert(sptr != NULL); 562 563 while (eptr != NULL) { 564 redisAssert(ziplistGet(eptr,&vstr,&vlen,&vll)); 565 score = zzlGetScore(sptr); 566 567 if (count == 0) { 568 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ? 569 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items; 570 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; 574 } 575 if (rioWriteBulkDouble(r,score) == 0) return 0; 576 if (vstr != NULL) { 577 if (rioWriteBulkString(r,(char*)vstr,vlen) == 0) return 0; 578 } else { 579 if (rioWriteBulkLongLong(r,vll) == 0) return 0; 580 } 581 zzlNext(zl,&eptr,&sptr); 582 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0; 583 items--; 584 } 585 } else if (o->encoding == REDIS_ENCODING_SKIPLIST) { 586 zset *zs = o->ptr; 587 dictIterator *di = dictGetIterator(zs->dict); 588 dictEntry *de; 589 590 while((de = dictNext(di)) != NULL) { 591 robj *eleobj = dictGetKey(de); 592 double *score = dictGetVal(de); 593 594 if (count == 0) { 595 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ? 596 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items; 597 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; 601 } 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; 605 items--; 606 } 607 dictReleaseIterator(di); 608 } else { 609 redisPanic("Unknown sorted zset encoding"); 610 } 611 return 1; 612 } 613 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. 618 * 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; 625 626 hashTypeCurrentFromZiplist(hi, what, &vstr, &vlen, &vll); 627 if (vstr) { 628 return rioWriteBulkString(r, (char*)vstr, vlen); 629 } else { 630 return rioWriteBulkLongLong(r, vll); 631 } 632 633 } else if (hi->encoding == REDIS_ENCODING_HT) { 634 robj *value; 635 636 hashTypeCurrentFromHashTable(hi, what, &value); 637 return rioWriteBulkObject(r, value); 638 } 639 640 redisPanic("Unknown hash encoding"); 641 return 0; 642 } 643 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); 649 650 hi = hashTypeInitIterator(o); 651 while (hashTypeNext(hi) != REDIS_ERR) { 652 if (count == 0) { 653 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ? 654 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items; 655 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; 659 } 660 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; 664 items--; 665 } 666 667 hashTypeReleaseIterator(hi); 668 669 return 1; 670 } 671 672 /* Write a sequence of commands able to fully rebuild the dataset into 673 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. 674 * 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; 681 dictEntry *de; 682 rio aof; 683 FILE *fp; 684 char tmpfile[256]; 685 int j; 686 long long now = mstime(); 687 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"); 692 if (!fp) { 693 redisLog(REDIS_WARNING, "Opening the temp file for AOF rewrite in rewriteAppendOnlyFile(): %s", strerror(errno)); 694 return REDIS_ERR; 695 } 696 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; 701 dict *d = db->dict; 702 if (dictSize(d) == 0) continue; 703 di = dictGetSafeIterator(d); 704 if (!di) { 705 fclose(fp); 706 return REDIS_ERR; 707 } 708 709 /* SELECT the new DB */ 710 if (rioWrite(&aof,selectcmd,sizeof(selectcmd)-1) == 0) goto werr; 711 if (rioWriteBulkLongLong(&aof,j) == 0) goto werr; 712 713 /* Iterate this DB writing every entry */ 714 while((de = dictNext(di)) != NULL) { 715 sds keystr; 716 robj key, *o; 717 long long expiretime; 718 719 keystr = dictGetKey(de); 720 o = dictGetVal(de); 721 initStaticStringObject(key,keystr); 722 723 expiretime = getExpire(db,&key); 724 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; 730 /* Key and value */ 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; 741 } else { 742 redisPanic("Unknown object type"); 743 } 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; 752 } 753 } 754 dictReleaseIterator(di); 755 } 756 757 /* Make sure data will not remain on the OS's output buffers */ 758 fflush(fp); 759 aof_fsync(fileno(fp)); 760 fclose(fp); 761 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)); 766 unlink(tmpfile); 767 return REDIS_ERR; 768 } 769 redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed"); 770 return REDIS_OK; 771 772 werr: 773 fclose(fp); 774 unlink(tmpfile); 775 redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno)); 776 if (di) dictReleaseIterator(di); 777 return REDIS_ERR; 778 } 779 780 /* This is how rewriting of the append only file in background works: 781 * 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! 791 */ 792 int rewriteAppendOnlyFileBackground(void) { 793 pid_t childpid; 794 long long start; 795 796 if (server.aof_child_pid != -1) return REDIS_ERR; 797 start = ustime(); 798 if ((childpid = fork()) == 0) { 799 char tmpfile[256]; 800 801 /* Child */ 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) { 806 _exit(0); 807 } else { 808 _exit(1); 809 } 810 } else { 811 /* Parent */ 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", 816 strerror(errno)); 817 return REDIS_ERR; 818 } 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; 829 return REDIS_OK; 830 } 831 return REDIS_OK; /* unreached */ 832 } 833 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"); 842 } else { 843 addReply(c,shared.err); 844 } 845 } 846 847 void aofRemoveTempFile(pid_t childpid) { 848 char tmpfile[256]; 849 850 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid); 851 unlink(tmpfile); 852 } 853 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; 860 861 if (redis_fstat(server.aof_fd,&sb) == -1) { 862 redisLog(REDIS_WARNING,"Unable to obtain the AOF file length. stat: %s", 863 strerror(errno)); 864 } else { 865 server.aof_current_size = sb.st_size; 866 } 867 } 868 869 /* A background append only file rewriting (BGREWRITEAOF) terminated its work. 870 * Handle this. */ 871 void backgroundRewriteDoneHandler(int exitcode, int bysignal) { 872 if (!bysignal && exitcode == 0) { 873 int newfd, oldfd; 874 int nwritten; 875 char tmpfile[256]; 876 long long now = ustime(); 877 878 redisLog(REDIS_NOTICE, 879 "Background AOF rewrite terminated with success"); 880 881 /* Flush the differences accumulated by the parent to the 882 * rewritten AOF. */ 883 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", 884 (int)server.aof_child_pid); 885 newfd = open(tmpfile,O_WRONLY|O_APPEND); 886 if (newfd == -1) { 887 redisLog(REDIS_WARNING, 888 "Unable to open the temporary AOF produced by the child: %s", strerror(errno)); 889 goto cleanup; 890 } 891 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)); 897 } else { 898 redisLog(REDIS_WARNING, 899 "Short write trying to flush the parent diff to the rewritten AOF: %s", strerror(errno)); 900 } 901 close(newfd); 902 goto cleanup; 903 } 904 905 redisLog(REDIS_NOTICE, 906 "Parent diff successfully flushed to the rewritten AOF (%lu bytes)", nwritten); 907 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. 912 * 913 * There are two possible scenarios: 914 * 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. 918 * 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 924 * server. 925 * 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) { 936 /* AOF disabled */ 937 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 940 * not exist. */ 941 oldfd = open(server.aof_filename,O_RDONLY|O_NONBLOCK); 942 } else { 943 /* AOF enabled */ 944 oldfd = -1; /* We'll set this to the current AOF filedes later. */ 945 } 946 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)); 952 close(newfd); 953 if (oldfd != -1) close(oldfd); 954 goto cleanup; 955 } 956 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. */ 960 close(newfd); 961 } else { 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) 966 aof_fsync(newfd); 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; 972 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(); 977 } 978 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; 983 984 /* Asynchronously close the overwritten AOF. */ 985 if (oldfd != -1) bioCreateBackgroundJob(REDIS_BIO_CLOSE_FILE,(void*)(long)oldfd,NULL,NULL); 986 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"); 992 } else { 993 redisLog(REDIS_WARNING, 994 "Background AOF rewrite terminated by signal %d", bysignal); 995 } 996 997 cleanup: 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; 1005 } 1006