]>
Commit | Line | Data |
---|---|---|
e2641e09 | 1 | #include "redis.h" |
2 | ||
3 | #include <signal.h> | |
4 | #include <fcntl.h> | |
5 | #include <sys/stat.h> | |
3688d7f3 | 6 | #include <sys/types.h> |
7 | #include <sys/time.h> | |
8 | #include <sys/resource.h> | |
9 | #include <sys/wait.h> | |
e2641e09 | 10 | |
11 | /* Called when the user switches from "appendonly yes" to "appendonly no" | |
12 | * at runtime using the CONFIG command. */ | |
13 | void stopAppendOnly(void) { | |
14 | flushAppendOnlyFile(); | |
15 | aof_fsync(server.appendfd); | |
16 | close(server.appendfd); | |
17 | ||
18 | server.appendfd = -1; | |
19 | server.appendseldb = -1; | |
20 | server.appendonly = 0; | |
21 | /* rewrite operation in progress? kill it, wait child exit */ | |
22 | if (server.bgsavechildpid != -1) { | |
23 | int statloc; | |
24 | ||
25 | if (kill(server.bgsavechildpid,SIGKILL) != -1) | |
26 | wait3(&statloc,0,NULL); | |
27 | /* reset the buffer accumulating changes while the child saves */ | |
28 | sdsfree(server.bgrewritebuf); | |
29 | server.bgrewritebuf = sdsempty(); | |
30 | server.bgsavechildpid = -1; | |
31 | } | |
32 | } | |
33 | ||
34 | /* Called when the user switches from "appendonly no" to "appendonly yes" | |
35 | * at runtime using the CONFIG command. */ | |
36 | int startAppendOnly(void) { | |
37 | server.appendonly = 1; | |
38 | server.lastfsync = time(NULL); | |
39 | server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644); | |
40 | if (server.appendfd == -1) { | |
41 | redisLog(REDIS_WARNING,"Used tried to switch on AOF via CONFIG, but I can't open the AOF file: %s",strerror(errno)); | |
42 | return REDIS_ERR; | |
43 | } | |
44 | if (rewriteAppendOnlyFileBackground() == REDIS_ERR) { | |
45 | server.appendonly = 0; | |
46 | close(server.appendfd); | |
47 | redisLog(REDIS_WARNING,"Used tried to switch on AOF via CONFIG, I can't trigger a background AOF rewrite operation. Check the above logs for more info about the error.",strerror(errno)); | |
48 | return REDIS_ERR; | |
49 | } | |
50 | return REDIS_OK; | |
51 | } | |
52 | ||
53 | /* Write the append only file buffer on disk. | |
54 | * | |
55 | * Since we are required to write the AOF before replying to the client, | |
56 | * and the only way the client socket can get a write is entering when the | |
57 | * the event loop, we accumulate all the AOF writes in a memory | |
58 | * buffer and write it on disk using this function just before entering | |
59 | * the event loop again. */ | |
60 | void flushAppendOnlyFile(void) { | |
61 | time_t now; | |
62 | ssize_t nwritten; | |
63 | ||
64 | if (sdslen(server.aofbuf) == 0) return; | |
65 | ||
66 | /* We want to perform a single write. This should be guaranteed atomic | |
67 | * at least if the filesystem we are writing is a real physical one. | |
68 | * While this will save us against the server being killed I don't think | |
69 | * there is much to do about the whole server stopping for power problems | |
70 | * or alike */ | |
71 | nwritten = write(server.appendfd,server.aofbuf,sdslen(server.aofbuf)); | |
72 | if (nwritten != (signed)sdslen(server.aofbuf)) { | |
73 | /* Ooops, we are in troubles. The best thing to do for now is | |
74 | * aborting instead of giving the illusion that everything is | |
75 | * working as expected. */ | |
76 | if (nwritten == -1) { | |
77 | redisLog(REDIS_WARNING,"Exiting on error writing to the append-only file: %s",strerror(errno)); | |
78 | } else { | |
79 | redisLog(REDIS_WARNING,"Exiting on short write while writing to the append-only file: %s",strerror(errno)); | |
80 | } | |
81 | exit(1); | |
82 | } | |
83 | sdsfree(server.aofbuf); | |
84 | server.aofbuf = sdsempty(); | |
85 | ||
86 | /* Don't Fsync if no-appendfsync-on-rewrite is set to yes and we have | |
87 | * childs performing heavy I/O on disk. */ | |
88 | if (server.no_appendfsync_on_rewrite && | |
89 | (server.bgrewritechildpid != -1 || server.bgsavechildpid != -1)) | |
90 | return; | |
91 | /* Fsync if needed */ | |
92 | now = time(NULL); | |
93 | if (server.appendfsync == APPENDFSYNC_ALWAYS || | |
94 | (server.appendfsync == APPENDFSYNC_EVERYSEC && | |
95 | now-server.lastfsync > 1)) | |
96 | { | |
97 | /* aof_fsync is defined as fdatasync() for Linux in order to avoid | |
98 | * flushing metadata. */ | |
99 | aof_fsync(server.appendfd); /* Let's try to get this data on the disk */ | |
100 | server.lastfsync = now; | |
101 | } | |
102 | } | |
103 | ||
104 | sds catAppendOnlyGenericCommand(sds buf, int argc, robj **argv) { | |
105 | int j; | |
106 | buf = sdscatprintf(buf,"*%d\r\n",argc); | |
107 | for (j = 0; j < argc; j++) { | |
108 | robj *o = getDecodedObject(argv[j]); | |
109 | buf = sdscatprintf(buf,"$%lu\r\n",(unsigned long)sdslen(o->ptr)); | |
110 | buf = sdscatlen(buf,o->ptr,sdslen(o->ptr)); | |
111 | buf = sdscatlen(buf,"\r\n",2); | |
112 | decrRefCount(o); | |
113 | } | |
114 | return buf; | |
115 | } | |
116 | ||
117 | sds catAppendOnlyExpireAtCommand(sds buf, robj *key, robj *seconds) { | |
118 | int argc = 3; | |
119 | long when; | |
120 | robj *argv[3]; | |
121 | ||
122 | /* Make sure we can use strtol */ | |
123 | seconds = getDecodedObject(seconds); | |
124 | when = time(NULL)+strtol(seconds->ptr,NULL,10); | |
125 | decrRefCount(seconds); | |
126 | ||
127 | argv[0] = createStringObject("EXPIREAT",8); | |
128 | argv[1] = key; | |
129 | argv[2] = createObject(REDIS_STRING, | |
130 | sdscatprintf(sdsempty(),"%ld",when)); | |
131 | buf = catAppendOnlyGenericCommand(buf, argc, argv); | |
132 | decrRefCount(argv[0]); | |
133 | decrRefCount(argv[2]); | |
134 | return buf; | |
135 | } | |
136 | ||
137 | void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) { | |
138 | sds buf = sdsempty(); | |
139 | robj *tmpargv[3]; | |
140 | ||
141 | /* The DB this command was targetting is not the same as the last command | |
142 | * we appendend. To issue a SELECT command is needed. */ | |
143 | if (dictid != server.appendseldb) { | |
144 | char seldb[64]; | |
145 | ||
146 | snprintf(seldb,sizeof(seldb),"%d",dictid); | |
147 | buf = sdscatprintf(buf,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n", | |
148 | (unsigned long)strlen(seldb),seldb); | |
149 | server.appendseldb = dictid; | |
150 | } | |
151 | ||
152 | if (cmd->proc == expireCommand) { | |
153 | /* Translate EXPIRE into EXPIREAT */ | |
154 | buf = catAppendOnlyExpireAtCommand(buf,argv[1],argv[2]); | |
155 | } else if (cmd->proc == setexCommand) { | |
156 | /* Translate SETEX to SET and EXPIREAT */ | |
157 | tmpargv[0] = createStringObject("SET",3); | |
158 | tmpargv[1] = argv[1]; | |
159 | tmpargv[2] = argv[3]; | |
160 | buf = catAppendOnlyGenericCommand(buf,3,tmpargv); | |
161 | decrRefCount(tmpargv[0]); | |
162 | buf = catAppendOnlyExpireAtCommand(buf,argv[1],argv[2]); | |
163 | } else { | |
164 | buf = catAppendOnlyGenericCommand(buf,argc,argv); | |
165 | } | |
166 | ||
167 | /* Append to the AOF buffer. This will be flushed on disk just before | |
168 | * of re-entering the event loop, so before the client will get a | |
169 | * positive reply about the operation performed. */ | |
170 | server.aofbuf = sdscatlen(server.aofbuf,buf,sdslen(buf)); | |
171 | ||
172 | /* If a background append only file rewriting is in progress we want to | |
173 | * accumulate the differences between the child DB and the current one | |
174 | * in a buffer, so that when the child process will do its work we | |
175 | * can append the differences to the new append only file. */ | |
176 | if (server.bgrewritechildpid != -1) | |
177 | server.bgrewritebuf = sdscatlen(server.bgrewritebuf,buf,sdslen(buf)); | |
178 | ||
179 | sdsfree(buf); | |
180 | } | |
181 | ||
182 | /* In Redis commands are always executed in the context of a client, so in | |
183 | * order to load the append only file we need to create a fake client. */ | |
184 | struct redisClient *createFakeClient(void) { | |
185 | struct redisClient *c = zmalloc(sizeof(*c)); | |
186 | ||
187 | selectDb(c,0); | |
188 | c->fd = -1; | |
189 | c->querybuf = sdsempty(); | |
190 | c->argc = 0; | |
191 | c->argv = NULL; | |
192 | c->flags = 0; | |
193 | /* We set the fake client as a slave waiting for the synchronization | |
194 | * so that Redis will not try to send replies to this client. */ | |
195 | c->replstate = REDIS_REPL_WAIT_BGSAVE_START; | |
196 | c->reply = listCreate(); | |
197 | listSetFreeMethod(c->reply,decrRefCount); | |
198 | listSetDupMethod(c->reply,dupClientReplyValue); | |
199 | initClientMultiState(c); | |
200 | return c; | |
201 | } | |
202 | ||
203 | void freeFakeClient(struct redisClient *c) { | |
204 | sdsfree(c->querybuf); | |
205 | listRelease(c->reply); | |
206 | freeClientMultiState(c); | |
207 | zfree(c); | |
208 | } | |
209 | ||
210 | /* Replay the append log file. On error REDIS_OK is returned. On non fatal | |
211 | * error (the append only file is zero-length) REDIS_ERR is returned. On | |
212 | * fatal error an error message is logged and the program exists. */ | |
213 | int loadAppendOnlyFile(char *filename) { | |
214 | struct redisClient *fakeClient; | |
215 | FILE *fp = fopen(filename,"r"); | |
216 | struct redis_stat sb; | |
217 | int appendonly = server.appendonly; | |
218 | ||
219 | if (redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0) | |
220 | return REDIS_ERR; | |
221 | ||
222 | if (fp == NULL) { | |
223 | redisLog(REDIS_WARNING,"Fatal error: can't open the append log file for reading: %s",strerror(errno)); | |
224 | exit(1); | |
225 | } | |
226 | ||
227 | /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI | |
228 | * to the same file we're about to read. */ | |
229 | server.appendonly = 0; | |
230 | ||
231 | fakeClient = createFakeClient(); | |
232 | while(1) { | |
233 | int argc, j; | |
234 | unsigned long len; | |
235 | robj **argv; | |
236 | char buf[128]; | |
237 | sds argsds; | |
238 | struct redisCommand *cmd; | |
239 | int force_swapout; | |
240 | ||
241 | if (fgets(buf,sizeof(buf),fp) == NULL) { | |
242 | if (feof(fp)) | |
243 | break; | |
244 | else | |
245 | goto readerr; | |
246 | } | |
247 | if (buf[0] != '*') goto fmterr; | |
248 | argc = atoi(buf+1); | |
249 | argv = zmalloc(sizeof(robj*)*argc); | |
250 | for (j = 0; j < argc; j++) { | |
251 | if (fgets(buf,sizeof(buf),fp) == NULL) goto readerr; | |
252 | if (buf[0] != '$') goto fmterr; | |
253 | len = strtol(buf+1,NULL,10); | |
254 | argsds = sdsnewlen(NULL,len); | |
255 | if (len && fread(argsds,len,1,fp) == 0) goto fmterr; | |
256 | argv[j] = createObject(REDIS_STRING,argsds); | |
257 | if (fread(buf,2,1,fp) == 0) goto fmterr; /* discard CRLF */ | |
258 | } | |
259 | ||
260 | /* Command lookup */ | |
261 | cmd = lookupCommand(argv[0]->ptr); | |
262 | if (!cmd) { | |
263 | redisLog(REDIS_WARNING,"Unknown command '%s' reading the append only file", argv[0]->ptr); | |
264 | exit(1); | |
265 | } | |
266 | /* Try object encoding */ | |
267 | if (cmd->flags & REDIS_CMD_BULK) | |
268 | argv[argc-1] = tryObjectEncoding(argv[argc-1]); | |
269 | /* Run the command in the context of a fake client */ | |
270 | fakeClient->argc = argc; | |
271 | fakeClient->argv = argv; | |
272 | cmd->proc(fakeClient); | |
273 | /* Discard the reply objects list from the fake client */ | |
274 | while(listLength(fakeClient->reply)) | |
275 | listDelNode(fakeClient->reply,listFirst(fakeClient->reply)); | |
276 | /* Clean up, ready for the next command */ | |
277 | for (j = 0; j < argc; j++) decrRefCount(argv[j]); | |
278 | zfree(argv); | |
279 | /* Handle swapping while loading big datasets when VM is on */ | |
280 | force_swapout = 0; | |
281 | if ((zmalloc_used_memory() - server.vm_max_memory) > 1024*1024*32) | |
282 | force_swapout = 1; | |
283 | ||
284 | if (server.vm_enabled && force_swapout) { | |
285 | while (zmalloc_used_memory() > server.vm_max_memory) { | |
286 | if (vmSwapOneObjectBlocking() == REDIS_ERR) break; | |
287 | } | |
288 | } | |
289 | } | |
290 | ||
291 | /* This point can only be reached when EOF is reached without errors. | |
292 | * If the client is in the middle of a MULTI/EXEC, log error and quit. */ | |
293 | if (fakeClient->flags & REDIS_MULTI) goto readerr; | |
294 | ||
295 | fclose(fp); | |
296 | freeFakeClient(fakeClient); | |
297 | server.appendonly = appendonly; | |
298 | return REDIS_OK; | |
299 | ||
300 | readerr: | |
301 | if (feof(fp)) { | |
302 | redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file"); | |
303 | } else { | |
304 | redisLog(REDIS_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno)); | |
305 | } | |
306 | exit(1); | |
307 | fmterr: | |
308 | redisLog(REDIS_WARNING,"Bad file format reading the append only file"); | |
309 | exit(1); | |
310 | } | |
311 | ||
312 | /* Write binary-safe string into a file in the bulkformat | |
313 | * $<count>\r\n<payload>\r\n */ | |
314 | int fwriteBulkString(FILE *fp, char *s, unsigned long len) { | |
315 | char cbuf[128]; | |
316 | int clen; | |
317 | cbuf[0] = '$'; | |
318 | clen = 1+ll2string(cbuf+1,sizeof(cbuf)-1,len); | |
319 | cbuf[clen++] = '\r'; | |
320 | cbuf[clen++] = '\n'; | |
321 | if (fwrite(cbuf,clen,1,fp) == 0) return 0; | |
322 | if (len > 0 && fwrite(s,len,1,fp) == 0) return 0; | |
323 | if (fwrite("\r\n",2,1,fp) == 0) return 0; | |
324 | return 1; | |
325 | } | |
326 | ||
327 | /* Write a double value in bulk format $<count>\r\n<payload>\r\n */ | |
328 | int fwriteBulkDouble(FILE *fp, double d) { | |
329 | char buf[128], dbuf[128]; | |
330 | ||
331 | snprintf(dbuf,sizeof(dbuf),"%.17g\r\n",d); | |
332 | snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(dbuf)-2); | |
333 | if (fwrite(buf,strlen(buf),1,fp) == 0) return 0; | |
334 | if (fwrite(dbuf,strlen(dbuf),1,fp) == 0) return 0; | |
335 | return 1; | |
336 | } | |
337 | ||
338 | /* Write a long value in bulk format $<count>\r\n<payload>\r\n */ | |
339 | int fwriteBulkLongLong(FILE *fp, long long l) { | |
340 | char bbuf[128], lbuf[128]; | |
341 | unsigned int blen, llen; | |
342 | llen = ll2string(lbuf,32,l); | |
343 | blen = snprintf(bbuf,sizeof(bbuf),"$%u\r\n%s\r\n",llen,lbuf); | |
344 | if (fwrite(bbuf,blen,1,fp) == 0) return 0; | |
345 | return 1; | |
346 | } | |
347 | ||
348 | /* Delegate writing an object to writing a bulk string or bulk long long. */ | |
349 | int fwriteBulkObject(FILE *fp, robj *obj) { | |
350 | /* Avoid using getDecodedObject to help copy-on-write (we are often | |
351 | * in a child process when this function is called). */ | |
352 | if (obj->encoding == REDIS_ENCODING_INT) { | |
353 | return fwriteBulkLongLong(fp,(long)obj->ptr); | |
354 | } else if (obj->encoding == REDIS_ENCODING_RAW) { | |
355 | return fwriteBulkString(fp,obj->ptr,sdslen(obj->ptr)); | |
356 | } else { | |
357 | redisPanic("Unknown string encoding"); | |
358 | } | |
359 | } | |
360 | ||
361 | /* Write a sequence of commands able to fully rebuild the dataset into | |
362 | * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */ | |
363 | int rewriteAppendOnlyFile(char *filename) { | |
364 | dictIterator *di = NULL; | |
365 | dictEntry *de; | |
366 | FILE *fp; | |
367 | char tmpfile[256]; | |
368 | int j; | |
369 | time_t now = time(NULL); | |
370 | ||
371 | /* Note that we have to use a different temp name here compared to the | |
372 | * one used by rewriteAppendOnlyFileBackground() function. */ | |
373 | snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid()); | |
374 | fp = fopen(tmpfile,"w"); | |
375 | if (!fp) { | |
376 | redisLog(REDIS_WARNING, "Failed rewriting the append only file: %s", strerror(errno)); | |
377 | return REDIS_ERR; | |
378 | } | |
379 | for (j = 0; j < server.dbnum; j++) { | |
380 | char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n"; | |
381 | redisDb *db = server.db+j; | |
382 | dict *d = db->dict; | |
383 | if (dictSize(d) == 0) continue; | |
384 | di = dictGetIterator(d); | |
385 | if (!di) { | |
386 | fclose(fp); | |
387 | return REDIS_ERR; | |
388 | } | |
389 | ||
390 | /* SELECT the new DB */ | |
391 | if (fwrite(selectcmd,sizeof(selectcmd)-1,1,fp) == 0) goto werr; | |
392 | if (fwriteBulkLongLong(fp,j) == 0) goto werr; | |
393 | ||
394 | /* Iterate this DB writing every entry */ | |
395 | while((de = dictNext(di)) != NULL) { | |
396 | sds keystr = dictGetEntryKey(de); | |
397 | robj key, *o; | |
398 | time_t expiretime; | |
399 | int swapped; | |
400 | ||
401 | keystr = dictGetEntryKey(de); | |
402 | o = dictGetEntryVal(de); | |
403 | initStaticStringObject(key,keystr); | |
404 | /* If the value for this key is swapped, load a preview in memory. | |
405 | * We use a "swapped" flag to remember if we need to free the | |
406 | * value object instead to just increment the ref count anyway | |
407 | * in order to avoid copy-on-write of pages if we are forked() */ | |
408 | if (!server.vm_enabled || o->storage == REDIS_VM_MEMORY || | |
409 | o->storage == REDIS_VM_SWAPPING) { | |
410 | swapped = 0; | |
411 | } else { | |
412 | o = vmPreviewObject(o); | |
413 | swapped = 1; | |
414 | } | |
415 | expiretime = getExpire(db,&key); | |
416 | ||
417 | /* Save the key and associated value */ | |
418 | if (o->type == REDIS_STRING) { | |
419 | /* Emit a SET command */ | |
420 | char cmd[]="*3\r\n$3\r\nSET\r\n"; | |
421 | if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr; | |
422 | /* Key and value */ | |
423 | if (fwriteBulkObject(fp,&key) == 0) goto werr; | |
424 | if (fwriteBulkObject(fp,o) == 0) goto werr; | |
425 | } else if (o->type == REDIS_LIST) { | |
426 | /* Emit the RPUSHes needed to rebuild the list */ | |
427 | char cmd[]="*3\r\n$5\r\nRPUSH\r\n"; | |
428 | if (o->encoding == REDIS_ENCODING_ZIPLIST) { | |
429 | unsigned char *zl = o->ptr; | |
430 | unsigned char *p = ziplistIndex(zl,0); | |
431 | unsigned char *vstr; | |
432 | unsigned int vlen; | |
433 | long long vlong; | |
434 | ||
435 | while(ziplistGet(p,&vstr,&vlen,&vlong)) { | |
436 | if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr; | |
437 | if (fwriteBulkObject(fp,&key) == 0) goto werr; | |
438 | if (vstr) { | |
439 | if (fwriteBulkString(fp,(char*)vstr,vlen) == 0) | |
440 | goto werr; | |
441 | } else { | |
442 | if (fwriteBulkLongLong(fp,vlong) == 0) | |
443 | goto werr; | |
444 | } | |
445 | p = ziplistNext(zl,p); | |
446 | } | |
447 | } else if (o->encoding == REDIS_ENCODING_LINKEDLIST) { | |
448 | list *list = o->ptr; | |
449 | listNode *ln; | |
450 | listIter li; | |
451 | ||
452 | listRewind(list,&li); | |
453 | while((ln = listNext(&li))) { | |
454 | robj *eleobj = listNodeValue(ln); | |
455 | ||
456 | if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr; | |
457 | if (fwriteBulkObject(fp,&key) == 0) goto werr; | |
458 | if (fwriteBulkObject(fp,eleobj) == 0) goto werr; | |
459 | } | |
460 | } else { | |
461 | redisPanic("Unknown list encoding"); | |
462 | } | |
463 | } else if (o->type == REDIS_SET) { | |
464 | /* Emit the SADDs needed to rebuild the set */ | |
465 | dict *set = o->ptr; | |
466 | dictIterator *di = dictGetIterator(set); | |
467 | dictEntry *de; | |
468 | ||
469 | while((de = dictNext(di)) != NULL) { | |
470 | char cmd[]="*3\r\n$4\r\nSADD\r\n"; | |
471 | robj *eleobj = dictGetEntryKey(de); | |
472 | ||
473 | if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr; | |
474 | if (fwriteBulkObject(fp,&key) == 0) goto werr; | |
475 | if (fwriteBulkObject(fp,eleobj) == 0) goto werr; | |
476 | } | |
477 | dictReleaseIterator(di); | |
478 | } else if (o->type == REDIS_ZSET) { | |
479 | /* Emit the ZADDs needed to rebuild the sorted set */ | |
480 | zset *zs = o->ptr; | |
481 | dictIterator *di = dictGetIterator(zs->dict); | |
482 | dictEntry *de; | |
483 | ||
484 | while((de = dictNext(di)) != NULL) { | |
485 | char cmd[]="*4\r\n$4\r\nZADD\r\n"; | |
486 | robj *eleobj = dictGetEntryKey(de); | |
487 | double *score = dictGetEntryVal(de); | |
488 | ||
489 | if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr; | |
490 | if (fwriteBulkObject(fp,&key) == 0) goto werr; | |
491 | if (fwriteBulkDouble(fp,*score) == 0) goto werr; | |
492 | if (fwriteBulkObject(fp,eleobj) == 0) goto werr; | |
493 | } | |
494 | dictReleaseIterator(di); | |
495 | } else if (o->type == REDIS_HASH) { | |
496 | char cmd[]="*4\r\n$4\r\nHSET\r\n"; | |
497 | ||
498 | /* Emit the HSETs needed to rebuild the hash */ | |
499 | if (o->encoding == REDIS_ENCODING_ZIPMAP) { | |
500 | unsigned char *p = zipmapRewind(o->ptr); | |
501 | unsigned char *field, *val; | |
502 | unsigned int flen, vlen; | |
503 | ||
504 | while((p = zipmapNext(p,&field,&flen,&val,&vlen)) != NULL) { | |
505 | if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr; | |
506 | if (fwriteBulkObject(fp,&key) == 0) goto werr; | |
daf2049d | 507 | if (fwriteBulkString(fp,(char*)field,flen) == 0) |
5bd09cd4 | 508 | goto werr; |
daf2049d | 509 | if (fwriteBulkString(fp,(char*)val,vlen) == 0) |
5bd09cd4 | 510 | goto werr; |
e2641e09 | 511 | } |
512 | } else { | |
513 | dictIterator *di = dictGetIterator(o->ptr); | |
514 | dictEntry *de; | |
515 | ||
516 | while((de = dictNext(di)) != NULL) { | |
517 | robj *field = dictGetEntryKey(de); | |
518 | robj *val = dictGetEntryVal(de); | |
519 | ||
520 | if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr; | |
521 | if (fwriteBulkObject(fp,&key) == 0) goto werr; | |
5bd09cd4 | 522 | if (fwriteBulkObject(fp,field) == 0) goto werr; |
523 | if (fwriteBulkObject(fp,val) == 0) goto werr; | |
e2641e09 | 524 | } |
525 | dictReleaseIterator(di); | |
526 | } | |
527 | } else { | |
528 | redisPanic("Unknown object type"); | |
529 | } | |
530 | /* Save the expire time */ | |
531 | if (expiretime != -1) { | |
532 | char cmd[]="*3\r\n$8\r\nEXPIREAT\r\n"; | |
533 | /* If this key is already expired skip it */ | |
534 | if (expiretime < now) continue; | |
535 | if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr; | |
536 | if (fwriteBulkObject(fp,&key) == 0) goto werr; | |
537 | if (fwriteBulkLongLong(fp,expiretime) == 0) goto werr; | |
538 | } | |
539 | if (swapped) decrRefCount(o); | |
540 | } | |
541 | dictReleaseIterator(di); | |
542 | } | |
543 | ||
544 | /* Make sure data will not remain on the OS's output buffers */ | |
545 | fflush(fp); | |
546 | aof_fsync(fileno(fp)); | |
547 | fclose(fp); | |
548 | ||
549 | /* Use RENAME to make sure the DB file is changed atomically only | |
550 | * if the generate DB file is ok. */ | |
551 | if (rename(tmpfile,filename) == -1) { | |
552 | redisLog(REDIS_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno)); | |
553 | unlink(tmpfile); | |
554 | return REDIS_ERR; | |
555 | } | |
556 | redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed"); | |
557 | return REDIS_OK; | |
558 | ||
559 | werr: | |
560 | fclose(fp); | |
561 | unlink(tmpfile); | |
562 | redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno)); | |
563 | if (di) dictReleaseIterator(di); | |
564 | return REDIS_ERR; | |
565 | } | |
566 | ||
567 | /* This is how rewriting of the append only file in background works: | |
568 | * | |
569 | * 1) The user calls BGREWRITEAOF | |
570 | * 2) Redis calls this function, that forks(): | |
571 | * 2a) the child rewrite the append only file in a temp file. | |
572 | * 2b) the parent accumulates differences in server.bgrewritebuf. | |
573 | * 3) When the child finished '2a' exists. | |
574 | * 4) The parent will trap the exit code, if it's OK, will append the | |
575 | * data accumulated into server.bgrewritebuf into the temp file, and | |
576 | * finally will rename(2) the temp file in the actual file name. | |
577 | * The the new file is reopened as the new append only file. Profit! | |
578 | */ | |
579 | int rewriteAppendOnlyFileBackground(void) { | |
580 | pid_t childpid; | |
581 | ||
582 | if (server.bgrewritechildpid != -1) return REDIS_ERR; | |
583 | if (server.vm_enabled) waitEmptyIOJobsQueue(); | |
584 | if ((childpid = fork()) == 0) { | |
585 | /* Child */ | |
586 | char tmpfile[256]; | |
587 | ||
588 | if (server.vm_enabled) vmReopenSwapFile(); | |
589 | close(server.fd); | |
590 | snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid()); | |
591 | if (rewriteAppendOnlyFile(tmpfile) == REDIS_OK) { | |
592 | _exit(0); | |
593 | } else { | |
594 | _exit(1); | |
595 | } | |
596 | } else { | |
597 | /* Parent */ | |
598 | if (childpid == -1) { | |
599 | redisLog(REDIS_WARNING, | |
600 | "Can't rewrite append only file in background: fork: %s", | |
601 | strerror(errno)); | |
602 | return REDIS_ERR; | |
603 | } | |
604 | redisLog(REDIS_NOTICE, | |
605 | "Background append only file rewriting started by pid %d",childpid); | |
606 | server.bgrewritechildpid = childpid; | |
607 | updateDictResizePolicy(); | |
608 | /* We set appendseldb to -1 in order to force the next call to the | |
609 | * feedAppendOnlyFile() to issue a SELECT command, so the differences | |
610 | * accumulated by the parent into server.bgrewritebuf will start | |
611 | * with a SELECT statement and it will be safe to merge. */ | |
612 | server.appendseldb = -1; | |
613 | return REDIS_OK; | |
614 | } | |
615 | return REDIS_OK; /* unreached */ | |
616 | } | |
617 | ||
618 | void bgrewriteaofCommand(redisClient *c) { | |
619 | if (server.bgrewritechildpid != -1) { | |
620 | addReplySds(c,sdsnew("-ERR background append only file rewriting already in progress\r\n")); | |
621 | return; | |
622 | } | |
623 | if (rewriteAppendOnlyFileBackground() == REDIS_OK) { | |
624 | char *status = "+Background append only file rewriting started\r\n"; | |
625 | addReplySds(c,sdsnew(status)); | |
626 | } else { | |
627 | addReply(c,shared.err); | |
628 | } | |
629 | } | |
630 | ||
631 | void aofRemoveTempFile(pid_t childpid) { | |
632 | char tmpfile[256]; | |
633 | ||
634 | snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid); | |
635 | unlink(tmpfile); | |
636 | } | |
637 | ||
638 | /* A background append only file rewriting (BGREWRITEAOF) terminated its work. | |
639 | * Handle this. */ | |
640 | void backgroundRewriteDoneHandler(int statloc) { | |
641 | int exitcode = WEXITSTATUS(statloc); | |
642 | int bysignal = WIFSIGNALED(statloc); | |
643 | ||
644 | if (!bysignal && exitcode == 0) { | |
645 | int fd; | |
646 | char tmpfile[256]; | |
647 | ||
648 | redisLog(REDIS_NOTICE, | |
649 | "Background append only file rewriting terminated with success"); | |
650 | /* Now it's time to flush the differences accumulated by the parent */ | |
651 | snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) server.bgrewritechildpid); | |
652 | fd = open(tmpfile,O_WRONLY|O_APPEND); | |
653 | if (fd == -1) { | |
654 | redisLog(REDIS_WARNING, "Not able to open the temp append only file produced by the child: %s", strerror(errno)); | |
655 | goto cleanup; | |
656 | } | |
657 | /* Flush our data... */ | |
658 | if (write(fd,server.bgrewritebuf,sdslen(server.bgrewritebuf)) != | |
659 | (signed) sdslen(server.bgrewritebuf)) { | |
660 | redisLog(REDIS_WARNING, "Error or short write trying to flush the parent diff of the append log file in the child temp file: %s", strerror(errno)); | |
661 | close(fd); | |
662 | goto cleanup; | |
663 | } | |
664 | redisLog(REDIS_NOTICE,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server.bgrewritebuf)); | |
665 | /* Now our work is to rename the temp file into the stable file. And | |
666 | * switch the file descriptor used by the server for append only. */ | |
667 | if (rename(tmpfile,server.appendfilename) == -1) { | |
668 | redisLog(REDIS_WARNING,"Can't rename the temp append only file into the stable one: %s", strerror(errno)); | |
669 | close(fd); | |
670 | goto cleanup; | |
671 | } | |
672 | /* Mission completed... almost */ | |
673 | redisLog(REDIS_NOTICE,"Append only file successfully rewritten."); | |
674 | if (server.appendfd != -1) { | |
675 | /* If append only is actually enabled... */ | |
676 | close(server.appendfd); | |
677 | server.appendfd = fd; | |
678 | if (server.appendfsync != APPENDFSYNC_NO) aof_fsync(fd); | |
679 | server.appendseldb = -1; /* Make sure it will issue SELECT */ | |
680 | redisLog(REDIS_NOTICE,"The new append only file was selected for future appends."); | |
681 | } else { | |
682 | /* If append only is disabled we just generate a dump in this | |
683 | * format. Why not? */ | |
684 | close(fd); | |
685 | } | |
686 | } else if (!bysignal && exitcode != 0) { | |
687 | redisLog(REDIS_WARNING, "Background append only file rewriting error"); | |
688 | } else { | |
689 | redisLog(REDIS_WARNING, | |
690 | "Background append only file rewriting terminated by signal %d", | |
691 | WTERMSIG(statloc)); | |
692 | } | |
693 | cleanup: | |
694 | sdsfree(server.bgrewritebuf); | |
695 | server.bgrewritebuf = sdsempty(); | |
696 | aofRemoveTempFile(server.bgrewritechildpid); | |
697 | server.bgrewritechildpid = -1; | |
698 | } |