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