]> git.saurik.com Git - redis.git/blame - src/aof.c
Merge pull request #496 from pietern/2.6-makeinstall
[redis.git] / src / aof.c
CommitLineData
e2641e09 1#include "redis.h"
986630af 2#include "bio.h"
f9c6f39b 3#include "rio.h"
e2641e09 4
5#include <signal.h>
6#include <fcntl.h>
7#include <sys/stat.h>
3688d7f3 8#include <sys/types.h>
9#include <sys/time.h>
10#include <sys/resource.h>
11#include <sys/wait.h>
e2641e09 12
b333e239 13void aofUpdateCurrentSize(void);
14
4b77700a 15void aof_background_fsync(int fd) {
9a35eb22 16 bioCreateBackgroundJob(REDIS_BIO_AOF_FSYNC,(void*)(long)fd,NULL,NULL);
4b77700a 17}
18
e2641e09 19/* Called when the user switches from "appendonly yes" to "appendonly no"
20 * at runtime using the CONFIG command. */
21void stopAppendOnly(void) {
e394114d 22 redisAssert(server.aof_state != REDIS_AOF_OFF);
db3c2a4f 23 flushAppendOnlyFile(1);
ff2145ad 24 aof_fsync(server.aof_fd);
25 close(server.aof_fd);
e2641e09 26
ff2145ad 27 server.aof_fd = -1;
28 server.aof_selected_db = -1;
e394114d 29 server.aof_state = REDIS_AOF_OFF;
e2641e09 30 /* rewrite operation in progress? kill it, wait child exit */
ff2145ad 31 if (server.aof_child_pid != -1) {
e2641e09 32 int statloc;
33
b941417c 34 redisLog(REDIS_NOTICE,"Killing running AOF rewrite child: %ld",
35 (long) server.aof_child_pid);
ff2145ad 36 if (kill(server.aof_child_pid,SIGKILL) != -1)
e2641e09 37 wait3(&statloc,0,NULL);
38 /* reset the buffer accumulating changes while the child saves */
ff2145ad 39 sdsfree(server.aof_rewrite_buf);
40 server.aof_rewrite_buf = sdsempty();
41 aofRemoveTempFile(server.aof_child_pid);
42 server.aof_child_pid = -1;
e2641e09 43 }
44}
45
46/* Called when the user switches from "appendonly no" to "appendonly yes"
47 * at runtime using the CONFIG command. */
48int startAppendOnly(void) {
56ff70f8 49 server.aof_last_fsync = server.unixtime;
ff2145ad 50 server.aof_fd = open(server.aof_filename,O_WRONLY|O_APPEND|O_CREAT,0644);
e394114d 51 redisAssert(server.aof_state == REDIS_AOF_OFF);
ff2145ad 52 if (server.aof_fd == -1) {
e7a2e7c1 53 redisLog(REDIS_WARNING,"Redis needs to enable the AOF but can't open the append only file: %s",strerror(errno));
e2641e09 54 return REDIS_ERR;
55 }
56 if (rewriteAppendOnlyFileBackground() == REDIS_ERR) {
ff2145ad 57 close(server.aof_fd);
e7a2e7c1 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.");
e2641e09 59 return REDIS_ERR;
60 }
e7a2e7c1 61 /* We correctly switched on AOF, now wait for the rerwite to be complete
62 * in order to append data on disk. */
e394114d 63 server.aof_state = REDIS_AOF_WAIT_REWRITE;
e2641e09 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
db3c2a4f 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. */
85void flushAppendOnlyFile(int force) {
e2641e09 86 ssize_t nwritten;
db3c2a4f 87 int sync_in_progress = 0;
e2641e09 88
ff2145ad 89 if (sdslen(server.aof_buf) == 0) return;
e2641e09 90
2c915bcf 91 if (server.aof_fsync == AOF_FSYNC_EVERYSEC)
db3c2a4f 92 sync_in_progress = bioPendingJobsOfType(REDIS_BIO_AOF_FSYNC) != 0;
93
2c915bcf 94 if (server.aof_fsync == AOF_FSYNC_EVERYSEC && !force) {
db3c2a4f 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) {
e7aec180 105 /* We were already waiting for fsync to finish, but for less
db3c2a4f 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. */
81f32c7b 111 server.aof_delayed_fsync++;
77ca5fcb 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.");
db3c2a4f 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
e2641e09 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 */
ff2145ad 124 nwritten = write(server.aof_fd,server.aof_buf,sdslen(server.aof_buf));
125 if (nwritten != (signed)sdslen(server.aof_buf)) {
e2641e09 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. */
a57225c2 129 if (nwritten == -1) {
e2641e09 130 redisLog(REDIS_WARNING,"Exiting on error writing to the append-only file: %s",strerror(errno));
a57225c2 131 } else {
e51b79f3 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));
a57225c2
PN
138 }
139 exit(1);
e2641e09 140 }
2c915bcf 141 server.aof_current_size += nwritten;
e2641e09 142
f990782f
PN
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). */
ff2145ad 145 if ((sdslen(server.aof_buf)+sdsavail(server.aof_buf)) < 4000) {
146 sdsclear(server.aof_buf);
f990782f 147 } else {
ff2145ad 148 sdsfree(server.aof_buf);
149 server.aof_buf = sdsempty();
f990782f
PN
150 }
151
29732248
PN
152 /* Don't fsync if no-appendfsync-on-rewrite is set to yes and there are
153 * children doing I/O in the background. */
2c915bcf 154 if (server.aof_no_fsync_on_rewrite &&
f48cd4b9 155 (server.aof_child_pid != -1 || server.rdb_child_pid != -1))
e2641e09 156 return;
29732248
PN
157
158 /* Perform the fsync if needed. */
2c915bcf 159 if (server.aof_fsync == AOF_FSYNC_ALWAYS) {
e2641e09 160 /* aof_fsync is defined as fdatasync() for Linux in order to avoid
161 * flushing metadata. */
ff2145ad 162 aof_fsync(server.aof_fd); /* Let's try to get this data on the disk */
163 server.aof_last_fsync = server.unixtime;
2c915bcf 164 } else if ((server.aof_fsync == AOF_FSYNC_EVERYSEC &&
ff2145ad 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;
e2641e09 168 }
169}
170
d1ec6c8b
PN
171sds 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
e2641e09 182 for (j = 0; j < argc; j++) {
d1ec6c8b
PN
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);
e2641e09 191 decrRefCount(o);
192 }
d1ec6c8b 193 return dst;
e2641e09 194}
195
12d293ca 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. */
203sds catAppendOnlyExpireAtCommand(sds buf, struct redisCommand *cmd, robj *key, robj *seconds) {
204 long long when;
e2641e09 205 robj *argv[3];
206
207 /* Make sure we can use strtol */
208 seconds = getDecodedObject(seconds);
12d293ca 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 }
e2641e09 222 decrRefCount(seconds);
223
12d293ca 224 argv[0] = createStringObject("PEXPIREAT",9);
e2641e09 225 argv[1] = key;
12d293ca 226 argv[2] = createStringObjectFromLongLong(when);
227 buf = catAppendOnlyGenericCommand(buf, 3, argv);
e2641e09 228 decrRefCount(argv[0]);
229 decrRefCount(argv[2]);
230 return buf;
231}
232
233void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) {
087f4140 234 sds buf = sdsempty();
e2641e09 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. */
ff2145ad 239 if (dictid != server.aof_selected_db) {
e2641e09 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);
ff2145ad 245 server.aof_selected_db = dictid;
e2641e09 246 }
247
12d293ca 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 */
e2641e09 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]);
12d293ca 259 buf = catAppendOnlyExpireAtCommand(buf,cmd,argv[1],argv[2]);
e2641e09 260 } else {
12d293ca 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. */
e2641e09 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
e394114d 269 * positive reply about the operation performed. */
270 if (server.aof_state == REDIS_AOF_ON)
ff2145ad 271 server.aof_buf = sdscatlen(server.aof_buf,buf,sdslen(buf));
e2641e09 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. */
ff2145ad 277 if (server.aof_child_pid != -1)
278 server.aof_rewrite_buf = sdscatlen(server.aof_rewrite_buf,buf,sdslen(buf));
e2641e09 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. */
285struct redisClient *createFakeClient(void) {
286 struct redisClient *c = zmalloc(sizeof(*c));
287
288 selectDb(c,0);
289 c->fd = -1;
290 c->querybuf = sdsempty();
9fa9ccb0 291 c->querybuf_peak = 0;
e2641e09 292 c->argc = 0;
293 c->argv = NULL;
2403fc9f 294 c->bufpos = 0;
e2641e09 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();
3853c168 300 c->reply_bytes = 0;
7eac2a75 301 c->obuf_soft_limit_reached_time = 0;
b67d2345 302 c->watched_keys = listCreate();
e2641e09 303 listSetFreeMethod(c->reply,decrRefCount);
304 listSetDupMethod(c->reply,dupClientReplyValue);
305 initClientMultiState(c);
306 return c;
307}
308
309void freeFakeClient(struct redisClient *c) {
310 sdsfree(c->querybuf);
311 listRelease(c->reply);
b67d2345 312 listRelease(c->watched_keys);
e2641e09 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. */
320int loadAppendOnlyFile(char *filename) {
321 struct redisClient *fakeClient;
322 FILE *fp = fopen(filename,"r");
323 struct redis_stat sb;
e394114d 324 int old_aof_state = server.aof_state;
97e7f8ae 325 long loops = 0;
e2641e09 326
4aec2ec8 327 if (fp && redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0) {
2c915bcf 328 server.aof_current_size = 0;
4aec2ec8 329 fclose(fp);
e2641e09 330 return REDIS_ERR;
4aec2ec8 331 }
e2641e09 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. */
e394114d 340 server.aof_state = REDIS_AOF_OFF;
e2641e09 341
342 fakeClient = createFakeClient();
97e7f8ae 343 startLoading(fp);
344
e2641e09 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;
e2641e09 352
97e7f8ae 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
e2641e09 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);
be6f6395
KM
367 if (argc < 1) goto fmterr;
368
e2641e09 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 }
e2641e09 386 /* Run the command in the context of a fake client */
387 fakeClient->argc = argc;
388 fakeClient->argv = argv;
389 cmd->proc(fakeClient);
57b07380
PN
390
391 /* The fake client should not have a reply */
392 redisAssert(fakeClient->bufpos == 0 && listLength(fakeClient->reply) == 0);
ef67a2fc 393 /* The fake client should never get blocked */
394 redisAssert((fakeClient->flags & REDIS_BLOCKED) == 0);
57b07380 395
45b0f6fb
PN
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);
e2641e09 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);
e394114d 409 server.aof_state = old_aof_state;
97e7f8ae 410 stopLoading();
b333e239 411 aofUpdateCurrentSize();
2c915bcf 412 server.aof_rewrite_base_size = server.aof_current_size;
e2641e09 413 return REDIS_OK;
414
415readerr:
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);
422fmterr:
412e457c 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>");
e2641e09 424 exit(1);
425}
426
7271198c
PN
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. */
429int 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
5b250096 441/* Emit the commands needed to rebuild a list object.
442 * The function returns 0 on error, 1 on success. */
443int 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) {
2c915bcf 455 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
456 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
8d875ccb 457
5b250096 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);
2c915bcf 468 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
5b250096 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
38c06fa0 480 if (count == 0) {
2c915bcf 481 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
482 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
8d875ccb 483
38c06fa0 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 }
5b250096 488 if (rioWriteBulkObject(r,eleobj) == 0) return 0;
2c915bcf 489 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
38c06fa0 490 items--;
5b250096 491 }
492 } else {
493 redisPanic("Unknown list encoding");
494 }
495 return 1;
496}
497
8d875ccb 498/* Emit the commands needed to rebuild a set object.
499 * The function returns 0 on error, 1 on success. */
500int 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) {
2c915bcf 509 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
510 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
8d875ccb 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;
2c915bcf 517 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
8d875ccb 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) {
2c915bcf 527 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
528 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
8d875ccb 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;
2c915bcf 535 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
8d875ccb 536 items--;
537 }
538 dictReleaseIterator(di);
539 } else {
540 redisPanic("Unknown set encoding");
541 }
542 return 1;
543}
544
7df9b141 545/* Emit the commands needed to rebuild a sorted set object.
546 * The function returns 0 on error, 1 on success. */
547int 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) {
2c915bcf 568 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
569 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
7df9b141 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);
2c915bcf 582 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
7df9b141 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) {
2c915bcf 595 int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
596 REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
7df9b141 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;
2c915bcf 604 if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
7df9b141 605 items--;
606 }
607 dictReleaseIterator(di);
608 } else {
609 redisPanic("Unknown sorted zset encoding");
610 }
611 return 1;
612}
613
addc0327 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. */
ebd85e9a
PN
620static 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
54ecc0e7 644/* Emit the commands needed to rebuild a hash object.
645 * The function returns 0 on error, 1 on success. */
646int rewriteHashObject(rio *r, robj *key, robj *o) {
ebd85e9a 647 hashTypeIterator *hi;
54ecc0e7 648 long long count = 0, items = hashTypeLength(o);
649
ebd85e9a
PN
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;
54ecc0e7 655
ebd85e9a
PN
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;
54ecc0e7 659 }
54ecc0e7 660
ebd85e9a
PN
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 }
54ecc0e7 666
ebd85e9a 667 hashTypeReleaseIterator(hi);
54ecc0e7 668
54ecc0e7 669 return 1;
670}
671
e2641e09 672/* Write a sequence of commands able to fully rebuild the dataset into
5b250096 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
2c915bcf 677 * and ZADD. However at max REDIS_AOF_REWRITE_ITEMS_PER_CMD items per time
5b250096 678 * are inserted using a single command. */
e2641e09 679int rewriteAppendOnlyFile(char *filename) {
680 dictIterator *di = NULL;
681 dictEntry *de;
7271198c 682 rio aof;
e2641e09 683 FILE *fp;
684 char tmpfile[256];
685 int j;
4be855e7 686 long long now = mstime();
e2641e09 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) {
e51b79f3 693 redisLog(REDIS_WARNING, "Opening the temp file for AOF rewrite in rewriteAppendOnlyFile(): %s", strerror(errno));
e2641e09 694 return REDIS_ERR;
695 }
7271198c 696
f96a8a80 697 rioInitWithFile(&aof,fp);
e2641e09 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;
591f29e0 703 di = dictGetSafeIterator(d);
e2641e09 704 if (!di) {
705 fclose(fp);
706 return REDIS_ERR;
707 }
708
709 /* SELECT the new DB */
7271198c
PN
710 if (rioWrite(&aof,selectcmd,sizeof(selectcmd)-1) == 0) goto werr;
711 if (rioWriteBulkLongLong(&aof,j) == 0) goto werr;
e2641e09 712
713 /* Iterate this DB writing every entry */
714 while((de = dictNext(di)) != NULL) {
6901fe77 715 sds keystr;
e2641e09 716 robj key, *o;
4be855e7 717 long long expiretime;
e2641e09 718
c0ba9ebe 719 keystr = dictGetKey(de);
720 o = dictGetVal(de);
e2641e09 721 initStaticStringObject(key,keystr);
16d77878 722
e2641e09 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";
7271198c 729 if (rioWrite(&aof,cmd,sizeof(cmd)-1) == 0) goto werr;
e2641e09 730 /* Key and value */
7271198c
PN
731 if (rioWriteBulkObject(&aof,&key) == 0) goto werr;
732 if (rioWriteBulkObject(&aof,o) == 0) goto werr;
e2641e09 733 } else if (o->type == REDIS_LIST) {
5b250096 734 if (rewriteListObject(&aof,&key,o) == 0) goto werr;
e2641e09 735 } else if (o->type == REDIS_SET) {
8d875ccb 736 if (rewriteSetObject(&aof,&key,o) == 0) goto werr;
e2641e09 737 } else if (o->type == REDIS_ZSET) {
7df9b141 738 if (rewriteSortedSetObject(&aof,&key,o) == 0) goto werr;
e2641e09 739 } else if (o->type == REDIS_HASH) {
54ecc0e7 740 if (rewriteHashObject(&aof,&key,o) == 0) goto werr;
e2641e09 741 } else {
742 redisPanic("Unknown object type");
743 }
744 /* Save the expire time */
745 if (expiretime != -1) {
12d293ca 746 char cmd[]="*3\r\n$9\r\nPEXPIREAT\r\n";
e2641e09 747 /* If this key is already expired skip it */
748 if (expiretime < now) continue;
7271198c
PN
749 if (rioWrite(&aof,cmd,sizeof(cmd)-1) == 0) goto werr;
750 if (rioWriteBulkObject(&aof,&key) == 0) goto werr;
b0b74486 751 if (rioWriteBulkLongLong(&aof,expiretime) == 0) goto werr;
e2641e09 752 }
e2641e09 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
772werr:
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.
ff2145ad 785 * 2b) the parent accumulates differences in server.aof_rewrite_buf.
e2641e09 786 * 3) When the child finished '2a' exists.
787 * 4) The parent will trap the exit code, if it's OK, will append the
ff2145ad 788 * data accumulated into server.aof_rewrite_buf into the temp file, and
e2641e09 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 */
792int rewriteAppendOnlyFileBackground(void) {
793 pid_t childpid;
615e414c 794 long long start;
e2641e09 795
ff2145ad 796 if (server.aof_child_pid != -1) return REDIS_ERR;
615e414c 797 start = ustime();
e2641e09 798 if ((childpid = fork()) == 0) {
e2641e09 799 char tmpfile[256];
800
615e414c 801 /* Child */
a5639e7d
PN
802 if (server.ipfd > 0) close(server.ipfd);
803 if (server.sofd > 0) close(server.sofd);
e2641e09 804 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
805 if (rewriteAppendOnlyFile(tmpfile) == REDIS_OK) {
55951f90 806 exitFromChild(0);
e2641e09 807 } else {
55951f90 808 exitFromChild(1);
e2641e09 809 }
810 } else {
811 /* Parent */
615e414c 812 server.stat_fork_time = ustime()-start;
e2641e09 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);
2c915bcf 821 server.aof_rewrite_scheduled = 0;
ff2145ad 822 server.aof_child_pid = childpid;
e2641e09 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
ff2145ad 826 * accumulated by the parent into server.aof_rewrite_buf will start
e2641e09 827 * with a SELECT statement and it will be safe to merge. */
ff2145ad 828 server.aof_selected_db = -1;
e2641e09 829 return REDIS_OK;
830 }
831 return REDIS_OK; /* unreached */
832}
833
834void bgrewriteaofCommand(redisClient *c) {
ff2145ad 835 if (server.aof_child_pid != -1) {
3ab20376 836 addReplyError(c,"Background append only file rewriting already in progress");
f48cd4b9 837 } else if (server.rdb_child_pid != -1) {
2c915bcf 838 server.aof_rewrite_scheduled = 1;
9e40bce3 839 addReplyStatus(c,"Background append only file rewriting scheduled");
b333e239 840 } else if (rewriteAppendOnlyFileBackground() == REDIS_OK) {
3ab20376 841 addReplyStatus(c,"Background append only file rewriting started");
e2641e09 842 } else {
843 addReply(c,shared.err);
844 }
845}
846
847void 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
2c915bcf 854/* Update the server.aof_current_size filed explicitly using stat(2)
b333e239 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
2f0f0d95 857 * to the current length, that is much faster. */
b333e239 858void aofUpdateCurrentSize(void) {
859 struct redis_stat sb;
860
ff2145ad 861 if (redis_fstat(server.aof_fd,&sb) == -1) {
e51b79f3 862 redisLog(REDIS_WARNING,"Unable to obtain the AOF file length. stat: %s",
b333e239 863 strerror(errno));
864 } else {
2c915bcf 865 server.aof_current_size = sb.st_size;
b333e239 866 }
867}
868
e2641e09 869/* A background append only file rewriting (BGREWRITEAOF) terminated its work.
870 * Handle this. */
36c17a53 871void backgroundRewriteDoneHandler(int exitcode, int bysignal) {
e2641e09 872 if (!bysignal && exitcode == 0) {
b454056d
PN
873 int newfd, oldfd;
874 int nwritten;
e2641e09 875 char tmpfile[256];
b454056d 876 long long now = ustime();
e2641e09 877
878 redisLog(REDIS_NOTICE,
b454056d
PN
879 "Background AOF rewrite terminated with success");
880
986630af 881 /* Flush the differences accumulated by the parent to the
882 * rewritten AOF. */
883 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof",
ff2145ad 884 (int)server.aof_child_pid);
b454056d
PN
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));
e2641e09 889 goto cleanup;
890 }
b454056d 891
ff2145ad 892 nwritten = write(newfd,server.aof_rewrite_buf,sdslen(server.aof_rewrite_buf));
893 if (nwritten != (signed)sdslen(server.aof_rewrite_buf)) {
b454056d
PN
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);
e2641e09 902 goto cleanup;
903 }
b454056d
PN
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
986630af 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:
b454056d
PN
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
986630af 928 * use a background thread to take care of this. First, we
b454056d
PN
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. */
ff2145ad 935 if (server.aof_fd == -1) {
b454056d 936 /* AOF disabled */
b454056d 937
986630af 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. */
2c915bcf 941 oldfd = open(server.aof_filename,O_RDONLY|O_NONBLOCK);
b454056d
PN
942 } else {
943 /* AOF enabled */
986630af 944 oldfd = -1; /* We'll set this to the current AOF filedes later. */
b454056d
PN
945 }
946
947 /* Rename the temporary file. This will not unlink the target file if
948 * it exists, because we reference it with "oldfd". */
2c915bcf 949 if (rename(tmpfile,server.aof_filename) == -1) {
b454056d 950 redisLog(REDIS_WARNING,
e51b79f3 951 "Error trying to rename the temporary AOF file: %s", strerror(errno));
b454056d 952 close(newfd);
986630af 953 if (oldfd != -1) close(oldfd);
e2641e09 954 goto cleanup;
955 }
b454056d 956
ff2145ad 957 if (server.aof_fd == -1) {
986630af 958 /* AOF disabled, we don't need to set the AOF file descriptor
959 * to this new file, so we can close it. */
b454056d
PN
960 close(newfd);
961 } else {
986630af 962 /* AOF enabled, replace the old fd with the new one. */
ff2145ad 963 oldfd = server.aof_fd;
964 server.aof_fd = newfd;
2c915bcf 965 if (server.aof_fsync == AOF_FSYNC_ALWAYS)
4b77700a 966 aof_fsync(newfd);
2c915bcf 967 else if (server.aof_fsync == AOF_FSYNC_EVERYSEC)
4b77700a 968 aof_background_fsync(newfd);
ff2145ad 969 server.aof_selected_db = -1; /* Make sure SELECT is re-issued */
b333e239 970 aofUpdateCurrentSize();
2c915bcf 971 server.aof_rewrite_base_size = server.aof_current_size;
5f54a5e6
PN
972
973 /* Clear regular AOF buffer since its contents was just written to
974 * the new AOF from the background rewrite buffer. */
ff2145ad 975 sdsfree(server.aof_buf);
976 server.aof_buf = sdsempty();
e2641e09 977 }
b454056d 978
e51b79f3 979 redisLog(REDIS_NOTICE, "Background AOF rewrite finished successfully");
e394114d 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;
b454056d
PN
983
984 /* Asynchronously close the overwritten AOF. */
50be9b97 985 if (oldfd != -1) bioCreateBackgroundJob(REDIS_BIO_CLOSE_FILE,(void*)(long)oldfd,NULL,NULL);
b454056d
PN
986
987 redisLog(REDIS_VERBOSE,
988 "Background AOF rewrite signal handler took %lldus", ustime()-now);
e2641e09 989 } else if (!bysignal && exitcode != 0) {
b454056d
PN
990 redisLog(REDIS_WARNING,
991 "Background AOF rewrite terminated with error");
e2641e09 992 } else {
993 redisLog(REDIS_WARNING,
b454056d 994 "Background AOF rewrite terminated by signal %d", bysignal);
e2641e09 995 }
b454056d 996
e2641e09 997cleanup:
ff2145ad 998 sdsfree(server.aof_rewrite_buf);
999 server.aof_rewrite_buf = sdsempty();
1000 aofRemoveTempFile(server.aof_child_pid);
1001 server.aof_child_pid = -1;
e394114d 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)
2c915bcf 1004 server.aof_rewrite_scheduled = 1;
e2641e09 1005}