]> git.saurik.com Git - redis.git/blame - src/replication.c
Sentinel: reply -IDONTKNOW to get-master-addr-by-name on lack of info.
[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>
8b6b1b27 6#include <sys/socket.h>
e2641e09 7#include <sys/stat.h>
8
f4aa600b 9/* ---------------------------------- MASTER -------------------------------- */
10
e2641e09 11void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc) {
12 listNode *ln;
13 listIter li;
632e4c09 14 int j;
e2641e09 15
e2641e09 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
632e4c09
PN
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. */
e2641e09 26 if (slave->slaveseldb != dictid) {
27 robj *selectcmd;
28
ae15f750 29 if (dictid >= 0 && dictid < REDIS_SHARED_SELECT_CMDS) {
ae15f750 30 selectcmd = shared.select[dictid];
88bd32f1 31 incrRefCount(selectcmd);
ae15f750 32 } else {
e2641e09 33 selectcmd = createObject(REDIS_STRING,
34 sdscatprintf(sdsempty(),"select %d\r\n",dictid));
e2641e09 35 }
36 addReply(slave,selectcmd);
ae15f750 37 decrRefCount(selectcmd);
e2641e09 38 slave->slaveseldb = dictid;
39 }
632e4c09
PN
40 addReplyMultiBulkLen(slave,argc);
41 for (j = 0; j < argc; j++) addReplyBulk(slave,argv[j]);
e2641e09 42 }
e2641e09 43}
44
e31b615e 45void replicationFeedMonitors(redisClient *c, list *monitors, int dictid, robj **argv, int argc) {
e2641e09 46 listNode *ln;
47 listIter li;
e31b615e 48 int j, port;
e2641e09 49 sds cmdrepr = sdsnew("+");
50 robj *cmdobj;
e31b615e 51 char ip[32];
e2641e09 52 struct timeval tv;
53
54 gettimeofday(&tv,NULL);
2b2eca1f 55 cmdrepr = sdscatprintf(cmdrepr,"%ld.%06ld ",(long)tv.tv_sec,(long)tv.tv_usec);
e31b615e 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 }
e2641e09 62
63 for (j = 0; j < argc; j++) {
64 if (argv[j]->encoding == REDIS_ENCODING_INT) {
d3b958c3 65 cmdrepr = sdscatprintf(cmdrepr, "\"%ld\"", (long)argv[j]->ptr);
e2641e09 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
e2641e09 84void syncCommand(redisClient *c) {
85 /* ignore SYNC if aleady slave or in monitor mode */
86 if (c->flags & REDIS_SLAVE) return;
87
778b2210 88 /* Refuse SYNC requests if we are a slave but the link with our master
89 * is not ok... */
1844f990 90 if (server.masterhost && server.repl_state != REDIS_REPL_CONNECTED) {
3ab20376 91 addReplyError(c,"Can't SYNC while not connected with my master");
778b2210 92 return;
93 }
94
e2641e09 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) {
3ab20376 100 addReplyError(c,"SYNC is invalid with pending input");
e2641e09 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 */
f48cd4b9 107 if (server.rdb_child_pid != -1) {
e2641e09 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. */
1824e3a3 123 copyClientOutputBuffer(c,slave);
e2641e09 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");
f48cd4b9 135 if (rdbSaveBackground(server.rdb_filename) != REDIS_OK) {
e2641e09 136 redisLog(REDIS_NOTICE,"Replication failed, can't BGSAVE");
3ab20376 137 addReplyError(c,"Unable to perform background save");
e2641e09 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
dbd8c753 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. */
161void 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
e2641e09 189void 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 }
e2641e09 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. */
248void 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 }
f48cd4b9 268 if ((slave->repldbfd = open(server.rdb_filename,O_RDONLY)) == -1 ||
e2641e09 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) {
f48cd4b9 285 if (rdbSaveBackground(server.rdb_filename) != REDIS_OK) {
e2641e09 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
f4aa600b 300/* ----------------------------------- SLAVE -------------------------------- */
301
302/* Abort the async download of the bulk dataset while SYNC-ing with master */
303void replicationAbortSyncTransfer(void) {
1844f990 304 redisAssert(server.repl_state == REDIS_REPL_TRANSFER);
f4aa600b 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);
1844f990 311 server.repl_state = REDIS_REPL_CONNECT;
f4aa600b 312}
313
314/* Asynchronously read the SYNC payload we receive from a master */
13732168 315#define REPL_MAX_WRITTEN_BEFORE_FSYNC (1024*1024*8) /* 8 MB */
f4aa600b 316void readSyncBulkPayload(aeEventLoop *el, int fd, void *privdata, int mask) {
26b33669 317 char buf[4096];
62ec599c 318 ssize_t nread, readlen;
13732168 319 off_t left;
62ec599c 320 REDIS_NOTUSED(el);
321 REDIS_NOTUSED(privdata);
322 REDIS_NOTUSED(mask);
f4aa600b 323
13732168 324 /* If repl_transfer_size == -1 we still have to read the bulk length
26b33669 325 * from the master reply. */
13732168 326 if (server.repl_transfer_size == -1) {
fa34ba39 327 if (syncReadLine(fd,buf,1024,server.repl_syncio_timeout*1000) == -1) {
26b33669 328 redisLog(REDIS_WARNING,
329 "I/O error reading bulk count from MASTER: %s",
330 strerror(errno));
b075621f 331 goto error;
26b33669 332 }
b075621f 333
26b33669 334 if (buf[0] == '-') {
335 redisLog(REDIS_WARNING,
336 "MASTER aborted replication with an error: %s",
337 buf+1);
b075621f 338 goto error;
89a1433e 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. */
56ff70f8 343 server.repl_transfer_lastio = server.unixtime;
89a1433e 344 return;
26b33669 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?");
b075621f 347 goto error;
26b33669 348 }
13732168 349 server.repl_transfer_size = strtol(buf+1,NULL,10);
26b33669 350 redisLog(REDIS_NOTICE,
351 "MASTER <-> SLAVE sync: receiving %ld bytes from master",
13732168 352 server.repl_transfer_size);
26b33669 353 return;
354 }
355
356 /* Read bulk data */
13732168 357 left = server.repl_transfer_size - server.repl_transfer_read;
358 readlen = (left < (signed)sizeof(buf)) ? left : (signed)sizeof(buf);
f4aa600b 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 }
56ff70f8 366 server.repl_transfer_lastio = server.unixtime;
f4aa600b 367 if (write(server.repl_transfer_fd,buf,nread) != nread) {
8111a803 368 redisLog(REDIS_WARNING,"Write error or short write writing to the DB dump file needed for MASTER <-> SLAVE synchronization: %s", strerror(errno));
b075621f 369 goto error;
f4aa600b 370 }
13732168 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
f4aa600b 386 /* Check if the transfer is now complete */
13732168 387 if (server.repl_transfer_read == server.repl_transfer_size) {
f48cd4b9 388 if (rename(server.repl_transfer_tmpfile,server.rdb_filename) == -1) {
f4aa600b 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 }
f6433915 393 redisLog(REDIS_NOTICE, "MASTER <-> SLAVE sync: Loading DB in memory");
f4aa600b 394 emptyDb();
9fd01051 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);
f48cd4b9 400 if (rdbLoad(server.rdb_filename) != REDIS_OK) {
f4aa600b 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 */
f4aa600b 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;
1844f990 411 server.repl_state = REDIS_REPL_CONNECTED;
26b33669 412 redisLog(REDIS_NOTICE, "MASTER <-> SLAVE sync: Finished with success");
e7a2e7c1 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. */
e394114d 416 if (server.aof_state != REDIS_AOF_OFF) {
e7a2e7c1 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 }
f4aa600b 429 }
b075621f
PN
430
431 return;
432
433error:
434 replicationAbortSyncTransfer();
435 return;
f4aa600b 436}
437
dbd8c753 438/* Send a synchronous command to the master. Used to send AUTH and
d3d56742 439 * REPLCONF commands before starting the replication with SYNC.
dbd8c753 440 *
441 * On success NULL is returned.
442 * On error an sds string describing the error is returned.
443 */
444char *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
a3309139 484void syncWithMaster(aeEventLoop *el, int fd, void *privdata, int mask) {
dbd8c753 485 char tmpfile[256], *err;
e2641e09 486 int dfd, maxtries = 5;
fd2a8951 487 int sockerr = 0;
488 socklen_t errlen = sizeof(sockerr);
a3309139
PN
489 REDIS_NOTUSED(el);
490 REDIS_NOTUSED(privdata);
491 REDIS_NOTUSED(mask);
e2641e09 492
76e772f3 493 /* If this event fired after the user turned the instance into a master
494 * with SLAVEOF NO ONE we must just return ASAP. */
1844f990 495 if (server.repl_state == REDIS_REPL_NONE) {
76e772f3 496 close(fd);
497 return;
498 }
499
fd2a8951 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 }
e2641e09 556
557 /* AUTH with the master if required. */
558 if(server.masterauth) {
dbd8c753 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);
a3309139
PN
563 goto error;
564 }
dbd8c753 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);
e2641e09 579 }
580 }
581
582 /* Issue the SYNC command */
9b43b1ef 583 if (syncWrite(fd,"SYNC\r\n",6,server.repl_syncio_timeout*1000) == -1) {
e2641e09 584 redisLog(REDIS_WARNING,"I/O error writing to MASTER: %s",
585 strerror(errno));
a3309139 586 goto error;
e2641e09 587 }
26b33669 588
589 /* Prepare a suitable temp file for bulk transfer */
e2641e09 590 while(maxtries--) {
591 snprintf(tmpfile,256,
56ff70f8 592 "temp-%d.%ld.rdb",(int)server.unixtime,(long int)getpid());
e2641e09 593 dfd = open(tmpfile,O_CREAT|O_WRONLY|O_EXCL,0644);
594 if (dfd != -1) break;
595 sleep(1);
596 }
597 if (dfd == -1) {
e2641e09 598 redisLog(REDIS_WARNING,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno));
a3309139 599 goto error;
e2641e09 600 }
e2641e09 601
f4aa600b 602 /* Setup the non blocking download of the bulk file. */
a3309139 603 if (aeCreateFileEvent(server.el,fd, AE_READABLE,readSyncBulkPayload,NULL)
62ec599c 604 == AE_ERR)
f4aa600b 605 {
f4aa600b 606 redisLog(REDIS_WARNING,"Can't create readable event for SYNC");
a3309139 607 goto error;
e2641e09 608 }
a3309139 609
1844f990 610 server.repl_state = REDIS_REPL_TRANSFER;
13732168 611 server.repl_transfer_size = -1;
612 server.repl_transfer_read = 0;
613 server.repl_transfer_last_fsync_off = 0;
f4aa600b 614 server.repl_transfer_fd = dfd;
56ff70f8 615 server.repl_transfer_lastio = server.unixtime;
f4aa600b 616 server.repl_transfer_tmpfile = zstrdup(tmpfile);
a3309139
PN
617 return;
618
619error:
a3309139 620 close(fd);
fd2a8951 621 server.repl_transfer_s = -1;
622 server.repl_state = REDIS_REPL_CONNECT;
a3309139
PN
623 return;
624}
625
626int 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
45029d37 636 if (aeCreateFileEvent(server.el,fd,AE_READABLE|AE_WRITABLE,syncWithMaster,NULL) ==
b075621f 637 AE_ERR)
a3309139
PN
638 {
639 close(fd);
640 redisLog(REDIS_WARNING,"Can't create readable event for SYNC");
641 return REDIS_ERR;
642 }
643
56ff70f8 644 server.repl_transfer_lastio = server.unixtime;
a3309139 645 server.repl_transfer_s = fd;
1844f990 646 server.repl_state = REDIS_REPL_CONNECTING;
e2641e09 647 return REDIS_OK;
648}
649
27acd7aa 650/* This function can be called when a non blocking connection is currently
651 * in progress to undo it. */
652void undoConnectWithMaster(void) {
653 int fd = server.repl_transfer_s;
654
fd2a8951 655 redisAssert(server.repl_state == REDIS_REPL_CONNECTING ||
656 server.repl_state == REDIS_REPL_RECEIVE_PONG);
27acd7aa 657 aeDeleteFileEvent(server.el,fd,AE_READABLE|AE_WRITABLE);
658 close(fd);
659 server.repl_transfer_s = -1;
1844f990 660 server.repl_state = REDIS_REPL_CONNECT;
27acd7aa 661}
662
e2641e09 663void 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);
1844f990 670 if (server.repl_state == REDIS_REPL_TRANSFER)
f4aa600b 671 replicationAbortSyncTransfer();
fd2a8951 672 else if (server.repl_state == REDIS_REPL_CONNECTING ||
673 server.repl_state == REDIS_REPL_RECEIVE_PONG)
27acd7aa 674 undoConnectWithMaster();
1844f990 675 server.repl_state = REDIS_REPL_NONE;
e2641e09 676 redisLog(REDIS_NOTICE,"MASTER MODE enabled (user request)");
677 }
678 } else {
ebdfad69 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. */
e2641e09 693 sdsfree(server.masterhost);
694 server.masterhost = sdsdup(c->argv[1]->ptr);
ebdfad69 695 server.masterport = port;
e2641e09 696 if (server.master) freeClient(server.master);
ed4d4f11 697 disconnectSlaves(); /* Force our slaves to resync with us as well. */
1844f990 698 if (server.repl_state == REDIS_REPL_TRANSFER)
f4aa600b 699 replicationAbortSyncTransfer();
1844f990 700 server.repl_state = REDIS_REPL_CONNECT;
e2641e09 701 redisLog(REDIS_NOTICE,"SLAVE OF %s:%d enabled (user request)",
702 server.masterhost, server.masterport);
703 }
704 addReply(c,shared.ok);
705}
f4aa600b 706
707/* --------------------------- REPLICATION CRON ---------------------------- */
708
f4aa600b 709void replicationCron(void) {
27acd7aa 710 /* Non blocking connection timeout? */
fd2a8951 711 if (server.masterhost &&
712 (server.repl_state == REDIS_REPL_CONNECTING ||
713 server.repl_state == REDIS_REPL_RECEIVE_PONG) &&
27acd7aa 714 (time(NULL)-server.repl_transfer_lastio) > server.repl_timeout)
715 {
716 redisLog(REDIS_WARNING,"Timeout connecting to the MASTER...");
717 undoConnectWithMaster();
718 }
719
f4aa600b 720 /* Bulk transfer I/O timeout? */
1844f990 721 if (server.masterhost && server.repl_state == REDIS_REPL_TRANSFER &&
8996bf77 722 (time(NULL)-server.repl_transfer_lastio) > server.repl_timeout)
f4aa600b 723 {
724 redisLog(REDIS_WARNING,"Timeout receiving bulk data from MASTER...");
725 replicationAbortSyncTransfer();
726 }
727
89a1433e 728 /* Timed out master when we are an already connected slave? */
1844f990 729 if (server.masterhost && server.repl_state == REDIS_REPL_CONNECTED &&
8996bf77 730 (time(NULL)-server.master->lastinteraction) > server.repl_timeout)
89a1433e 731 {
732 redisLog(REDIS_WARNING,"MASTER time out: no data nor PING received...");
733 freeClient(server.master);
734 }
735
f4aa600b 736 /* Check if we should connect to a MASTER */
1844f990 737 if (server.repl_state == REDIS_REPL_CONNECT) {
f4aa600b 738 redisLog(REDIS_NOTICE,"Connecting to MASTER...");
a3309139
PN
739 if (connectWithMaster() == REDIS_OK) {
740 redisLog(REDIS_NOTICE,"MASTER <-> SLAVE sync started");
f4aa600b 741 }
742 }
89a1433e 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. */
0671d88c 748 if (!(server.cronloops % (server.repl_ping_slave_period * REDIS_HZ))) {
89a1433e 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 */
a950a843 761 addReplySds(slave,sdsnew("*1\r\n$4\r\nPING\r\n"));
89a1433e 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. */
f96a9f82 768 if (write(slave->fd, "\n", 1) == -1) {
769 /* Don't worry, it's just a ping. */
770 }
89a1433e 771 }
772 }
773 }
f4aa600b 774}