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