6 #include <sys/socket.h>
9 /* ---------------------------------- MASTER -------------------------------- */
11 void replicationFeedSlaves(list
*slaves
, int dictid
, robj
**argv
, int argc
) {
16 listRewind(slaves
,&li
);
17 while((ln
= listNext(&li
))) {
18 redisClient
*slave
= ln
->value
;
20 /* Don't feed slaves that are still waiting for BGSAVE to start */
21 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) continue;
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
) {
29 if (dictid
>= 0 && dictid
< REDIS_SHARED_SELECT_CMDS
) {
30 selectcmd
= shared
.select
[dictid
];
31 incrRefCount(selectcmd
);
33 selectcmd
= createObject(REDIS_STRING
,
34 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
36 addReply(slave
,selectcmd
);
37 decrRefCount(selectcmd
);
38 slave
->slaveseldb
= dictid
;
40 addReplyMultiBulkLen(slave
,argc
);
41 for (j
= 0; j
< argc
; j
++) addReplyBulk(slave
,argv
[j
]);
45 void replicationFeedMonitors(redisClient
*c
, list
*monitors
, int dictid
, robj
**argv
, int argc
) {
49 sds cmdrepr
= sdsnew("+");
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
);
59 anetPeerToString(c
->fd
,ip
,&port
);
60 cmdrepr
= sdscatprintf(cmdrepr
,"[%d %s:%d] ", dictid
,ip
,port
);
63 for (j
= 0; j
< argc
; j
++) {
64 if (argv
[j
]->encoding
== REDIS_ENCODING_INT
) {
65 cmdrepr
= sdscatprintf(cmdrepr
, "\"%ld\"", (long)argv
[j
]->ptr
);
67 cmdrepr
= sdscatrepr(cmdrepr
,(char*)argv
[j
]->ptr
,
68 sdslen(argv
[j
]->ptr
));
71 cmdrepr
= sdscatlen(cmdrepr
," ",1);
73 cmdrepr
= sdscatlen(cmdrepr
,"\r\n",2);
74 cmdobj
= createObject(REDIS_STRING
,cmdrepr
);
76 listRewind(monitors
,&li
);
77 while((ln
= listNext(&li
))) {
78 redisClient
*monitor
= ln
->value
;
79 addReply(monitor
,cmdobj
);
84 void syncCommand(redisClient
*c
) {
85 /* ignore SYNC if aleady slave or in monitor mode */
86 if (c
->flags
& REDIS_SLAVE
) return;
88 /* Refuse SYNC requests if we are a slave but the link with our master
90 if (server
.masterhost
&& server
.repl_state
!= REDIS_REPL_CONNECTED
) {
91 addReplyError(c
,"Can't SYNC while not connected with my master");
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");
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 */
115 listRewind(server
.slaves
,&li
);
116 while((ln
= listNext(&li
))) {
118 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) break;
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");
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");
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");
140 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
143 c
->flags
|= REDIS_SLAVE
;
145 listAddNodeTail(server
.slaves
,c
);
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.
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
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
161 void replconfCommand(redisClient
*c
) {
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
);
171 /* Process every option-value pair. */
172 for (j
= 1; j
< c
->argc
; j
+=2) {
173 if (!strcasecmp(c
->argv
[j
]->ptr
,"listening-port")) {
176 if ((getLongFromObjectOrReply(c
,c
->argv
[j
+1],
177 &port
,NULL
) != REDIS_OK
))
179 c
->slave_listening_port
= port
;
181 addReplyErrorFormat(c
,"Unrecognized REPLCONF option: %s",
182 (char*)c
->argv
[j
]->ptr
);
186 addReply(c
,shared
.ok
);
189 void sendBulkToSlave(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
190 redisClient
*slave
= privdata
;
193 char buf
[REDIS_IOBUF_LEN
];
194 ssize_t nwritten
, buflen
;
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. */
203 bulkcount
= sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
205 if (write(fd
,bulkcount
,sdslen(bulkcount
)) != (signed)sdslen(bulkcount
))
213 lseek(slave
->repldbfd
,slave
->repldboff
,SEEK_SET
);
214 buflen
= read(slave
->repldbfd
,buf
,REDIS_IOBUF_LEN
);
216 redisLog(REDIS_WARNING
,"Read error sending DB to slave: %s",
217 (buflen
== 0) ? "premature EOF" : strerror(errno
));
221 if ((nwritten
= write(fd
,buf
,buflen
)) == -1) {
222 redisLog(REDIS_VERBOSE
,"Write error sending DB to slave: %s",
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
) {
238 redisLog(REDIS_NOTICE
,"Synchronization with slave succeeded");
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.
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
) {
253 listRewind(server
.slaves
,&li
);
254 while((ln
= listNext(&li
))) {
255 redisClient
*slave
= ln
->value
;
257 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) {
259 slave
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
260 } else if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) {
261 struct redis_stat buf
;
263 if (bgsaveerr
!= REDIS_OK
) {
265 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE child returned an error");
268 if ((slave
->repldbfd
= open(server
.rdb_filename
,O_RDONLY
)) == -1 ||
269 redis_fstat(slave
->repldbfd
,&buf
) == -1) {
271 redisLog(REDIS_WARNING
,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno
));
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
) {
285 if (rdbSaveBackground(server
.rdb_filename
) != REDIS_OK
) {
288 listRewind(server
.slaves
,&li
);
289 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE failed");
290 while((ln
= listNext(&li
))) {
291 redisClient
*slave
= ln
->value
;
293 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
)
300 /* ----------------------------------- SLAVE -------------------------------- */
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
);
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
;
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
) {
318 ssize_t nread
, readlen
;
321 REDIS_NOTUSED(privdata
);
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",
335 redisLog(REDIS_WARNING
,
336 "MASTER aborted replication with an error: %s",
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
343 server
.repl_transfer_lastio
= server
.unixtime
;
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?");
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
);
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
);
361 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
362 (nread
== -1) ? strerror(errno
) : "connection lost");
363 replicationAbortSyncTransfer();
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
));
371 server
.repl_transfer_read
+= nread
;
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
376 if (server
.repl_transfer_read
>=
377 server
.repl_transfer_last_fsync_off
+ REPL_MAX_WRITTEN_BEFORE_FSYNC
)
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
;
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();
393 redisLog(REDIS_NOTICE
, "MASTER <-> SLAVE sync: Loading DB in memory");
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();
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
) {
420 while (retry
-- && startAppendOnly() == REDIS_ERR
) {
421 redisLog(REDIS_WARNING
,"Failed enabling the AOF after successful master synchrnization! Trying it again in one second.");
425 redisLog(REDIS_WARNING
,"FATAL: this slave instance finished the synchronization with its master, but the AOF can't be turned on. Exiting now.");
434 replicationAbortSyncTransfer();
438 /* Send a synchronous command to the master. Used to send AUTH and
439 * REPLCONF commands before starting the replication with SYNC.
441 * On success NULL is returned.
442 * On error an sds string describing the error is returned.
444 char *sendSynchronousCommand(int fd
, ...) {
446 sds cmd
= sdsempty();
449 /* Create the command to send to the master, we use simple inline
450 * protocol for simplicity as currently we only send simple strings. */
453 arg
= va_arg(ap
, char*);
454 if (arg
== NULL
) break;
456 if (sdslen(cmd
) != 0) cmd
= sdscatlen(cmd
," ",1);
457 cmd
= sdscat(cmd
,arg
);
459 cmd
= sdscatlen(cmd
,"\r\n",2);
461 /* Transfer command to the server. */
462 if (syncWrite(fd
,cmd
,sdslen(cmd
),server
.repl_syncio_timeout
*1000) == -1) {
464 return sdscatprintf(sdsempty(),"Writing to master: %s",
469 /* Read the reply from the server. */
470 if (syncReadLine(fd
,buf
,sizeof(buf
),server
.repl_syncio_timeout
*1000) == -1)
472 return sdscatprintf(sdsempty(),"Reading from master: %s",
476 /* Check for errors from the server. */
478 return sdscatprintf(sdsempty(),"Error from master: %s", buf
);
481 return NULL
; /* No errors. */
484 void syncWithMaster(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
485 char tmpfile
[256], *err
;
486 int dfd
, maxtries
= 5;
488 socklen_t errlen
= sizeof(sockerr
);
490 REDIS_NOTUSED(privdata
);
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
) {
500 /* Check for errors in the socket. */
501 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &sockerr
, &errlen
) == -1)
504 aeDeleteFileEvent(server
.el
,fd
,AE_READABLE
|AE_WRITABLE
);
505 redisLog(REDIS_WARNING
,"Error condition on socket for SYNC: %s",
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);
526 /* Receive the PONG command. */
527 if (server
.repl_state
== REDIS_REPL_RECEIVE_PONG
) {
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
);
534 /* Read the reply with explicit timeout. */
536 if (syncReadLine(fd
,buf
,sizeof(buf
),
537 server
.repl_syncio_timeout
*1000) == -1)
539 redisLog(REDIS_WARNING
,
540 "I/O error reading PING reply from master: %s",
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.");
552 redisLog(REDIS_NOTICE
,
553 "Master replied to PING, replication can continue...");
557 /* AUTH with the master if required. */
558 if(server
.masterauth
) {
559 err
= sendSynchronousCommand(fd
,"AUTH",server
.masterauth
,NULL
);
561 redisLog(REDIS_WARNING
,"Unable to AUTH to MASTER: %s",err
);
567 /* Set the slave port, so that Master's INFO command can list the
568 * slave listening port correctly. */
570 sds port
= sdsfromlonglong(server
.port
);
571 err
= sendSynchronousCommand(fd
,"REPLCONF","listening-port",port
,
574 /* Ignore the error if any, not all the Redis versions support
575 * REPLCONF listening-port. */
577 redisLog(REDIS_NOTICE
,"(non critical): Master does not understand REPLCONF listening-port: %s", err
);
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",
589 /* Prepare a suitable temp file for bulk transfer */
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;
598 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
602 /* Setup the non blocking download of the bulk file. */
603 if (aeCreateFileEvent(server
.el
,fd
, AE_READABLE
,readSyncBulkPayload
,NULL
)
606 redisLog(REDIS_WARNING
,"Can't create readable event for SYNC");
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
);
621 server
.repl_transfer_s
= -1;
622 server
.repl_state
= REDIS_REPL_CONNECT
;
626 int connectWithMaster(void) {
629 fd
= anetTcpNonBlockConnect(NULL
,server
.masterhost
,server
.masterport
);
631 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
636 if (aeCreateFileEvent(server
.el
,fd
,AE_READABLE
|AE_WRITABLE
,syncWithMaster
,NULL
) ==
640 redisLog(REDIS_WARNING
,"Can't create readable event for SYNC");
644 server
.repl_transfer_lastio
= server
.unixtime
;
645 server
.repl_transfer_s
= fd
;
646 server
.repl_state
= REDIS_REPL_CONNECTING
;
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
;
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
);
659 server
.repl_transfer_s
= -1;
660 server
.repl_state
= REDIS_REPL_CONNECT
;
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)");
681 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &port
, NULL
) != REDIS_OK
))
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"));
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
);
704 addReply(c
,shared
.ok
);
707 /* --------------------------- REPLICATION CRON ---------------------------- */
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
)
716 redisLog(REDIS_WARNING
,"Timeout connecting to the MASTER...");
717 undoConnectWithMaster();
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
)
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();
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
)
732 redisLog(REDIS_WARNING
,"MASTER time out: no data nor PING received...");
733 freeClient(server
.master
);
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");
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
))) {
752 listRewind(server
.slaves
,&li
);
753 while((ln
= listNext(&li
))) {
754 redisClient
*slave
= ln
->value
;
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"));
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. */