]> git.saurik.com Git - redis.git/blob - src/aof.c
Log when the child rewriting the AOF is killed by stopAppendOnly()
[redis.git] / src / aof.c
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 = time(NULL);
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 redisLog(REDIS_NOTICE,"Asynchronous AOF fsync is taking too long (disk is busy?). Writing the AOF buffer without waiting for fsync to complete, this may slow down Redis.");
112 }
113 }
114 /* If you are following this code path, then we are going to write so
115 * set reset the postponed flush sentinel to zero. */
116 server.aof_flush_postponed_start = 0;
117
118 /* We want to perform a single write. This should be guaranteed atomic
119 * at least if the filesystem we are writing is a real physical one.
120 * While this will save us against the server being killed I don't think
121 * there is much to do about the whole server stopping for power problems
122 * or alike */
123 nwritten = write(server.aof_fd,server.aof_buf,sdslen(server.aof_buf));
124 if (nwritten != (signed)sdslen(server.aof_buf)) {
125 /* Ooops, we are in troubles. The best thing to do for now is
126 * aborting instead of giving the illusion that everything is
127 * working as expected. */
128 if (nwritten == -1) {
129 redisLog(REDIS_WARNING,"Exiting on error writing to the append-only file: %s",strerror(errno));
130 } else {
131 redisLog(REDIS_WARNING,"Exiting on short write while writing to the append-only file: %s",strerror(errno));
132 }
133 exit(1);
134 }
135 server.aof_current_size += nwritten;
136
137 /* Re-use AOF buffer when it is small enough. The maximum comes from the
138 * arena size of 4k minus some overhead (but is otherwise arbitrary). */
139 if ((sdslen(server.aof_buf)+sdsavail(server.aof_buf)) < 4000) {
140 sdsclear(server.aof_buf);
141 } else {
142 sdsfree(server.aof_buf);
143 server.aof_buf = sdsempty();
144 }
145
146 /* Don't fsync if no-appendfsync-on-rewrite is set to yes and there are
147 * children doing I/O in the background. */
148 if (server.aof_no_fsync_on_rewrite &&
149 (server.aof_child_pid != -1 || server.rdb_child_pid != -1))
150 return;
151
152 /* Perform the fsync if needed. */
153 if (server.aof_fsync == AOF_FSYNC_ALWAYS) {
154 /* aof_fsync is defined as fdatasync() for Linux in order to avoid
155 * flushing metadata. */
156 aof_fsync(server.aof_fd); /* Let's try to get this data on the disk */
157 server.aof_last_fsync = server.unixtime;
158 } else if ((server.aof_fsync == AOF_FSYNC_EVERYSEC &&
159 server.unixtime > server.aof_last_fsync)) {
160 if (!sync_in_progress) aof_background_fsync(server.aof_fd);
161 server.aof_last_fsync = server.unixtime;
162 }
163 }
164
165 sds catAppendOnlyGenericCommand(sds dst, int argc, robj **argv) {
166 char buf[32];
167 int len, j;
168 robj *o;
169
170 buf[0] = '*';
171 len = 1+ll2string(buf+1,sizeof(buf)-1,argc);
172 buf[len++] = '\r';
173 buf[len++] = '\n';
174 dst = sdscatlen(dst,buf,len);
175
176 for (j = 0; j < argc; j++) {
177 o = getDecodedObject(argv[j]);
178 buf[0] = '$';
179 len = 1+ll2string(buf+1,sizeof(buf)-1,sdslen(o->ptr));
180 buf[len++] = '\r';
181 buf[len++] = '\n';
182 dst = sdscatlen(dst,buf,len);
183 dst = sdscatlen(dst,o->ptr,sdslen(o->ptr));
184 dst = sdscatlen(dst,"\r\n",2);
185 decrRefCount(o);
186 }
187 return dst;
188 }
189
190 /* Create the sds representation of an PEXPIREAT command, using
191 * 'seconds' as time to live and 'cmd' to understand what command
192 * we are translating into a PEXPIREAT.
193 *
194 * This command is used in order to translate EXPIRE and PEXPIRE commands
195 * into PEXPIREAT command so that we retain precision in the append only
196 * file, and the time is always absolute and not relative. */
197 sds catAppendOnlyExpireAtCommand(sds buf, struct redisCommand *cmd, robj *key, robj *seconds) {
198 long long when;
199 robj *argv[3];
200
201 /* Make sure we can use strtol */
202 seconds = getDecodedObject(seconds);
203 when = strtoll(seconds->ptr,NULL,10);
204 /* Convert argument into milliseconds for EXPIRE, SETEX, EXPIREAT */
205 if (cmd->proc == expireCommand || cmd->proc == setexCommand ||
206 cmd->proc == expireatCommand)
207 {
208 when *= 1000;
209 }
210 /* Convert into absolute time for EXPIRE, PEXPIRE, SETEX, PSETEX */
211 if (cmd->proc == expireCommand || cmd->proc == pexpireCommand ||
212 cmd->proc == setexCommand || cmd->proc == psetexCommand)
213 {
214 when += mstime();
215 }
216 decrRefCount(seconds);
217
218 argv[0] = createStringObject("PEXPIREAT",9);
219 argv[1] = key;
220 argv[2] = createStringObjectFromLongLong(when);
221 buf = catAppendOnlyGenericCommand(buf, 3, argv);
222 decrRefCount(argv[0]);
223 decrRefCount(argv[2]);
224 return buf;
225 }
226
227 void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) {
228 sds buf = sdsempty();
229 robj *tmpargv[3];
230
231 /* The DB this command was targetting is not the same as the last command
232 * we appendend. To issue a SELECT command is needed. */
233 if (dictid != server.aof_selected_db) {
234 char seldb[64];
235
236 snprintf(seldb,sizeof(seldb),"%d",dictid);
237 buf = sdscatprintf(buf,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
238 (unsigned long)strlen(seldb),seldb);
239 server.aof_selected_db = dictid;
240 }
241
242 if (cmd->proc == expireCommand || cmd->proc == pexpireCommand ||
243 cmd->proc == expireatCommand) {
244 /* Translate EXPIRE/PEXPIRE/EXPIREAT into PEXPIREAT */
245 buf = catAppendOnlyExpireAtCommand(buf,cmd,argv[1],argv[2]);
246 } else if (cmd->proc == setexCommand || cmd->proc == psetexCommand) {
247 /* Translate SETEX/PSETEX to SET and PEXPIREAT */
248 tmpargv[0] = createStringObject("SET",3);
249 tmpargv[1] = argv[1];
250 tmpargv[2] = argv[3];
251 buf = catAppendOnlyGenericCommand(buf,3,tmpargv);
252 decrRefCount(tmpargv[0]);
253 buf = catAppendOnlyExpireAtCommand(buf,cmd,argv[1],argv[2]);
254 } else {
255 /* All the other commands don't need translation or need the
256 * same translation already operated in the command vector
257 * for the replication itself. */
258 buf = catAppendOnlyGenericCommand(buf,argc,argv);
259 }
260
261 /* Append to the AOF buffer. This will be flushed on disk just before
262 * of re-entering the event loop, so before the client will get a
263 * positive reply about the operation performed. */
264 if (server.aof_state == REDIS_AOF_ON)
265 server.aof_buf = sdscatlen(server.aof_buf,buf,sdslen(buf));
266
267 /* If a background append only file rewriting is in progress we want to
268 * accumulate the differences between the child DB and the current one
269 * in a buffer, so that when the child process will do its work we
270 * can append the differences to the new append only file. */
271 if (server.aof_child_pid != -1)
272 server.aof_rewrite_buf = sdscatlen(server.aof_rewrite_buf,buf,sdslen(buf));
273
274 sdsfree(buf);
275 }
276
277 /* In Redis commands are always executed in the context of a client, so in
278 * order to load the append only file we need to create a fake client. */
279 struct redisClient *createFakeClient(void) {
280 struct redisClient *c = zmalloc(sizeof(*c));
281
282 selectDb(c,0);
283 c->fd = -1;
284 c->querybuf = sdsempty();
285 c->argc = 0;
286 c->argv = NULL;
287 c->bufpos = 0;
288 c->flags = 0;
289 /* We set the fake client as a slave waiting for the synchronization
290 * so that Redis will not try to send replies to this client. */
291 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
292 c->reply = listCreate();
293 c->watched_keys = listCreate();
294 listSetFreeMethod(c->reply,decrRefCount);
295 listSetDupMethod(c->reply,dupClientReplyValue);
296 initClientMultiState(c);
297 return c;
298 }
299
300 void freeFakeClient(struct redisClient *c) {
301 sdsfree(c->querybuf);
302 listRelease(c->reply);
303 listRelease(c->watched_keys);
304 freeClientMultiState(c);
305 zfree(c);
306 }
307
308 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
309 * error (the append only file is zero-length) REDIS_ERR is returned. On
310 * fatal error an error message is logged and the program exists. */
311 int loadAppendOnlyFile(char *filename) {
312 struct redisClient *fakeClient;
313 FILE *fp = fopen(filename,"r");
314 struct redis_stat sb;
315 int old_aof_state = server.aof_state;
316 long loops = 0;
317
318 if (fp && redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0) {
319 server.aof_current_size = 0;
320 fclose(fp);
321 return REDIS_ERR;
322 }
323
324 if (fp == NULL) {
325 redisLog(REDIS_WARNING,"Fatal error: can't open the append log file for reading: %s",strerror(errno));
326 exit(1);
327 }
328
329 /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
330 * to the same file we're about to read. */
331 server.aof_state = REDIS_AOF_OFF;
332
333 fakeClient = createFakeClient();
334 startLoading(fp);
335
336 while(1) {
337 int argc, j;
338 unsigned long len;
339 robj **argv;
340 char buf[128];
341 sds argsds;
342 struct redisCommand *cmd;
343
344 /* Serve the clients from time to time */
345 if (!(loops++ % 1000)) {
346 loadingProgress(ftello(fp));
347 aeProcessEvents(server.el, AE_FILE_EVENTS|AE_DONT_WAIT);
348 }
349
350 if (fgets(buf,sizeof(buf),fp) == NULL) {
351 if (feof(fp))
352 break;
353 else
354 goto readerr;
355 }
356 if (buf[0] != '*') goto fmterr;
357 argc = atoi(buf+1);
358 if (argc < 1) goto fmterr;
359
360 argv = zmalloc(sizeof(robj*)*argc);
361 for (j = 0; j < argc; j++) {
362 if (fgets(buf,sizeof(buf),fp) == NULL) goto readerr;
363 if (buf[0] != '$') goto fmterr;
364 len = strtol(buf+1,NULL,10);
365 argsds = sdsnewlen(NULL,len);
366 if (len && fread(argsds,len,1,fp) == 0) goto fmterr;
367 argv[j] = createObject(REDIS_STRING,argsds);
368 if (fread(buf,2,1,fp) == 0) goto fmterr; /* discard CRLF */
369 }
370
371 /* Command lookup */
372 cmd = lookupCommand(argv[0]->ptr);
373 if (!cmd) {
374 redisLog(REDIS_WARNING,"Unknown command '%s' reading the append only file", argv[0]->ptr);
375 exit(1);
376 }
377 /* Run the command in the context of a fake client */
378 fakeClient->argc = argc;
379 fakeClient->argv = argv;
380 cmd->proc(fakeClient);
381
382 /* The fake client should not have a reply */
383 redisAssert(fakeClient->bufpos == 0 && listLength(fakeClient->reply) == 0);
384 /* The fake client should never get blocked */
385 redisAssert((fakeClient->flags & REDIS_BLOCKED) == 0);
386
387 /* Clean up. Command code may have changed argv/argc so we use the
388 * argv/argc of the client instead of the local variables. */
389 for (j = 0; j < fakeClient->argc; j++)
390 decrRefCount(fakeClient->argv[j]);
391 zfree(fakeClient->argv);
392 }
393
394 /* This point can only be reached when EOF is reached without errors.
395 * If the client is in the middle of a MULTI/EXEC, log error and quit. */
396 if (fakeClient->flags & REDIS_MULTI) goto readerr;
397
398 fclose(fp);
399 freeFakeClient(fakeClient);
400 server.aof_state = old_aof_state;
401 stopLoading();
402 aofUpdateCurrentSize();
403 server.aof_rewrite_base_size = server.aof_current_size;
404 return REDIS_OK;
405
406 readerr:
407 if (feof(fp)) {
408 redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file");
409 } else {
410 redisLog(REDIS_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno));
411 }
412 exit(1);
413 fmterr:
414 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>");
415 exit(1);
416 }
417
418 /* Delegate writing an object to writing a bulk string or bulk long long.
419 * This is not placed in rio.c since that adds the redis.h dependency. */
420 int rioWriteBulkObject(rio *r, robj *obj) {
421 /* Avoid using getDecodedObject to help copy-on-write (we are often
422 * in a child process when this function is called). */
423 if (obj->encoding == REDIS_ENCODING_INT) {
424 return rioWriteBulkLongLong(r,(long)obj->ptr);
425 } else if (obj->encoding == REDIS_ENCODING_RAW) {
426 return rioWriteBulkString(r,obj->ptr,sdslen(obj->ptr));
427 } else {
428 redisPanic("Unknown string encoding");
429 }
430 }
431
432 /* Emit the commands needed to rebuild a list object.
433 * The function returns 0 on error, 1 on success. */
434 int rewriteListObject(rio *r, robj *key, robj *o) {
435 long long count = 0, items = listTypeLength(o);
436
437 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
438 unsigned char *zl = o->ptr;
439 unsigned char *p = ziplistIndex(zl,0);
440 unsigned char *vstr;
441 unsigned int vlen;
442 long long vlong;
443
444 while(ziplistGet(p,&vstr,&vlen,&vlong)) {
445 if (count == 0) {
446 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
447 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
448
449 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
450 if (rioWriteBulkString(r,"RPUSH",5) == 0) return 0;
451 if (rioWriteBulkObject(r,key) == 0) return 0;
452 }
453 if (vstr) {
454 if (rioWriteBulkString(r,(char*)vstr,vlen) == 0) return 0;
455 } else {
456 if (rioWriteBulkLongLong(r,vlong) == 0) return 0;
457 }
458 p = ziplistNext(zl,p);
459 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
460 items--;
461 }
462 } else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
463 list *list = o->ptr;
464 listNode *ln;
465 listIter li;
466
467 listRewind(list,&li);
468 while((ln = listNext(&li))) {
469 robj *eleobj = listNodeValue(ln);
470
471 if (count == 0) {
472 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
473 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
474
475 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
476 if (rioWriteBulkString(r,"RPUSH",5) == 0) return 0;
477 if (rioWriteBulkObject(r,key) == 0) return 0;
478 }
479 if (rioWriteBulkObject(r,eleobj) == 0) return 0;
480 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
481 items--;
482 }
483 } else {
484 redisPanic("Unknown list encoding");
485 }
486 return 1;
487 }
488
489 /* Emit the commands needed to rebuild a set object.
490 * The function returns 0 on error, 1 on success. */
491 int rewriteSetObject(rio *r, robj *key, robj *o) {
492 long long count = 0, items = setTypeSize(o);
493
494 if (o->encoding == REDIS_ENCODING_INTSET) {
495 int ii = 0;
496 int64_t llval;
497
498 while(intsetGet(o->ptr,ii++,&llval)) {
499 if (count == 0) {
500 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
501 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
502
503 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
504 if (rioWriteBulkString(r,"SADD",4) == 0) return 0;
505 if (rioWriteBulkObject(r,key) == 0) return 0;
506 }
507 if (rioWriteBulkLongLong(r,llval) == 0) return 0;
508 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
509 items--;
510 }
511 } else if (o->encoding == REDIS_ENCODING_HT) {
512 dictIterator *di = dictGetIterator(o->ptr);
513 dictEntry *de;
514
515 while((de = dictNext(di)) != NULL) {
516 robj *eleobj = dictGetKey(de);
517 if (count == 0) {
518 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
519 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
520
521 if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
522 if (rioWriteBulkString(r,"SADD",4) == 0) return 0;
523 if (rioWriteBulkObject(r,key) == 0) return 0;
524 }
525 if (rioWriteBulkObject(r,eleobj) == 0) return 0;
526 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
527 items--;
528 }
529 dictReleaseIterator(di);
530 } else {
531 redisPanic("Unknown set encoding");
532 }
533 return 1;
534 }
535
536 /* Emit the commands needed to rebuild a sorted set object.
537 * The function returns 0 on error, 1 on success. */
538 int rewriteSortedSetObject(rio *r, robj *key, robj *o) {
539 long long count = 0, items = zsetLength(o);
540
541 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
542 unsigned char *zl = o->ptr;
543 unsigned char *eptr, *sptr;
544 unsigned char *vstr;
545 unsigned int vlen;
546 long long vll;
547 double score;
548
549 eptr = ziplistIndex(zl,0);
550 redisAssert(eptr != NULL);
551 sptr = ziplistNext(zl,eptr);
552 redisAssert(sptr != NULL);
553
554 while (eptr != NULL) {
555 redisAssert(ziplistGet(eptr,&vstr,&vlen,&vll));
556 score = zzlGetScore(sptr);
557
558 if (count == 0) {
559 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
560 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
561
562 if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0;
563 if (rioWriteBulkString(r,"ZADD",4) == 0) return 0;
564 if (rioWriteBulkObject(r,key) == 0) return 0;
565 }
566 if (rioWriteBulkDouble(r,score) == 0) return 0;
567 if (vstr != NULL) {
568 if (rioWriteBulkString(r,(char*)vstr,vlen) == 0) return 0;
569 } else {
570 if (rioWriteBulkLongLong(r,vll) == 0) return 0;
571 }
572 zzlNext(zl,&eptr,&sptr);
573 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
574 items--;
575 }
576 } else if (o->encoding == REDIS_ENCODING_SKIPLIST) {
577 zset *zs = o->ptr;
578 dictIterator *di = dictGetIterator(zs->dict);
579 dictEntry *de;
580
581 while((de = dictNext(di)) != NULL) {
582 robj *eleobj = dictGetKey(de);
583 double *score = dictGetVal(de);
584
585 if (count == 0) {
586 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
587 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
588
589 if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0;
590 if (rioWriteBulkString(r,"ZADD",4) == 0) return 0;
591 if (rioWriteBulkObject(r,key) == 0) return 0;
592 }
593 if (rioWriteBulkDouble(r,*score) == 0) return 0;
594 if (rioWriteBulkObject(r,eleobj) == 0) return 0;
595 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
596 items--;
597 }
598 dictReleaseIterator(di);
599 } else {
600 redisPanic("Unknown sorted zset encoding");
601 }
602 return 1;
603 }
604
605 /* Emit the commands needed to rebuild a hash object.
606 * The function returns 0 on error, 1 on success. */
607 int rewriteHashObject(rio *r, robj *key, robj *o) {
608 long long count = 0, items = hashTypeLength(o);
609
610 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
611 unsigned char *p = zipmapRewind(o->ptr);
612 unsigned char *field, *val;
613 unsigned int flen, vlen;
614
615 while((p = zipmapNext(p,&field,&flen,&val,&vlen)) != NULL) {
616 if (count == 0) {
617 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
618 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
619
620 if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0;
621 if (rioWriteBulkString(r,"HMSET",5) == 0) return 0;
622 if (rioWriteBulkObject(r,key) == 0) return 0;
623 }
624 if (rioWriteBulkString(r,(char*)field,flen) == 0) return 0;
625 if (rioWriteBulkString(r,(char*)val,vlen) == 0) return 0;
626 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
627 items--;
628 }
629 } else {
630 dictIterator *di = dictGetIterator(o->ptr);
631 dictEntry *de;
632
633 while((de = dictNext(di)) != NULL) {
634 robj *field = dictGetKey(de);
635 robj *val = dictGetVal(de);
636
637 if (count == 0) {
638 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
639 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
640
641 if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0;
642 if (rioWriteBulkString(r,"HMSET",5) == 0) return 0;
643 if (rioWriteBulkObject(r,key) == 0) return 0;
644 }
645 if (rioWriteBulkObject(r,field) == 0) return 0;
646 if (rioWriteBulkObject(r,val) == 0) return 0;
647 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
648 items--;
649 }
650 dictReleaseIterator(di);
651 }
652 return 1;
653 }
654
655 /* Write a sequence of commands able to fully rebuild the dataset into
656 * "filename". Used both by REWRITEAOF and BGREWRITEAOF.
657 *
658 * In order to minimize the number of commands needed in the rewritten
659 * log Redis uses variadic commands when possible, such as RPUSH, SADD
660 * and ZADD. However at max REDIS_AOF_REWRITE_ITEMS_PER_CMD items per time
661 * are inserted using a single command. */
662 int rewriteAppendOnlyFile(char *filename) {
663 dictIterator *di = NULL;
664 dictEntry *de;
665 rio aof;
666 FILE *fp;
667 char tmpfile[256];
668 int j;
669 long long now = mstime();
670
671 /* Note that we have to use a different temp name here compared to the
672 * one used by rewriteAppendOnlyFileBackground() function. */
673 snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
674 fp = fopen(tmpfile,"w");
675 if (!fp) {
676 redisLog(REDIS_WARNING, "Failed rewriting the append only file: %s", strerror(errno));
677 return REDIS_ERR;
678 }
679
680 rioInitWithFile(&aof,fp);
681 for (j = 0; j < server.dbnum; j++) {
682 char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
683 redisDb *db = server.db+j;
684 dict *d = db->dict;
685 if (dictSize(d) == 0) continue;
686 di = dictGetSafeIterator(d);
687 if (!di) {
688 fclose(fp);
689 return REDIS_ERR;
690 }
691
692 /* SELECT the new DB */
693 if (rioWrite(&aof,selectcmd,sizeof(selectcmd)-1) == 0) goto werr;
694 if (rioWriteBulkLongLong(&aof,j) == 0) goto werr;
695
696 /* Iterate this DB writing every entry */
697 while((de = dictNext(di)) != NULL) {
698 sds keystr;
699 robj key, *o;
700 long long expiretime;
701
702 keystr = dictGetKey(de);
703 o = dictGetVal(de);
704 initStaticStringObject(key,keystr);
705
706 expiretime = getExpire(db,&key);
707
708 /* Save the key and associated value */
709 if (o->type == REDIS_STRING) {
710 /* Emit a SET command */
711 char cmd[]="*3\r\n$3\r\nSET\r\n";
712 if (rioWrite(&aof,cmd,sizeof(cmd)-1) == 0) goto werr;
713 /* Key and value */
714 if (rioWriteBulkObject(&aof,&key) == 0) goto werr;
715 if (rioWriteBulkObject(&aof,o) == 0) goto werr;
716 } else if (o->type == REDIS_LIST) {
717 if (rewriteListObject(&aof,&key,o) == 0) goto werr;
718 } else if (o->type == REDIS_SET) {
719 if (rewriteSetObject(&aof,&key,o) == 0) goto werr;
720 } else if (o->type == REDIS_ZSET) {
721 if (rewriteSortedSetObject(&aof,&key,o) == 0) goto werr;
722 } else if (o->type == REDIS_HASH) {
723 if (rewriteHashObject(&aof,&key,o) == 0) goto werr;
724 } else {
725 redisPanic("Unknown object type");
726 }
727 /* Save the expire time */
728 if (expiretime != -1) {
729 char cmd[]="*3\r\n$9\r\nPEXPIREAT\r\n";
730 /* If this key is already expired skip it */
731 if (expiretime < now) continue;
732 if (rioWrite(&aof,cmd,sizeof(cmd)-1) == 0) goto werr;
733 if (rioWriteBulkObject(&aof,&key) == 0) goto werr;
734 if (rioWriteBulkLongLong(&aof,expiretime) == 0) goto werr;
735 }
736 }
737 dictReleaseIterator(di);
738 }
739
740 /* Make sure data will not remain on the OS's output buffers */
741 fflush(fp);
742 aof_fsync(fileno(fp));
743 fclose(fp);
744
745 /* Use RENAME to make sure the DB file is changed atomically only
746 * if the generate DB file is ok. */
747 if (rename(tmpfile,filename) == -1) {
748 redisLog(REDIS_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno));
749 unlink(tmpfile);
750 return REDIS_ERR;
751 }
752 redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");
753 return REDIS_OK;
754
755 werr:
756 fclose(fp);
757 unlink(tmpfile);
758 redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));
759 if (di) dictReleaseIterator(di);
760 return REDIS_ERR;
761 }
762
763 /* This is how rewriting of the append only file in background works:
764 *
765 * 1) The user calls BGREWRITEAOF
766 * 2) Redis calls this function, that forks():
767 * 2a) the child rewrite the append only file in a temp file.
768 * 2b) the parent accumulates differences in server.aof_rewrite_buf.
769 * 3) When the child finished '2a' exists.
770 * 4) The parent will trap the exit code, if it's OK, will append the
771 * data accumulated into server.aof_rewrite_buf into the temp file, and
772 * finally will rename(2) the temp file in the actual file name.
773 * The the new file is reopened as the new append only file. Profit!
774 */
775 int rewriteAppendOnlyFileBackground(void) {
776 pid_t childpid;
777 long long start;
778
779 if (server.aof_child_pid != -1) return REDIS_ERR;
780 start = ustime();
781 if ((childpid = fork()) == 0) {
782 char tmpfile[256];
783
784 /* Child */
785 if (server.ipfd > 0) close(server.ipfd);
786 if (server.sofd > 0) close(server.sofd);
787 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
788 if (rewriteAppendOnlyFile(tmpfile) == REDIS_OK) {
789 _exit(0);
790 } else {
791 _exit(1);
792 }
793 } else {
794 /* Parent */
795 server.stat_fork_time = ustime()-start;
796 if (childpid == -1) {
797 redisLog(REDIS_WARNING,
798 "Can't rewrite append only file in background: fork: %s",
799 strerror(errno));
800 return REDIS_ERR;
801 }
802 redisLog(REDIS_NOTICE,
803 "Background append only file rewriting started by pid %d",childpid);
804 server.aof_rewrite_scheduled = 0;
805 server.aof_child_pid = childpid;
806 updateDictResizePolicy();
807 /* We set appendseldb to -1 in order to force the next call to the
808 * feedAppendOnlyFile() to issue a SELECT command, so the differences
809 * accumulated by the parent into server.aof_rewrite_buf will start
810 * with a SELECT statement and it will be safe to merge. */
811 server.aof_selected_db = -1;
812 return REDIS_OK;
813 }
814 return REDIS_OK; /* unreached */
815 }
816
817 void bgrewriteaofCommand(redisClient *c) {
818 if (server.aof_child_pid != -1) {
819 addReplyError(c,"Background append only file rewriting already in progress");
820 } else if (server.rdb_child_pid != -1) {
821 server.aof_rewrite_scheduled = 1;
822 addReplyStatus(c,"Background append only file rewriting scheduled");
823 } else if (rewriteAppendOnlyFileBackground() == REDIS_OK) {
824 addReplyStatus(c,"Background append only file rewriting started");
825 } else {
826 addReply(c,shared.err);
827 }
828 }
829
830 void aofRemoveTempFile(pid_t childpid) {
831 char tmpfile[256];
832
833 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid);
834 unlink(tmpfile);
835 }
836
837 /* Update the server.aof_current_size filed explicitly using stat(2)
838 * to check the size of the file. This is useful after a rewrite or after
839 * a restart, normally the size is updated just adding the write length
840 * to the current lenght, that is much faster. */
841 void aofUpdateCurrentSize(void) {
842 struct redis_stat sb;
843
844 if (redis_fstat(server.aof_fd,&sb) == -1) {
845 redisLog(REDIS_WARNING,"Unable to check the AOF length: %s",
846 strerror(errno));
847 } else {
848 server.aof_current_size = sb.st_size;
849 }
850 }
851
852 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
853 * Handle this. */
854 void backgroundRewriteDoneHandler(int exitcode, int bysignal) {
855 if (!bysignal && exitcode == 0) {
856 int newfd, oldfd;
857 int nwritten;
858 char tmpfile[256];
859 long long now = ustime();
860
861 redisLog(REDIS_NOTICE,
862 "Background AOF rewrite terminated with success");
863
864 /* Flush the differences accumulated by the parent to the
865 * rewritten AOF. */
866 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof",
867 (int)server.aof_child_pid);
868 newfd = open(tmpfile,O_WRONLY|O_APPEND);
869 if (newfd == -1) {
870 redisLog(REDIS_WARNING,
871 "Unable to open the temporary AOF produced by the child: %s", strerror(errno));
872 goto cleanup;
873 }
874
875 nwritten = write(newfd,server.aof_rewrite_buf,sdslen(server.aof_rewrite_buf));
876 if (nwritten != (signed)sdslen(server.aof_rewrite_buf)) {
877 if (nwritten == -1) {
878 redisLog(REDIS_WARNING,
879 "Error trying to flush the parent diff to the rewritten AOF: %s", strerror(errno));
880 } else {
881 redisLog(REDIS_WARNING,
882 "Short write trying to flush the parent diff to the rewritten AOF: %s", strerror(errno));
883 }
884 close(newfd);
885 goto cleanup;
886 }
887
888 redisLog(REDIS_NOTICE,
889 "Parent diff successfully flushed to the rewritten AOF (%lu bytes)", nwritten);
890
891 /* The only remaining thing to do is to rename the temporary file to
892 * the configured file and switch the file descriptor used to do AOF
893 * writes. We don't want close(2) or rename(2) calls to block the
894 * server on old file deletion.
895 *
896 * There are two possible scenarios:
897 *
898 * 1) AOF is DISABLED and this was a one time rewrite. The temporary
899 * file will be renamed to the configured file. When this file already
900 * exists, it will be unlinked, which may block the server.
901 *
902 * 2) AOF is ENABLED and the rewritten AOF will immediately start
903 * receiving writes. After the temporary file is renamed to the
904 * configured file, the original AOF file descriptor will be closed.
905 * Since this will be the last reference to that file, closing it
906 * causes the underlying file to be unlinked, which may block the
907 * server.
908 *
909 * To mitigate the blocking effect of the unlink operation (either
910 * caused by rename(2) in scenario 1, or by close(2) in scenario 2), we
911 * use a background thread to take care of this. First, we
912 * make scenario 1 identical to scenario 2 by opening the target file
913 * when it exists. The unlink operation after the rename(2) will then
914 * be executed upon calling close(2) for its descriptor. Everything to
915 * guarantee atomicity for this switch has already happened by then, so
916 * we don't care what the outcome or duration of that close operation
917 * is, as long as the file descriptor is released again. */
918 if (server.aof_fd == -1) {
919 /* AOF disabled */
920
921 /* Don't care if this fails: oldfd will be -1 and we handle that.
922 * One notable case of -1 return is if the old file does
923 * not exist. */
924 oldfd = open(server.aof_filename,O_RDONLY|O_NONBLOCK);
925 } else {
926 /* AOF enabled */
927 oldfd = -1; /* We'll set this to the current AOF filedes later. */
928 }
929
930 /* Rename the temporary file. This will not unlink the target file if
931 * it exists, because we reference it with "oldfd". */
932 if (rename(tmpfile,server.aof_filename) == -1) {
933 redisLog(REDIS_WARNING,
934 "Error trying to rename the temporary AOF: %s", strerror(errno));
935 close(newfd);
936 if (oldfd != -1) close(oldfd);
937 goto cleanup;
938 }
939
940 if (server.aof_fd == -1) {
941 /* AOF disabled, we don't need to set the AOF file descriptor
942 * to this new file, so we can close it. */
943 close(newfd);
944 } else {
945 /* AOF enabled, replace the old fd with the new one. */
946 oldfd = server.aof_fd;
947 server.aof_fd = newfd;
948 if (server.aof_fsync == AOF_FSYNC_ALWAYS)
949 aof_fsync(newfd);
950 else if (server.aof_fsync == AOF_FSYNC_EVERYSEC)
951 aof_background_fsync(newfd);
952 server.aof_selected_db = -1; /* Make sure SELECT is re-issued */
953 aofUpdateCurrentSize();
954 server.aof_rewrite_base_size = server.aof_current_size;
955
956 /* Clear regular AOF buffer since its contents was just written to
957 * the new AOF from the background rewrite buffer. */
958 sdsfree(server.aof_buf);
959 server.aof_buf = sdsempty();
960 }
961
962 redisLog(REDIS_NOTICE, "Background AOF rewrite successful");
963 /* Change state from WAIT_REWRITE to ON if needed */
964 if (server.aof_state == REDIS_AOF_WAIT_REWRITE)
965 server.aof_state = REDIS_AOF_ON;
966
967 /* Asynchronously close the overwritten AOF. */
968 if (oldfd != -1) bioCreateBackgroundJob(REDIS_BIO_CLOSE_FILE,(void*)(long)oldfd,NULL,NULL);
969
970 redisLog(REDIS_VERBOSE,
971 "Background AOF rewrite signal handler took %lldus", ustime()-now);
972 } else if (!bysignal && exitcode != 0) {
973 redisLog(REDIS_WARNING,
974 "Background AOF rewrite terminated with error");
975 } else {
976 redisLog(REDIS_WARNING,
977 "Background AOF rewrite terminated by signal %d", bysignal);
978 }
979
980 cleanup:
981 sdsfree(server.aof_rewrite_buf);
982 server.aof_rewrite_buf = sdsempty();
983 aofRemoveTempFile(server.aof_child_pid);
984 server.aof_child_pid = -1;
985 /* Schedule a new rewrite if we are waiting for it to switch the AOF ON. */
986 if (server.aof_state == REDIS_AOF_WAIT_REWRITE)
987 server.aof_rewrite_scheduled = 1;
988 }