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