]> git.saurik.com Git - redis.git/blob - src/replication.c
Marginally more robust glibc version test for sync_file_range detection.
[redis.git] / src / replication.c
1 #include "redis.h"
2
3 #include <sys/time.h>
4 #include <unistd.h>
5 #include <fcntl.h>
6 #include <sys/socket.h>
7 #include <sys/stat.h>
8
9 /* ---------------------------------- MASTER -------------------------------- */
10
11 void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc) {
12 listNode *ln;
13 listIter li;
14 int j;
15
16 listRewind(slaves,&li);
17 while((ln = listNext(&li))) {
18 redisClient *slave = ln->value;
19
20 /* Don't feed slaves that are still waiting for BGSAVE to start */
21 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) continue;
22
23 /* Feed slaves that are waiting for the initial SYNC (so these commands
24 * are queued in the output buffer until the intial SYNC completes),
25 * or are already in sync with the master. */
26 if (slave->slaveseldb != dictid) {
27 robj *selectcmd;
28
29 if (dictid >= 0 && dictid < REDIS_SHARED_SELECT_CMDS) {
30 selectcmd = shared.select[dictid];
31 incrRefCount(selectcmd);
32 } else {
33 selectcmd = createObject(REDIS_STRING,
34 sdscatprintf(sdsempty(),"select %d\r\n",dictid));
35 }
36 addReply(slave,selectcmd);
37 decrRefCount(selectcmd);
38 slave->slaveseldb = dictid;
39 }
40 addReplyMultiBulkLen(slave,argc);
41 for (j = 0; j < argc; j++) addReplyBulk(slave,argv[j]);
42 }
43 }
44
45 void replicationFeedMonitors(redisClient *c, list *monitors, int dictid, robj **argv, int argc) {
46 listNode *ln;
47 listIter li;
48 int j, port;
49 sds cmdrepr = sdsnew("+");
50 robj *cmdobj;
51 char ip[32];
52 struct timeval tv;
53
54 gettimeofday(&tv,NULL);
55 cmdrepr = sdscatprintf(cmdrepr,"%ld.%06ld ",(long)tv.tv_sec,(long)tv.tv_usec);
56 if (c->flags & REDIS_LUA_CLIENT) {
57 cmdrepr = sdscatprintf(cmdrepr,"[%d lua] ", dictid);
58 } else {
59 anetPeerToString(c->fd,ip,&port);
60 cmdrepr = sdscatprintf(cmdrepr,"[%d %s:%d] ", dictid,ip,port);
61 }
62
63 for (j = 0; j < argc; j++) {
64 if (argv[j]->encoding == REDIS_ENCODING_INT) {
65 cmdrepr = sdscatprintf(cmdrepr, "\"%ld\"", (long)argv[j]->ptr);
66 } else {
67 cmdrepr = sdscatrepr(cmdrepr,(char*)argv[j]->ptr,
68 sdslen(argv[j]->ptr));
69 }
70 if (j != argc-1)
71 cmdrepr = sdscatlen(cmdrepr," ",1);
72 }
73 cmdrepr = sdscatlen(cmdrepr,"\r\n",2);
74 cmdobj = createObject(REDIS_STRING,cmdrepr);
75
76 listRewind(monitors,&li);
77 while((ln = listNext(&li))) {
78 redisClient *monitor = ln->value;
79 addReply(monitor,cmdobj);
80 }
81 decrRefCount(cmdobj);
82 }
83
84 void syncCommand(redisClient *c) {
85 /* ignore SYNC if aleady slave or in monitor mode */
86 if (c->flags & REDIS_SLAVE) return;
87
88 /* Refuse SYNC requests if we are a slave but the link with our master
89 * is not ok... */
90 if (server.masterhost && server.repl_state != REDIS_REPL_CONNECTED) {
91 addReplyError(c,"Can't SYNC while not connected with my master");
92 return;
93 }
94
95 /* SYNC can't be issued when the server has pending data to send to
96 * the client about already issued commands. We need a fresh reply
97 * buffer registering the differences between the BGSAVE and the current
98 * dataset, so that we can copy to other slaves if needed. */
99 if (listLength(c->reply) != 0) {
100 addReplyError(c,"SYNC is invalid with pending input");
101 return;
102 }
103
104 redisLog(REDIS_NOTICE,"Slave ask for synchronization");
105 /* Here we need to check if there is a background saving operation
106 * in progress, or if it is required to start one */
107 if (server.rdb_child_pid != -1) {
108 /* Ok a background save is in progress. Let's check if it is a good
109 * one for replication, i.e. if there is another slave that is
110 * registering differences since the server forked to save */
111 redisClient *slave;
112 listNode *ln;
113 listIter li;
114
115 listRewind(server.slaves,&li);
116 while((ln = listNext(&li))) {
117 slave = ln->value;
118 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) break;
119 }
120 if (ln) {
121 /* Perfect, the server is already registering differences for
122 * another slave. Set the right state, and copy the buffer. */
123 copyClientOutputBuffer(c,slave);
124 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
125 redisLog(REDIS_NOTICE,"Waiting for end of BGSAVE for SYNC");
126 } else {
127 /* No way, we need to wait for the next BGSAVE in order to
128 * register differences */
129 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
130 redisLog(REDIS_NOTICE,"Waiting for next BGSAVE for SYNC");
131 }
132 } else {
133 /* Ok we don't have a BGSAVE in progress, let's start one */
134 redisLog(REDIS_NOTICE,"Starting BGSAVE for SYNC");
135 if (rdbSaveBackground(server.rdb_filename) != REDIS_OK) {
136 redisLog(REDIS_NOTICE,"Replication failed, can't BGSAVE");
137 addReplyError(c,"Unable to perform background save");
138 return;
139 }
140 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
141 }
142 c->repldbfd = -1;
143 c->flags |= REDIS_SLAVE;
144 c->slaveseldb = 0;
145 listAddNodeTail(server.slaves,c);
146 return;
147 }
148
149 /* REPLCONF <option> <value> <option> <value> ...
150 * This command is used by a slave in order to configure the replication
151 * process before starting it with the SYNC command.
152 *
153 * Currently the only use of this command is to communicate to the master
154 * what is the listening port of the Slave redis instance, so that the
155 * master can accurately list slaves and their listening ports in
156 * the INFO output.
157 *
158 * In the future the same command can be used in order to configure
159 * the replication to initiate an incremental replication instead of a
160 * full resync. */
161 void replconfCommand(redisClient *c) {
162 int j;
163
164 if ((c->argc % 2) == 0) {
165 /* Number of arguments must be odd to make sure that every
166 * option has a corresponding value. */
167 addReply(c,shared.syntaxerr);
168 return;
169 }
170
171 /* Process every option-value pair. */
172 for (j = 1; j < c->argc; j+=2) {
173 if (!strcasecmp(c->argv[j]->ptr,"listening-port")) {
174 long port;
175
176 if ((getLongFromObjectOrReply(c,c->argv[j+1],
177 &port,NULL) != REDIS_OK))
178 return;
179 c->slave_listening_port = port;
180 } else {
181 addReplyErrorFormat(c,"Unrecognized REPLCONF option: %s",
182 (char*)c->argv[j]->ptr);
183 return;
184 }
185 }
186 addReply(c,shared.ok);
187 }
188
189 void sendBulkToSlave(aeEventLoop *el, int fd, void *privdata, int mask) {
190 redisClient *slave = privdata;
191 REDIS_NOTUSED(el);
192 REDIS_NOTUSED(mask);
193 char buf[REDIS_IOBUF_LEN];
194 ssize_t nwritten, buflen;
195
196 if (slave->repldboff == 0) {
197 /* Write the bulk write count before to transfer the DB. In theory here
198 * we don't know how much room there is in the output buffer of the
199 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
200 * operations) will never be smaller than the few bytes we need. */
201 sds bulkcount;
202
203 bulkcount = sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
204 slave->repldbsize);
205 if (write(fd,bulkcount,sdslen(bulkcount)) != (signed)sdslen(bulkcount))
206 {
207 sdsfree(bulkcount);
208 freeClient(slave);
209 return;
210 }
211 sdsfree(bulkcount);
212 }
213 lseek(slave->repldbfd,slave->repldboff,SEEK_SET);
214 buflen = read(slave->repldbfd,buf,REDIS_IOBUF_LEN);
215 if (buflen <= 0) {
216 redisLog(REDIS_WARNING,"Read error sending DB to slave: %s",
217 (buflen == 0) ? "premature EOF" : strerror(errno));
218 freeClient(slave);
219 return;
220 }
221 if ((nwritten = write(fd,buf,buflen)) == -1) {
222 redisLog(REDIS_VERBOSE,"Write error sending DB to slave: %s",
223 strerror(errno));
224 freeClient(slave);
225 return;
226 }
227 slave->repldboff += nwritten;
228 if (slave->repldboff == slave->repldbsize) {
229 close(slave->repldbfd);
230 slave->repldbfd = -1;
231 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
232 slave->replstate = REDIS_REPL_ONLINE;
233 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE,
234 sendReplyToClient, slave) == AE_ERR) {
235 freeClient(slave);
236 return;
237 }
238 redisLog(REDIS_NOTICE,"Synchronization with slave succeeded");
239 }
240 }
241
242 /* This function is called at the end of every backgrond saving.
243 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
244 * otherwise REDIS_ERR is passed to the function.
245 *
246 * The goal of this function is to handle slaves waiting for a successful
247 * background saving in order to perform non-blocking synchronization. */
248 void updateSlavesWaitingBgsave(int bgsaveerr) {
249 listNode *ln;
250 int startbgsave = 0;
251 listIter li;
252
253 listRewind(server.slaves,&li);
254 while((ln = listNext(&li))) {
255 redisClient *slave = ln->value;
256
257 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) {
258 startbgsave = 1;
259 slave->replstate = REDIS_REPL_WAIT_BGSAVE_END;
260 } else if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) {
261 struct redis_stat buf;
262
263 if (bgsaveerr != REDIS_OK) {
264 freeClient(slave);
265 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE child returned an error");
266 continue;
267 }
268 if ((slave->repldbfd = open(server.rdb_filename,O_RDONLY)) == -1 ||
269 redis_fstat(slave->repldbfd,&buf) == -1) {
270 freeClient(slave);
271 redisLog(REDIS_WARNING,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno));
272 continue;
273 }
274 slave->repldboff = 0;
275 slave->repldbsize = buf.st_size;
276 slave->replstate = REDIS_REPL_SEND_BULK;
277 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
278 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE, sendBulkToSlave, slave) == AE_ERR) {
279 freeClient(slave);
280 continue;
281 }
282 }
283 }
284 if (startbgsave) {
285 if (rdbSaveBackground(server.rdb_filename) != REDIS_OK) {
286 listIter li;
287
288 listRewind(server.slaves,&li);
289 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE failed");
290 while((ln = listNext(&li))) {
291 redisClient *slave = ln->value;
292
293 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START)
294 freeClient(slave);
295 }
296 }
297 }
298 }
299
300 /* ----------------------------------- SLAVE -------------------------------- */
301
302 /* Abort the async download of the bulk dataset while SYNC-ing with master */
303 void replicationAbortSyncTransfer(void) {
304 redisAssert(server.repl_state == REDIS_REPL_TRANSFER);
305
306 aeDeleteFileEvent(server.el,server.repl_transfer_s,AE_READABLE);
307 close(server.repl_transfer_s);
308 close(server.repl_transfer_fd);
309 unlink(server.repl_transfer_tmpfile);
310 zfree(server.repl_transfer_tmpfile);
311 server.repl_state = REDIS_REPL_CONNECT;
312 }
313
314 /* Asynchronously read the SYNC payload we receive from a master */
315 #define REPL_MAX_WRITTEN_BEFORE_FSYNC (1024*1024*8) /* 8 MB */
316 void readSyncBulkPayload(aeEventLoop *el, int fd, void *privdata, int mask) {
317 char buf[4096];
318 ssize_t nread, readlen;
319 off_t left;
320 REDIS_NOTUSED(el);
321 REDIS_NOTUSED(privdata);
322 REDIS_NOTUSED(mask);
323
324 /* If repl_transfer_size == -1 we still have to read the bulk length
325 * from the master reply. */
326 if (server.repl_transfer_size == -1) {
327 if (syncReadLine(fd,buf,1024,server.repl_syncio_timeout*1000) == -1) {
328 redisLog(REDIS_WARNING,
329 "I/O error reading bulk count from MASTER: %s",
330 strerror(errno));
331 goto error;
332 }
333
334 if (buf[0] == '-') {
335 redisLog(REDIS_WARNING,
336 "MASTER aborted replication with an error: %s",
337 buf+1);
338 goto error;
339 } else if (buf[0] == '\0') {
340 /* At this stage just a newline works as a PING in order to take
341 * the connection live. So we refresh our last interaction
342 * timestamp. */
343 server.repl_transfer_lastio = server.unixtime;
344 return;
345 } else if (buf[0] != '$') {
346 redisLog(REDIS_WARNING,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
347 goto error;
348 }
349 server.repl_transfer_size = strtol(buf+1,NULL,10);
350 redisLog(REDIS_NOTICE,
351 "MASTER <-> SLAVE sync: receiving %ld bytes from master",
352 server.repl_transfer_size);
353 return;
354 }
355
356 /* Read bulk data */
357 left = server.repl_transfer_size - server.repl_transfer_read;
358 readlen = (left < (signed)sizeof(buf)) ? left : (signed)sizeof(buf);
359 nread = read(fd,buf,readlen);
360 if (nread <= 0) {
361 redisLog(REDIS_WARNING,"I/O error trying to sync with MASTER: %s",
362 (nread == -1) ? strerror(errno) : "connection lost");
363 replicationAbortSyncTransfer();
364 return;
365 }
366 server.repl_transfer_lastio = server.unixtime;
367 if (write(server.repl_transfer_fd,buf,nread) != nread) {
368 redisLog(REDIS_WARNING,"Write error or short write writing to the DB dump file needed for MASTER <-> SLAVE synchronization: %s", strerror(errno));
369 goto error;
370 }
371 server.repl_transfer_read += nread;
372
373 /* Sync data on disk from time to time, otherwise at the end of the transfer
374 * we may suffer a big delay as the memory buffers are copied into the
375 * actual disk. */
376 if (server.repl_transfer_read >=
377 server.repl_transfer_last_fsync_off + REPL_MAX_WRITTEN_BEFORE_FSYNC)
378 {
379 off_t sync_size = server.repl_transfer_read -
380 server.repl_transfer_last_fsync_off;
381 rdb_fsync_range(server.repl_transfer_fd,
382 server.repl_transfer_last_fsync_off, sync_size);
383 server.repl_transfer_last_fsync_off += sync_size;
384 }
385
386 /* Check if the transfer is now complete */
387 if (server.repl_transfer_read == server.repl_transfer_size) {
388 if (rename(server.repl_transfer_tmpfile,server.rdb_filename) == -1) {
389 redisLog(REDIS_WARNING,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno));
390 replicationAbortSyncTransfer();
391 return;
392 }
393 redisLog(REDIS_NOTICE, "MASTER <-> SLAVE sync: Loading DB in memory");
394 emptyDb();
395 /* Before loading the DB into memory we need to delete the readable
396 * handler, otherwise it will get called recursively since
397 * rdbLoad() will call the event loop to process events from time to
398 * time for non blocking loading. */
399 aeDeleteFileEvent(server.el,server.repl_transfer_s,AE_READABLE);
400 if (rdbLoad(server.rdb_filename) != REDIS_OK) {
401 redisLog(REDIS_WARNING,"Failed trying to load the MASTER synchronization DB from disk");
402 replicationAbortSyncTransfer();
403 return;
404 }
405 /* Final setup of the connected slave <- master link */
406 zfree(server.repl_transfer_tmpfile);
407 close(server.repl_transfer_fd);
408 server.master = createClient(server.repl_transfer_s);
409 server.master->flags |= REDIS_MASTER;
410 server.master->authenticated = 1;
411 server.repl_state = REDIS_REPL_CONNECTED;
412 redisLog(REDIS_NOTICE, "MASTER <-> SLAVE sync: Finished with success");
413 /* Restart the AOF subsystem now that we finished the sync. This
414 * will trigger an AOF rewrite, and when done will start appending
415 * to the new file. */
416 if (server.aof_state != REDIS_AOF_OFF) {
417 int retry = 10;
418
419 stopAppendOnly();
420 while (retry-- && startAppendOnly() == REDIS_ERR) {
421 redisLog(REDIS_WARNING,"Failed enabling the AOF after successful master synchrnization! Trying it again in one second.");
422 sleep(1);
423 }
424 if (!retry) {
425 redisLog(REDIS_WARNING,"FATAL: this slave instance finished the synchronization with its master, but the AOF can't be turned on. Exiting now.");
426 exit(1);
427 }
428 }
429 }
430
431 return;
432
433 error:
434 replicationAbortSyncTransfer();
435 return;
436 }
437
438 /* Send a synchronous command to the master. Used to send AUTH and
439 * REPLCONF commands before starting the replication with SYNC.
440 *
441 * On success NULL is returned.
442 * On error an sds string describing the error is returned.
443 */
444 char *sendSynchronousCommand(int fd, ...) {
445 va_list ap;
446 sds cmd = sdsempty();
447 char *arg, buf[256];
448
449 /* Create the command to send to the master, we use simple inline
450 * protocol for simplicity as currently we only send simple strings. */
451 va_start(ap,fd);
452 while(1) {
453 arg = va_arg(ap, char*);
454 if (arg == NULL) break;
455
456 if (sdslen(cmd) != 0) cmd = sdscatlen(cmd," ",1);
457 cmd = sdscat(cmd,arg);
458 }
459 cmd = sdscatlen(cmd,"\r\n",2);
460
461 /* Transfer command to the server. */
462 if (syncWrite(fd,cmd,sdslen(cmd),server.repl_syncio_timeout*1000) == -1) {
463 sdsfree(cmd);
464 return sdscatprintf(sdsempty(),"Writing to master: %s",
465 strerror(errno));
466 }
467 sdsfree(cmd);
468
469 /* Read the reply from the server. */
470 if (syncReadLine(fd,buf,sizeof(buf),server.repl_syncio_timeout*1000) == -1)
471 {
472 return sdscatprintf(sdsempty(),"Reading from master: %s",
473 strerror(errno));
474 }
475
476 /* Check for errors from the server. */
477 if (buf[0] != '+') {
478 return sdscatprintf(sdsempty(),"Error from master: %s", buf);
479 }
480
481 return NULL; /* No errors. */
482 }
483
484 void syncWithMaster(aeEventLoop *el, int fd, void *privdata, int mask) {
485 char tmpfile[256], *err;
486 int dfd, maxtries = 5;
487 int sockerr = 0;
488 socklen_t errlen = sizeof(sockerr);
489 REDIS_NOTUSED(el);
490 REDIS_NOTUSED(privdata);
491 REDIS_NOTUSED(mask);
492
493 /* If this event fired after the user turned the instance into a master
494 * with SLAVEOF NO ONE we must just return ASAP. */
495 if (server.repl_state == REDIS_REPL_NONE) {
496 close(fd);
497 return;
498 }
499
500 /* Check for errors in the socket. */
501 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &sockerr, &errlen) == -1)
502 sockerr = errno;
503 if (sockerr) {
504 aeDeleteFileEvent(server.el,fd,AE_READABLE|AE_WRITABLE);
505 redisLog(REDIS_WARNING,"Error condition on socket for SYNC: %s",
506 strerror(sockerr));
507 goto error;
508 }
509
510 /* If we were connecting, it's time to send a non blocking PING, we want to
511 * make sure the master is able to reply before going into the actual
512 * replication process where we have long timeouts in the order of
513 * seconds (in the meantime the slave would block). */
514 if (server.repl_state == REDIS_REPL_CONNECTING) {
515 redisLog(REDIS_NOTICE,"Non blocking connect for SYNC fired the event.");
516 /* Delete the writable event so that the readable event remains
517 * registered and we can wait for the PONG reply. */
518 aeDeleteFileEvent(server.el,fd,AE_WRITABLE);
519 server.repl_state = REDIS_REPL_RECEIVE_PONG;
520 /* Send the PING, don't check for errors at all, we have the timeout
521 * that will take care about this. */
522 syncWrite(fd,"PING\r\n",6,100);
523 return;
524 }
525
526 /* Receive the PONG command. */
527 if (server.repl_state == REDIS_REPL_RECEIVE_PONG) {
528 char buf[1024];
529
530 /* Delete the readable event, we no longer need it now that there is
531 * the PING reply to read. */
532 aeDeleteFileEvent(server.el,fd,AE_READABLE);
533
534 /* Read the reply with explicit timeout. */
535 buf[0] = '\0';
536 if (syncReadLine(fd,buf,sizeof(buf),
537 server.repl_syncio_timeout*1000) == -1)
538 {
539 redisLog(REDIS_WARNING,
540 "I/O error reading PING reply from master: %s",
541 strerror(errno));
542 goto error;
543 }
544
545 /* We don't care about the reply, it can be +PONG or an error since
546 * the server requires AUTH. As long as it replies correctly, it's
547 * fine from our point of view. */
548 if (buf[0] != '-' && buf[0] != '+') {
549 redisLog(REDIS_WARNING,"Unexpected reply to PING from master.");
550 goto error;
551 } else {
552 redisLog(REDIS_NOTICE,
553 "Master replied to PING, replication can continue...");
554 }
555 }
556
557 /* AUTH with the master if required. */
558 if(server.masterauth) {
559 err = sendSynchronousCommand(fd,"AUTH",server.masterauth,NULL);
560 if (err) {
561 redisLog(REDIS_WARNING,"Unable to AUTH to MASTER: %s",err);
562 sdsfree(err);
563 goto error;
564 }
565 }
566
567 /* Set the slave port, so that Master's INFO command can list the
568 * slave listening port correctly. */
569 {
570 sds port = sdsfromlonglong(server.port);
571 err = sendSynchronousCommand(fd,"REPLCONF","listening-port",port,
572 NULL);
573 sdsfree(port);
574 /* Ignore the error if any, not all the Redis versions support
575 * REPLCONF listening-port. */
576 if (err) {
577 redisLog(REDIS_NOTICE,"(non critical): Master does not understand REPLCONF listening-port: %s", err);
578 sdsfree(err);
579 }
580 }
581
582 /* Issue the SYNC command */
583 if (syncWrite(fd,"SYNC\r\n",6,server.repl_syncio_timeout*1000) == -1) {
584 redisLog(REDIS_WARNING,"I/O error writing to MASTER: %s",
585 strerror(errno));
586 goto error;
587 }
588
589 /* Prepare a suitable temp file for bulk transfer */
590 while(maxtries--) {
591 snprintf(tmpfile,256,
592 "temp-%d.%ld.rdb",(int)server.unixtime,(long int)getpid());
593 dfd = open(tmpfile,O_CREAT|O_WRONLY|O_EXCL,0644);
594 if (dfd != -1) break;
595 sleep(1);
596 }
597 if (dfd == -1) {
598 redisLog(REDIS_WARNING,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno));
599 goto error;
600 }
601
602 /* Setup the non blocking download of the bulk file. */
603 if (aeCreateFileEvent(server.el,fd, AE_READABLE,readSyncBulkPayload,NULL)
604 == AE_ERR)
605 {
606 redisLog(REDIS_WARNING,"Can't create readable event for SYNC");
607 goto error;
608 }
609
610 server.repl_state = REDIS_REPL_TRANSFER;
611 server.repl_transfer_size = -1;
612 server.repl_transfer_read = 0;
613 server.repl_transfer_last_fsync_off = 0;
614 server.repl_transfer_fd = dfd;
615 server.repl_transfer_lastio = server.unixtime;
616 server.repl_transfer_tmpfile = zstrdup(tmpfile);
617 return;
618
619 error:
620 close(fd);
621 server.repl_transfer_s = -1;
622 server.repl_state = REDIS_REPL_CONNECT;
623 return;
624 }
625
626 int connectWithMaster(void) {
627 int fd;
628
629 fd = anetTcpNonBlockConnect(NULL,server.masterhost,server.masterport);
630 if (fd == -1) {
631 redisLog(REDIS_WARNING,"Unable to connect to MASTER: %s",
632 strerror(errno));
633 return REDIS_ERR;
634 }
635
636 if (aeCreateFileEvent(server.el,fd,AE_READABLE|AE_WRITABLE,syncWithMaster,NULL) ==
637 AE_ERR)
638 {
639 close(fd);
640 redisLog(REDIS_WARNING,"Can't create readable event for SYNC");
641 return REDIS_ERR;
642 }
643
644 server.repl_transfer_lastio = server.unixtime;
645 server.repl_transfer_s = fd;
646 server.repl_state = REDIS_REPL_CONNECTING;
647 return REDIS_OK;
648 }
649
650 /* This function can be called when a non blocking connection is currently
651 * in progress to undo it. */
652 void undoConnectWithMaster(void) {
653 int fd = server.repl_transfer_s;
654
655 redisAssert(server.repl_state == REDIS_REPL_CONNECTING ||
656 server.repl_state == REDIS_REPL_RECEIVE_PONG);
657 aeDeleteFileEvent(server.el,fd,AE_READABLE|AE_WRITABLE);
658 close(fd);
659 server.repl_transfer_s = -1;
660 server.repl_state = REDIS_REPL_CONNECT;
661 }
662
663 void slaveofCommand(redisClient *c) {
664 if (!strcasecmp(c->argv[1]->ptr,"no") &&
665 !strcasecmp(c->argv[2]->ptr,"one")) {
666 if (server.masterhost) {
667 sdsfree(server.masterhost);
668 server.masterhost = NULL;
669 if (server.master) freeClient(server.master);
670 if (server.repl_state == REDIS_REPL_TRANSFER)
671 replicationAbortSyncTransfer();
672 else if (server.repl_state == REDIS_REPL_CONNECTING ||
673 server.repl_state == REDIS_REPL_RECEIVE_PONG)
674 undoConnectWithMaster();
675 server.repl_state = REDIS_REPL_NONE;
676 redisLog(REDIS_NOTICE,"MASTER MODE enabled (user request)");
677 }
678 } else {
679 long port;
680
681 if ((getLongFromObjectOrReply(c, c->argv[2], &port, NULL) != REDIS_OK))
682 return;
683
684 /* Check if we are already attached to the specified slave */
685 if (server.masterhost && !strcasecmp(server.masterhost,c->argv[1]->ptr)
686 && server.masterport == port) {
687 redisLog(REDIS_NOTICE,"SLAVE OF would result into synchronization with the master we are already connected with. No operation performed.");
688 addReplySds(c,sdsnew("+OK Already connected to specified master\r\n"));
689 return;
690 }
691 /* There was no previous master or the user specified a different one,
692 * we can continue. */
693 sdsfree(server.masterhost);
694 server.masterhost = sdsdup(c->argv[1]->ptr);
695 server.masterport = port;
696 if (server.master) freeClient(server.master);
697 disconnectSlaves(); /* Force our slaves to resync with us as well. */
698 if (server.repl_state == REDIS_REPL_TRANSFER)
699 replicationAbortSyncTransfer();
700 server.repl_state = REDIS_REPL_CONNECT;
701 redisLog(REDIS_NOTICE,"SLAVE OF %s:%d enabled (user request)",
702 server.masterhost, server.masterport);
703 }
704 addReply(c,shared.ok);
705 }
706
707 /* --------------------------- REPLICATION CRON ---------------------------- */
708
709 void replicationCron(void) {
710 /* Non blocking connection timeout? */
711 if (server.masterhost &&
712 (server.repl_state == REDIS_REPL_CONNECTING ||
713 server.repl_state == REDIS_REPL_RECEIVE_PONG) &&
714 (time(NULL)-server.repl_transfer_lastio) > server.repl_timeout)
715 {
716 redisLog(REDIS_WARNING,"Timeout connecting to the MASTER...");
717 undoConnectWithMaster();
718 }
719
720 /* Bulk transfer I/O timeout? */
721 if (server.masterhost && server.repl_state == REDIS_REPL_TRANSFER &&
722 (time(NULL)-server.repl_transfer_lastio) > server.repl_timeout)
723 {
724 redisLog(REDIS_WARNING,"Timeout receiving bulk data from MASTER... If the problem persists try to set the 'repl-timeout' parameter in redis.conf to a larger value.");
725 replicationAbortSyncTransfer();
726 }
727
728 /* Timed out master when we are an already connected slave? */
729 if (server.masterhost && server.repl_state == REDIS_REPL_CONNECTED &&
730 (time(NULL)-server.master->lastinteraction) > server.repl_timeout)
731 {
732 redisLog(REDIS_WARNING,"MASTER time out: no data nor PING received...");
733 freeClient(server.master);
734 }
735
736 /* Check if we should connect to a MASTER */
737 if (server.repl_state == REDIS_REPL_CONNECT) {
738 redisLog(REDIS_NOTICE,"Connecting to MASTER...");
739 if (connectWithMaster() == REDIS_OK) {
740 redisLog(REDIS_NOTICE,"MASTER <-> SLAVE sync started");
741 }
742 }
743
744 /* If we have attached slaves, PING them from time to time.
745 * So slaves can implement an explicit timeout to masters, and will
746 * be able to detect a link disconnection even if the TCP connection
747 * will not actually go down. */
748 if (!(server.cronloops % (server.repl_ping_slave_period * REDIS_HZ))) {
749 listIter li;
750 listNode *ln;
751
752 listRewind(server.slaves,&li);
753 while((ln = listNext(&li))) {
754 redisClient *slave = ln->value;
755
756 /* Don't ping slaves that are in the middle of a bulk transfer
757 * with the master for first synchronization. */
758 if (slave->replstate == REDIS_REPL_SEND_BULK) continue;
759 if (slave->replstate == REDIS_REPL_ONLINE) {
760 /* If the slave is online send a normal ping */
761 addReplySds(slave,sdsnew("*1\r\n$4\r\nPING\r\n"));
762 } else {
763 /* Otherwise we are in the pre-synchronization stage.
764 * Just a newline will do the work of refreshing the
765 * connection last interaction time, and at the same time
766 * we'll be sure that being a single char there are no
767 * short-write problems. */
768 if (write(slave->fd, "\n", 1) == -1) {
769 /* Don't worry, it's just a ping. */
770 }
771 }
772 }
773 }
774 }