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