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