xref: /f-stack/app/redis-5.0.5/src/replication.c (revision 572c4311)
1*572c4311Sfengbojiang /* Asynchronous replication implementation.
2*572c4311Sfengbojiang  *
3*572c4311Sfengbojiang  * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
4*572c4311Sfengbojiang  * All rights reserved.
5*572c4311Sfengbojiang  *
6*572c4311Sfengbojiang  * Redistribution and use in source and binary forms, with or without
7*572c4311Sfengbojiang  * modification, are permitted provided that the following conditions are met:
8*572c4311Sfengbojiang  *
9*572c4311Sfengbojiang  *   * Redistributions of source code must retain the above copyright notice,
10*572c4311Sfengbojiang  *     this list of conditions and the following disclaimer.
11*572c4311Sfengbojiang  *   * Redistributions in binary form must reproduce the above copyright
12*572c4311Sfengbojiang  *     notice, this list of conditions and the following disclaimer in the
13*572c4311Sfengbojiang  *     documentation and/or other materials provided with the distribution.
14*572c4311Sfengbojiang  *   * Neither the name of Redis nor the names of its contributors may be used
15*572c4311Sfengbojiang  *     to endorse or promote products derived from this software without
16*572c4311Sfengbojiang  *     specific prior written permission.
17*572c4311Sfengbojiang  *
18*572c4311Sfengbojiang  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19*572c4311Sfengbojiang  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20*572c4311Sfengbojiang  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21*572c4311Sfengbojiang  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22*572c4311Sfengbojiang  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23*572c4311Sfengbojiang  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24*572c4311Sfengbojiang  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25*572c4311Sfengbojiang  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26*572c4311Sfengbojiang  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27*572c4311Sfengbojiang  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28*572c4311Sfengbojiang  * POSSIBILITY OF SUCH DAMAGE.
29*572c4311Sfengbojiang  */
30*572c4311Sfengbojiang 
31*572c4311Sfengbojiang 
32*572c4311Sfengbojiang #include "server.h"
33*572c4311Sfengbojiang #include "cluster.h"
34*572c4311Sfengbojiang 
35*572c4311Sfengbojiang #include <sys/time.h>
36*572c4311Sfengbojiang #include <unistd.h>
37*572c4311Sfengbojiang #include <fcntl.h>
38*572c4311Sfengbojiang #include <sys/socket.h>
39*572c4311Sfengbojiang #include <sys/stat.h>
40*572c4311Sfengbojiang 
41*572c4311Sfengbojiang void replicationDiscardCachedMaster(void);
42*572c4311Sfengbojiang void replicationResurrectCachedMaster(int newfd);
43*572c4311Sfengbojiang void replicationSendAck(void);
44*572c4311Sfengbojiang void putSlaveOnline(client *slave);
45*572c4311Sfengbojiang int cancelReplicationHandshake(void);
46*572c4311Sfengbojiang 
47*572c4311Sfengbojiang /* --------------------------- Utility functions ---------------------------- */
48*572c4311Sfengbojiang 
49*572c4311Sfengbojiang /* Return the pointer to a string representing the slave ip:listening_port
50*572c4311Sfengbojiang  * pair. Mostly useful for logging, since we want to log a slave using its
51*572c4311Sfengbojiang  * IP address and its listening port which is more clear for the user, for
52*572c4311Sfengbojiang  * example: "Closing connection with replica 10.1.2.3:6380". */
replicationGetSlaveName(client * c)53*572c4311Sfengbojiang char *replicationGetSlaveName(client *c) {
54*572c4311Sfengbojiang     static char buf[NET_PEER_ID_LEN];
55*572c4311Sfengbojiang     char ip[NET_IP_STR_LEN];
56*572c4311Sfengbojiang 
57*572c4311Sfengbojiang     ip[0] = '\0';
58*572c4311Sfengbojiang     buf[0] = '\0';
59*572c4311Sfengbojiang     if (c->slave_ip[0] != '\0' ||
60*572c4311Sfengbojiang         anetPeerToString(c->fd,ip,sizeof(ip),NULL) != -1)
61*572c4311Sfengbojiang     {
62*572c4311Sfengbojiang         /* Note that the 'ip' buffer is always larger than 'c->slave_ip' */
63*572c4311Sfengbojiang         if (c->slave_ip[0] != '\0') memcpy(ip,c->slave_ip,sizeof(c->slave_ip));
64*572c4311Sfengbojiang 
65*572c4311Sfengbojiang         if (c->slave_listening_port)
66*572c4311Sfengbojiang             anetFormatAddr(buf,sizeof(buf),ip,c->slave_listening_port);
67*572c4311Sfengbojiang         else
68*572c4311Sfengbojiang             snprintf(buf,sizeof(buf),"%s:<unknown-replica-port>",ip);
69*572c4311Sfengbojiang     } else {
70*572c4311Sfengbojiang         snprintf(buf,sizeof(buf),"client id #%llu",
71*572c4311Sfengbojiang             (unsigned long long) c->id);
72*572c4311Sfengbojiang     }
73*572c4311Sfengbojiang     return buf;
74*572c4311Sfengbojiang }
75*572c4311Sfengbojiang 
76*572c4311Sfengbojiang /* ---------------------------------- MASTER -------------------------------- */
77*572c4311Sfengbojiang 
createReplicationBacklog(void)78*572c4311Sfengbojiang void createReplicationBacklog(void) {
79*572c4311Sfengbojiang     serverAssert(server.repl_backlog == NULL);
80*572c4311Sfengbojiang     server.repl_backlog = zmalloc(server.repl_backlog_size);
81*572c4311Sfengbojiang     server.repl_backlog_histlen = 0;
82*572c4311Sfengbojiang     server.repl_backlog_idx = 0;
83*572c4311Sfengbojiang 
84*572c4311Sfengbojiang     /* We don't have any data inside our buffer, but virtually the first
85*572c4311Sfengbojiang      * byte we have is the next byte that will be generated for the
86*572c4311Sfengbojiang      * replication stream. */
87*572c4311Sfengbojiang     server.repl_backlog_off = server.master_repl_offset+1;
88*572c4311Sfengbojiang }
89*572c4311Sfengbojiang 
90*572c4311Sfengbojiang /* This function is called when the user modifies the replication backlog
91*572c4311Sfengbojiang  * size at runtime. It is up to the function to both update the
92*572c4311Sfengbojiang  * server.repl_backlog_size and to resize the buffer and setup it so that
93*572c4311Sfengbojiang  * it contains the same data as the previous one (possibly less data, but
94*572c4311Sfengbojiang  * the most recent bytes, or the same data and more free space in case the
95*572c4311Sfengbojiang  * buffer is enlarged). */
resizeReplicationBacklog(long long newsize)96*572c4311Sfengbojiang void resizeReplicationBacklog(long long newsize) {
97*572c4311Sfengbojiang     if (newsize < CONFIG_REPL_BACKLOG_MIN_SIZE)
98*572c4311Sfengbojiang         newsize = CONFIG_REPL_BACKLOG_MIN_SIZE;
99*572c4311Sfengbojiang     if (server.repl_backlog_size == newsize) return;
100*572c4311Sfengbojiang 
101*572c4311Sfengbojiang     server.repl_backlog_size = newsize;
102*572c4311Sfengbojiang     if (server.repl_backlog != NULL) {
103*572c4311Sfengbojiang         /* What we actually do is to flush the old buffer and realloc a new
104*572c4311Sfengbojiang          * empty one. It will refill with new data incrementally.
105*572c4311Sfengbojiang          * The reason is that copying a few gigabytes adds latency and even
106*572c4311Sfengbojiang          * worse often we need to alloc additional space before freeing the
107*572c4311Sfengbojiang          * old buffer. */
108*572c4311Sfengbojiang         zfree(server.repl_backlog);
109*572c4311Sfengbojiang         server.repl_backlog = zmalloc(server.repl_backlog_size);
110*572c4311Sfengbojiang         server.repl_backlog_histlen = 0;
111*572c4311Sfengbojiang         server.repl_backlog_idx = 0;
112*572c4311Sfengbojiang         /* Next byte we have is... the next since the buffer is empty. */
113*572c4311Sfengbojiang         server.repl_backlog_off = server.master_repl_offset+1;
114*572c4311Sfengbojiang     }
115*572c4311Sfengbojiang }
116*572c4311Sfengbojiang 
freeReplicationBacklog(void)117*572c4311Sfengbojiang void freeReplicationBacklog(void) {
118*572c4311Sfengbojiang     serverAssert(listLength(server.slaves) == 0);
119*572c4311Sfengbojiang     zfree(server.repl_backlog);
120*572c4311Sfengbojiang     server.repl_backlog = NULL;
121*572c4311Sfengbojiang }
122*572c4311Sfengbojiang 
123*572c4311Sfengbojiang /* Add data to the replication backlog.
124*572c4311Sfengbojiang  * This function also increments the global replication offset stored at
125*572c4311Sfengbojiang  * server.master_repl_offset, because there is no case where we want to feed
126*572c4311Sfengbojiang  * the backlog without incrementing the offset. */
feedReplicationBacklog(void * ptr,size_t len)127*572c4311Sfengbojiang void feedReplicationBacklog(void *ptr, size_t len) {
128*572c4311Sfengbojiang     unsigned char *p = ptr;
129*572c4311Sfengbojiang 
130*572c4311Sfengbojiang     server.master_repl_offset += len;
131*572c4311Sfengbojiang 
132*572c4311Sfengbojiang     /* This is a circular buffer, so write as much data we can at every
133*572c4311Sfengbojiang      * iteration and rewind the "idx" index if we reach the limit. */
134*572c4311Sfengbojiang     while(len) {
135*572c4311Sfengbojiang         size_t thislen = server.repl_backlog_size - server.repl_backlog_idx;
136*572c4311Sfengbojiang         if (thislen > len) thislen = len;
137*572c4311Sfengbojiang         memcpy(server.repl_backlog+server.repl_backlog_idx,p,thislen);
138*572c4311Sfengbojiang         server.repl_backlog_idx += thislen;
139*572c4311Sfengbojiang         if (server.repl_backlog_idx == server.repl_backlog_size)
140*572c4311Sfengbojiang             server.repl_backlog_idx = 0;
141*572c4311Sfengbojiang         len -= thislen;
142*572c4311Sfengbojiang         p += thislen;
143*572c4311Sfengbojiang         server.repl_backlog_histlen += thislen;
144*572c4311Sfengbojiang     }
145*572c4311Sfengbojiang     if (server.repl_backlog_histlen > server.repl_backlog_size)
146*572c4311Sfengbojiang         server.repl_backlog_histlen = server.repl_backlog_size;
147*572c4311Sfengbojiang     /* Set the offset of the first byte we have in the backlog. */
148*572c4311Sfengbojiang     server.repl_backlog_off = server.master_repl_offset -
149*572c4311Sfengbojiang                               server.repl_backlog_histlen + 1;
150*572c4311Sfengbojiang }
151*572c4311Sfengbojiang 
152*572c4311Sfengbojiang /* Wrapper for feedReplicationBacklog() that takes Redis string objects
153*572c4311Sfengbojiang  * as input. */
feedReplicationBacklogWithObject(robj * o)154*572c4311Sfengbojiang void feedReplicationBacklogWithObject(robj *o) {
155*572c4311Sfengbojiang     char llstr[LONG_STR_SIZE];
156*572c4311Sfengbojiang     void *p;
157*572c4311Sfengbojiang     size_t len;
158*572c4311Sfengbojiang 
159*572c4311Sfengbojiang     if (o->encoding == OBJ_ENCODING_INT) {
160*572c4311Sfengbojiang         len = ll2string(llstr,sizeof(llstr),(long)o->ptr);
161*572c4311Sfengbojiang         p = llstr;
162*572c4311Sfengbojiang     } else {
163*572c4311Sfengbojiang         len = sdslen(o->ptr);
164*572c4311Sfengbojiang         p = o->ptr;
165*572c4311Sfengbojiang     }
166*572c4311Sfengbojiang     feedReplicationBacklog(p,len);
167*572c4311Sfengbojiang }
168*572c4311Sfengbojiang 
169*572c4311Sfengbojiang /* Propagate write commands to slaves, and populate the replication backlog
170*572c4311Sfengbojiang  * as well. This function is used if the instance is a master: we use
171*572c4311Sfengbojiang  * the commands received by our clients in order to create the replication
172*572c4311Sfengbojiang  * stream. Instead if the instance is a slave and has sub-slaves attached,
173*572c4311Sfengbojiang  * we use replicationFeedSlavesFromMaster() */
replicationFeedSlaves(list * slaves,int dictid,robj ** argv,int argc)174*572c4311Sfengbojiang void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc) {
175*572c4311Sfengbojiang     listNode *ln;
176*572c4311Sfengbojiang     listIter li;
177*572c4311Sfengbojiang     int j, len;
178*572c4311Sfengbojiang     char llstr[LONG_STR_SIZE];
179*572c4311Sfengbojiang 
180*572c4311Sfengbojiang     /* If the instance is not a top level master, return ASAP: we'll just proxy
181*572c4311Sfengbojiang      * the stream of data we receive from our master instead, in order to
182*572c4311Sfengbojiang      * propagate *identical* replication stream. In this way this slave can
183*572c4311Sfengbojiang      * advertise the same replication ID as the master (since it shares the
184*572c4311Sfengbojiang      * master replication history and has the same backlog and offsets). */
185*572c4311Sfengbojiang     if (server.masterhost != NULL) return;
186*572c4311Sfengbojiang 
187*572c4311Sfengbojiang     /* If there aren't slaves, and there is no backlog buffer to populate,
188*572c4311Sfengbojiang      * we can return ASAP. */
189*572c4311Sfengbojiang     if (server.repl_backlog == NULL && listLength(slaves) == 0) return;
190*572c4311Sfengbojiang 
191*572c4311Sfengbojiang     /* We can't have slaves attached and no backlog. */
192*572c4311Sfengbojiang     serverAssert(!(listLength(slaves) != 0 && server.repl_backlog == NULL));
193*572c4311Sfengbojiang 
194*572c4311Sfengbojiang     /* Send SELECT command to every slave if needed. */
195*572c4311Sfengbojiang     if (server.slaveseldb != dictid) {
196*572c4311Sfengbojiang         robj *selectcmd;
197*572c4311Sfengbojiang 
198*572c4311Sfengbojiang         /* For a few DBs we have pre-computed SELECT command. */
199*572c4311Sfengbojiang         if (dictid >= 0 && dictid < PROTO_SHARED_SELECT_CMDS) {
200*572c4311Sfengbojiang             selectcmd = shared.select[dictid];
201*572c4311Sfengbojiang         } else {
202*572c4311Sfengbojiang             int dictid_len;
203*572c4311Sfengbojiang 
204*572c4311Sfengbojiang             dictid_len = ll2string(llstr,sizeof(llstr),dictid);
205*572c4311Sfengbojiang             selectcmd = createObject(OBJ_STRING,
206*572c4311Sfengbojiang                 sdscatprintf(sdsempty(),
207*572c4311Sfengbojiang                 "*2\r\n$6\r\nSELECT\r\n$%d\r\n%s\r\n",
208*572c4311Sfengbojiang                 dictid_len, llstr));
209*572c4311Sfengbojiang         }
210*572c4311Sfengbojiang 
211*572c4311Sfengbojiang         /* Add the SELECT command into the backlog. */
212*572c4311Sfengbojiang         if (server.repl_backlog) feedReplicationBacklogWithObject(selectcmd);
213*572c4311Sfengbojiang 
214*572c4311Sfengbojiang         /* Send it to slaves. */
215*572c4311Sfengbojiang         listRewind(slaves,&li);
216*572c4311Sfengbojiang         while((ln = listNext(&li))) {
217*572c4311Sfengbojiang             client *slave = ln->value;
218*572c4311Sfengbojiang             if (slave->replstate == SLAVE_STATE_WAIT_BGSAVE_START) continue;
219*572c4311Sfengbojiang             addReply(slave,selectcmd);
220*572c4311Sfengbojiang         }
221*572c4311Sfengbojiang 
222*572c4311Sfengbojiang         if (dictid < 0 || dictid >= PROTO_SHARED_SELECT_CMDS)
223*572c4311Sfengbojiang             decrRefCount(selectcmd);
224*572c4311Sfengbojiang     }
225*572c4311Sfengbojiang     server.slaveseldb = dictid;
226*572c4311Sfengbojiang 
227*572c4311Sfengbojiang     /* Write the command to the replication backlog if any. */
228*572c4311Sfengbojiang     if (server.repl_backlog) {
229*572c4311Sfengbojiang         char aux[LONG_STR_SIZE+3];
230*572c4311Sfengbojiang 
231*572c4311Sfengbojiang         /* Add the multi bulk reply length. */
232*572c4311Sfengbojiang         aux[0] = '*';
233*572c4311Sfengbojiang         len = ll2string(aux+1,sizeof(aux)-1,argc);
234*572c4311Sfengbojiang         aux[len+1] = '\r';
235*572c4311Sfengbojiang         aux[len+2] = '\n';
236*572c4311Sfengbojiang         feedReplicationBacklog(aux,len+3);
237*572c4311Sfengbojiang 
238*572c4311Sfengbojiang         for (j = 0; j < argc; j++) {
239*572c4311Sfengbojiang             long objlen = stringObjectLen(argv[j]);
240*572c4311Sfengbojiang 
241*572c4311Sfengbojiang             /* We need to feed the buffer with the object as a bulk reply
242*572c4311Sfengbojiang              * not just as a plain string, so create the $..CRLF payload len
243*572c4311Sfengbojiang              * and add the final CRLF */
244*572c4311Sfengbojiang             aux[0] = '$';
245*572c4311Sfengbojiang             len = ll2string(aux+1,sizeof(aux)-1,objlen);
246*572c4311Sfengbojiang             aux[len+1] = '\r';
247*572c4311Sfengbojiang             aux[len+2] = '\n';
248*572c4311Sfengbojiang             feedReplicationBacklog(aux,len+3);
249*572c4311Sfengbojiang             feedReplicationBacklogWithObject(argv[j]);
250*572c4311Sfengbojiang             feedReplicationBacklog(aux+len+1,2);
251*572c4311Sfengbojiang         }
252*572c4311Sfengbojiang     }
253*572c4311Sfengbojiang 
254*572c4311Sfengbojiang     /* Write the command to every slave. */
255*572c4311Sfengbojiang     listRewind(slaves,&li);
256*572c4311Sfengbojiang     while((ln = listNext(&li))) {
257*572c4311Sfengbojiang         client *slave = ln->value;
258*572c4311Sfengbojiang 
259*572c4311Sfengbojiang         /* Don't feed slaves that are still waiting for BGSAVE to start */
260*572c4311Sfengbojiang         if (slave->replstate == SLAVE_STATE_WAIT_BGSAVE_START) continue;
261*572c4311Sfengbojiang 
262*572c4311Sfengbojiang         /* Feed slaves that are waiting for the initial SYNC (so these commands
263*572c4311Sfengbojiang          * are queued in the output buffer until the initial SYNC completes),
264*572c4311Sfengbojiang          * or are already in sync with the master. */
265*572c4311Sfengbojiang 
266*572c4311Sfengbojiang         /* Add the multi bulk length. */
267*572c4311Sfengbojiang         addReplyMultiBulkLen(slave,argc);
268*572c4311Sfengbojiang 
269*572c4311Sfengbojiang         /* Finally any additional argument that was not stored inside the
270*572c4311Sfengbojiang          * static buffer if any (from j to argc). */
271*572c4311Sfengbojiang         for (j = 0; j < argc; j++)
272*572c4311Sfengbojiang             addReplyBulk(slave,argv[j]);
273*572c4311Sfengbojiang     }
274*572c4311Sfengbojiang }
275*572c4311Sfengbojiang 
276*572c4311Sfengbojiang /* This function is used in order to proxy what we receive from our master
277*572c4311Sfengbojiang  * to our sub-slaves. */
278*572c4311Sfengbojiang #include <ctype.h>
replicationFeedSlavesFromMasterStream(list * slaves,char * buf,size_t buflen)279*572c4311Sfengbojiang void replicationFeedSlavesFromMasterStream(list *slaves, char *buf, size_t buflen) {
280*572c4311Sfengbojiang     listNode *ln;
281*572c4311Sfengbojiang     listIter li;
282*572c4311Sfengbojiang 
283*572c4311Sfengbojiang     /* Debugging: this is handy to see the stream sent from master
284*572c4311Sfengbojiang      * to slaves. Disabled with if(0). */
285*572c4311Sfengbojiang     if (0) {
286*572c4311Sfengbojiang         printf("%zu:",buflen);
287*572c4311Sfengbojiang         for (size_t j = 0; j < buflen; j++) {
288*572c4311Sfengbojiang             printf("%c", isprint(buf[j]) ? buf[j] : '.');
289*572c4311Sfengbojiang         }
290*572c4311Sfengbojiang         printf("\n");
291*572c4311Sfengbojiang     }
292*572c4311Sfengbojiang 
293*572c4311Sfengbojiang     if (server.repl_backlog) feedReplicationBacklog(buf,buflen);
294*572c4311Sfengbojiang     listRewind(slaves,&li);
295*572c4311Sfengbojiang     while((ln = listNext(&li))) {
296*572c4311Sfengbojiang         client *slave = ln->value;
297*572c4311Sfengbojiang 
298*572c4311Sfengbojiang         /* Don't feed slaves that are still waiting for BGSAVE to start */
299*572c4311Sfengbojiang         if (slave->replstate == SLAVE_STATE_WAIT_BGSAVE_START) continue;
300*572c4311Sfengbojiang         addReplyString(slave,buf,buflen);
301*572c4311Sfengbojiang     }
302*572c4311Sfengbojiang }
303*572c4311Sfengbojiang 
replicationFeedMonitors(client * c,list * monitors,int dictid,robj ** argv,int argc)304*572c4311Sfengbojiang void replicationFeedMonitors(client *c, list *monitors, int dictid, robj **argv, int argc) {
305*572c4311Sfengbojiang     listNode *ln;
306*572c4311Sfengbojiang     listIter li;
307*572c4311Sfengbojiang     int j;
308*572c4311Sfengbojiang     sds cmdrepr = sdsnew("+");
309*572c4311Sfengbojiang     robj *cmdobj;
310*572c4311Sfengbojiang     struct timeval tv;
311*572c4311Sfengbojiang 
312*572c4311Sfengbojiang     gettimeofday(&tv,NULL);
313*572c4311Sfengbojiang     cmdrepr = sdscatprintf(cmdrepr,"%ld.%06ld ",(long)tv.tv_sec,(long)tv.tv_usec);
314*572c4311Sfengbojiang     if (c->flags & CLIENT_LUA) {
315*572c4311Sfengbojiang         cmdrepr = sdscatprintf(cmdrepr,"[%d lua] ",dictid);
316*572c4311Sfengbojiang     } else if (c->flags & CLIENT_UNIX_SOCKET) {
317*572c4311Sfengbojiang         cmdrepr = sdscatprintf(cmdrepr,"[%d unix:%s] ",dictid,server.unixsocket);
318*572c4311Sfengbojiang     } else {
319*572c4311Sfengbojiang         cmdrepr = sdscatprintf(cmdrepr,"[%d %s] ",dictid,getClientPeerId(c));
320*572c4311Sfengbojiang     }
321*572c4311Sfengbojiang 
322*572c4311Sfengbojiang     for (j = 0; j < argc; j++) {
323*572c4311Sfengbojiang         if (argv[j]->encoding == OBJ_ENCODING_INT) {
324*572c4311Sfengbojiang             cmdrepr = sdscatprintf(cmdrepr, "\"%ld\"", (long)argv[j]->ptr);
325*572c4311Sfengbojiang         } else {
326*572c4311Sfengbojiang             cmdrepr = sdscatrepr(cmdrepr,(char*)argv[j]->ptr,
327*572c4311Sfengbojiang                         sdslen(argv[j]->ptr));
328*572c4311Sfengbojiang         }
329*572c4311Sfengbojiang         if (j != argc-1)
330*572c4311Sfengbojiang             cmdrepr = sdscatlen(cmdrepr," ",1);
331*572c4311Sfengbojiang     }
332*572c4311Sfengbojiang     cmdrepr = sdscatlen(cmdrepr,"\r\n",2);
333*572c4311Sfengbojiang     cmdobj = createObject(OBJ_STRING,cmdrepr);
334*572c4311Sfengbojiang 
335*572c4311Sfengbojiang     listRewind(monitors,&li);
336*572c4311Sfengbojiang     while((ln = listNext(&li))) {
337*572c4311Sfengbojiang         client *monitor = ln->value;
338*572c4311Sfengbojiang         addReply(monitor,cmdobj);
339*572c4311Sfengbojiang     }
340*572c4311Sfengbojiang     decrRefCount(cmdobj);
341*572c4311Sfengbojiang }
342*572c4311Sfengbojiang 
343*572c4311Sfengbojiang /* Feed the slave 'c' with the replication backlog starting from the
344*572c4311Sfengbojiang  * specified 'offset' up to the end of the backlog. */
addReplyReplicationBacklog(client * c,long long offset)345*572c4311Sfengbojiang long long addReplyReplicationBacklog(client *c, long long offset) {
346*572c4311Sfengbojiang     long long j, skip, len;
347*572c4311Sfengbojiang 
348*572c4311Sfengbojiang     serverLog(LL_DEBUG, "[PSYNC] Replica request offset: %lld", offset);
349*572c4311Sfengbojiang 
350*572c4311Sfengbojiang     if (server.repl_backlog_histlen == 0) {
351*572c4311Sfengbojiang         serverLog(LL_DEBUG, "[PSYNC] Backlog history len is zero");
352*572c4311Sfengbojiang         return 0;
353*572c4311Sfengbojiang     }
354*572c4311Sfengbojiang 
355*572c4311Sfengbojiang     serverLog(LL_DEBUG, "[PSYNC] Backlog size: %lld",
356*572c4311Sfengbojiang              server.repl_backlog_size);
357*572c4311Sfengbojiang     serverLog(LL_DEBUG, "[PSYNC] First byte: %lld",
358*572c4311Sfengbojiang              server.repl_backlog_off);
359*572c4311Sfengbojiang     serverLog(LL_DEBUG, "[PSYNC] History len: %lld",
360*572c4311Sfengbojiang              server.repl_backlog_histlen);
361*572c4311Sfengbojiang     serverLog(LL_DEBUG, "[PSYNC] Current index: %lld",
362*572c4311Sfengbojiang              server.repl_backlog_idx);
363*572c4311Sfengbojiang 
364*572c4311Sfengbojiang     /* Compute the amount of bytes we need to discard. */
365*572c4311Sfengbojiang     skip = offset - server.repl_backlog_off;
366*572c4311Sfengbojiang     serverLog(LL_DEBUG, "[PSYNC] Skipping: %lld", skip);
367*572c4311Sfengbojiang 
368*572c4311Sfengbojiang     /* Point j to the oldest byte, that is actually our
369*572c4311Sfengbojiang      * server.repl_backlog_off byte. */
370*572c4311Sfengbojiang     j = (server.repl_backlog_idx +
371*572c4311Sfengbojiang         (server.repl_backlog_size-server.repl_backlog_histlen)) %
372*572c4311Sfengbojiang         server.repl_backlog_size;
373*572c4311Sfengbojiang     serverLog(LL_DEBUG, "[PSYNC] Index of first byte: %lld", j);
374*572c4311Sfengbojiang 
375*572c4311Sfengbojiang     /* Discard the amount of data to seek to the specified 'offset'. */
376*572c4311Sfengbojiang     j = (j + skip) % server.repl_backlog_size;
377*572c4311Sfengbojiang 
378*572c4311Sfengbojiang     /* Feed slave with data. Since it is a circular buffer we have to
379*572c4311Sfengbojiang      * split the reply in two parts if we are cross-boundary. */
380*572c4311Sfengbojiang     len = server.repl_backlog_histlen - skip;
381*572c4311Sfengbojiang     serverLog(LL_DEBUG, "[PSYNC] Reply total length: %lld", len);
382*572c4311Sfengbojiang     while(len) {
383*572c4311Sfengbojiang         long long thislen =
384*572c4311Sfengbojiang             ((server.repl_backlog_size - j) < len) ?
385*572c4311Sfengbojiang             (server.repl_backlog_size - j) : len;
386*572c4311Sfengbojiang 
387*572c4311Sfengbojiang         serverLog(LL_DEBUG, "[PSYNC] addReply() length: %lld", thislen);
388*572c4311Sfengbojiang         addReplySds(c,sdsnewlen(server.repl_backlog + j, thislen));
389*572c4311Sfengbojiang         len -= thislen;
390*572c4311Sfengbojiang         j = 0;
391*572c4311Sfengbojiang     }
392*572c4311Sfengbojiang     return server.repl_backlog_histlen - skip;
393*572c4311Sfengbojiang }
394*572c4311Sfengbojiang 
395*572c4311Sfengbojiang /* Return the offset to provide as reply to the PSYNC command received
396*572c4311Sfengbojiang  * from the slave. The returned value is only valid immediately after
397*572c4311Sfengbojiang  * the BGSAVE process started and before executing any other command
398*572c4311Sfengbojiang  * from clients. */
getPsyncInitialOffset(void)399*572c4311Sfengbojiang long long getPsyncInitialOffset(void) {
400*572c4311Sfengbojiang     return server.master_repl_offset;
401*572c4311Sfengbojiang }
402*572c4311Sfengbojiang 
403*572c4311Sfengbojiang /* Send a FULLRESYNC reply in the specific case of a full resynchronization,
404*572c4311Sfengbojiang  * as a side effect setup the slave for a full sync in different ways:
405*572c4311Sfengbojiang  *
406*572c4311Sfengbojiang  * 1) Remember, into the slave client structure, the replication offset
407*572c4311Sfengbojiang  *    we sent here, so that if new slaves will later attach to the same
408*572c4311Sfengbojiang  *    background RDB saving process (by duplicating this client output
409*572c4311Sfengbojiang  *    buffer), we can get the right offset from this slave.
410*572c4311Sfengbojiang  * 2) Set the replication state of the slave to WAIT_BGSAVE_END so that
411*572c4311Sfengbojiang  *    we start accumulating differences from this point.
412*572c4311Sfengbojiang  * 3) Force the replication stream to re-emit a SELECT statement so
413*572c4311Sfengbojiang  *    the new slave incremental differences will start selecting the
414*572c4311Sfengbojiang  *    right database number.
415*572c4311Sfengbojiang  *
416*572c4311Sfengbojiang  * Normally this function should be called immediately after a successful
417*572c4311Sfengbojiang  * BGSAVE for replication was started, or when there is one already in
418*572c4311Sfengbojiang  * progress that we attached our slave to. */
replicationSetupSlaveForFullResync(client * slave,long long offset)419*572c4311Sfengbojiang int replicationSetupSlaveForFullResync(client *slave, long long offset) {
420*572c4311Sfengbojiang     char buf[128];
421*572c4311Sfengbojiang     int buflen;
422*572c4311Sfengbojiang 
423*572c4311Sfengbojiang     slave->psync_initial_offset = offset;
424*572c4311Sfengbojiang     slave->replstate = SLAVE_STATE_WAIT_BGSAVE_END;
425*572c4311Sfengbojiang     /* We are going to accumulate the incremental changes for this
426*572c4311Sfengbojiang      * slave as well. Set slaveseldb to -1 in order to force to re-emit
427*572c4311Sfengbojiang      * a SELECT statement in the replication stream. */
428*572c4311Sfengbojiang     server.slaveseldb = -1;
429*572c4311Sfengbojiang 
430*572c4311Sfengbojiang     /* Don't send this reply to slaves that approached us with
431*572c4311Sfengbojiang      * the old SYNC command. */
432*572c4311Sfengbojiang     if (!(slave->flags & CLIENT_PRE_PSYNC)) {
433*572c4311Sfengbojiang         buflen = snprintf(buf,sizeof(buf),"+FULLRESYNC %s %lld\r\n",
434*572c4311Sfengbojiang                           server.replid,offset);
435*572c4311Sfengbojiang         if (write(slave->fd,buf,buflen) != buflen) {
436*572c4311Sfengbojiang             freeClientAsync(slave);
437*572c4311Sfengbojiang             return C_ERR;
438*572c4311Sfengbojiang         }
439*572c4311Sfengbojiang     }
440*572c4311Sfengbojiang     return C_OK;
441*572c4311Sfengbojiang }
442*572c4311Sfengbojiang 
443*572c4311Sfengbojiang /* This function handles the PSYNC command from the point of view of a
444*572c4311Sfengbojiang  * master receiving a request for partial resynchronization.
445*572c4311Sfengbojiang  *
446*572c4311Sfengbojiang  * On success return C_OK, otherwise C_ERR is returned and we proceed
447*572c4311Sfengbojiang  * with the usual full resync. */
masterTryPartialResynchronization(client * c)448*572c4311Sfengbojiang int masterTryPartialResynchronization(client *c) {
449*572c4311Sfengbojiang     long long psync_offset, psync_len;
450*572c4311Sfengbojiang     char *master_replid = c->argv[1]->ptr;
451*572c4311Sfengbojiang     char buf[128];
452*572c4311Sfengbojiang     int buflen;
453*572c4311Sfengbojiang 
454*572c4311Sfengbojiang     /* Parse the replication offset asked by the slave. Go to full sync
455*572c4311Sfengbojiang      * on parse error: this should never happen but we try to handle
456*572c4311Sfengbojiang      * it in a robust way compared to aborting. */
457*572c4311Sfengbojiang     if (getLongLongFromObjectOrReply(c,c->argv[2],&psync_offset,NULL) !=
458*572c4311Sfengbojiang        C_OK) goto need_full_resync;
459*572c4311Sfengbojiang 
460*572c4311Sfengbojiang     /* Is the replication ID of this master the same advertised by the wannabe
461*572c4311Sfengbojiang      * slave via PSYNC? If the replication ID changed this master has a
462*572c4311Sfengbojiang      * different replication history, and there is no way to continue.
463*572c4311Sfengbojiang      *
464*572c4311Sfengbojiang      * Note that there are two potentially valid replication IDs: the ID1
465*572c4311Sfengbojiang      * and the ID2. The ID2 however is only valid up to a specific offset. */
466*572c4311Sfengbojiang     if (strcasecmp(master_replid, server.replid) &&
467*572c4311Sfengbojiang         (strcasecmp(master_replid, server.replid2) ||
468*572c4311Sfengbojiang          psync_offset > server.second_replid_offset))
469*572c4311Sfengbojiang     {
470*572c4311Sfengbojiang         /* Run id "?" is used by slaves that want to force a full resync. */
471*572c4311Sfengbojiang         if (master_replid[0] != '?') {
472*572c4311Sfengbojiang             if (strcasecmp(master_replid, server.replid) &&
473*572c4311Sfengbojiang                 strcasecmp(master_replid, server.replid2))
474*572c4311Sfengbojiang             {
475*572c4311Sfengbojiang                 serverLog(LL_NOTICE,"Partial resynchronization not accepted: "
476*572c4311Sfengbojiang                     "Replication ID mismatch (Replica asked for '%s', my "
477*572c4311Sfengbojiang                     "replication IDs are '%s' and '%s')",
478*572c4311Sfengbojiang                     master_replid, server.replid, server.replid2);
479*572c4311Sfengbojiang             } else {
480*572c4311Sfengbojiang                 serverLog(LL_NOTICE,"Partial resynchronization not accepted: "
481*572c4311Sfengbojiang                     "Requested offset for second ID was %lld, but I can reply "
482*572c4311Sfengbojiang                     "up to %lld", psync_offset, server.second_replid_offset);
483*572c4311Sfengbojiang             }
484*572c4311Sfengbojiang         } else {
485*572c4311Sfengbojiang             serverLog(LL_NOTICE,"Full resync requested by replica %s",
486*572c4311Sfengbojiang                 replicationGetSlaveName(c));
487*572c4311Sfengbojiang         }
488*572c4311Sfengbojiang         goto need_full_resync;
489*572c4311Sfengbojiang     }
490*572c4311Sfengbojiang 
491*572c4311Sfengbojiang     /* We still have the data our slave is asking for? */
492*572c4311Sfengbojiang     if (!server.repl_backlog ||
493*572c4311Sfengbojiang         psync_offset < server.repl_backlog_off ||
494*572c4311Sfengbojiang         psync_offset > (server.repl_backlog_off + server.repl_backlog_histlen))
495*572c4311Sfengbojiang     {
496*572c4311Sfengbojiang         serverLog(LL_NOTICE,
497*572c4311Sfengbojiang             "Unable to partial resync with replica %s for lack of backlog (Replica request was: %lld).", replicationGetSlaveName(c), psync_offset);
498*572c4311Sfengbojiang         if (psync_offset > server.master_repl_offset) {
499*572c4311Sfengbojiang             serverLog(LL_WARNING,
500*572c4311Sfengbojiang                 "Warning: replica %s tried to PSYNC with an offset that is greater than the master replication offset.", replicationGetSlaveName(c));
501*572c4311Sfengbojiang         }
502*572c4311Sfengbojiang         goto need_full_resync;
503*572c4311Sfengbojiang     }
504*572c4311Sfengbojiang 
505*572c4311Sfengbojiang     /* If we reached this point, we are able to perform a partial resync:
506*572c4311Sfengbojiang      * 1) Set client state to make it a slave.
507*572c4311Sfengbojiang      * 2) Inform the client we can continue with +CONTINUE
508*572c4311Sfengbojiang      * 3) Send the backlog data (from the offset to the end) to the slave. */
509*572c4311Sfengbojiang     c->flags |= CLIENT_SLAVE;
510*572c4311Sfengbojiang     c->replstate = SLAVE_STATE_ONLINE;
511*572c4311Sfengbojiang     c->repl_ack_time = server.unixtime;
512*572c4311Sfengbojiang     c->repl_put_online_on_ack = 0;
513*572c4311Sfengbojiang     listAddNodeTail(server.slaves,c);
514*572c4311Sfengbojiang     /* We can't use the connection buffers since they are used to accumulate
515*572c4311Sfengbojiang      * new commands at this stage. But we are sure the socket send buffer is
516*572c4311Sfengbojiang      * empty so this write will never fail actually. */
517*572c4311Sfengbojiang     if (c->slave_capa & SLAVE_CAPA_PSYNC2) {
518*572c4311Sfengbojiang         buflen = snprintf(buf,sizeof(buf),"+CONTINUE %s\r\n", server.replid);
519*572c4311Sfengbojiang     } else {
520*572c4311Sfengbojiang         buflen = snprintf(buf,sizeof(buf),"+CONTINUE\r\n");
521*572c4311Sfengbojiang     }
522*572c4311Sfengbojiang     if (write(c->fd,buf,buflen) != buflen) {
523*572c4311Sfengbojiang         freeClientAsync(c);
524*572c4311Sfengbojiang         return C_OK;
525*572c4311Sfengbojiang     }
526*572c4311Sfengbojiang     psync_len = addReplyReplicationBacklog(c,psync_offset);
527*572c4311Sfengbojiang     serverLog(LL_NOTICE,
528*572c4311Sfengbojiang         "Partial resynchronization request from %s accepted. Sending %lld bytes of backlog starting from offset %lld.",
529*572c4311Sfengbojiang             replicationGetSlaveName(c),
530*572c4311Sfengbojiang             psync_len, psync_offset);
531*572c4311Sfengbojiang     /* Note that we don't need to set the selected DB at server.slaveseldb
532*572c4311Sfengbojiang      * to -1 to force the master to emit SELECT, since the slave already
533*572c4311Sfengbojiang      * has this state from the previous connection with the master. */
534*572c4311Sfengbojiang 
535*572c4311Sfengbojiang     refreshGoodSlavesCount();
536*572c4311Sfengbojiang     return C_OK; /* The caller can return, no full resync needed. */
537*572c4311Sfengbojiang 
538*572c4311Sfengbojiang need_full_resync:
539*572c4311Sfengbojiang     /* We need a full resync for some reason... Note that we can't
540*572c4311Sfengbojiang      * reply to PSYNC right now if a full SYNC is needed. The reply
541*572c4311Sfengbojiang      * must include the master offset at the time the RDB file we transfer
542*572c4311Sfengbojiang      * is generated, so we need to delay the reply to that moment. */
543*572c4311Sfengbojiang     return C_ERR;
544*572c4311Sfengbojiang }
545*572c4311Sfengbojiang 
546*572c4311Sfengbojiang /* Start a BGSAVE for replication goals, which is, selecting the disk or
547*572c4311Sfengbojiang  * socket target depending on the configuration, and making sure that
548*572c4311Sfengbojiang  * the script cache is flushed before to start.
549*572c4311Sfengbojiang  *
550*572c4311Sfengbojiang  * The mincapa argument is the bitwise AND among all the slaves capabilities
551*572c4311Sfengbojiang  * of the slaves waiting for this BGSAVE, so represents the slave capabilities
552*572c4311Sfengbojiang  * all the slaves support. Can be tested via SLAVE_CAPA_* macros.
553*572c4311Sfengbojiang  *
554*572c4311Sfengbojiang  * Side effects, other than starting a BGSAVE:
555*572c4311Sfengbojiang  *
556*572c4311Sfengbojiang  * 1) Handle the slaves in WAIT_START state, by preparing them for a full
557*572c4311Sfengbojiang  *    sync if the BGSAVE was successfully started, or sending them an error
558*572c4311Sfengbojiang  *    and dropping them from the list of slaves.
559*572c4311Sfengbojiang  *
560*572c4311Sfengbojiang  * 2) Flush the Lua scripting script cache if the BGSAVE was actually
561*572c4311Sfengbojiang  *    started.
562*572c4311Sfengbojiang  *
563*572c4311Sfengbojiang  * Returns C_OK on success or C_ERR otherwise. */
startBgsaveForReplication(int mincapa)564*572c4311Sfengbojiang int startBgsaveForReplication(int mincapa) {
565*572c4311Sfengbojiang     int retval;
566*572c4311Sfengbojiang     int socket_target = server.repl_diskless_sync && (mincapa & SLAVE_CAPA_EOF);
567*572c4311Sfengbojiang     listIter li;
568*572c4311Sfengbojiang     listNode *ln;
569*572c4311Sfengbojiang 
570*572c4311Sfengbojiang     serverLog(LL_NOTICE,"Starting BGSAVE for SYNC with target: %s",
571*572c4311Sfengbojiang         socket_target ? "replicas sockets" : "disk");
572*572c4311Sfengbojiang 
573*572c4311Sfengbojiang     rdbSaveInfo rsi, *rsiptr;
574*572c4311Sfengbojiang     rsiptr = rdbPopulateSaveInfo(&rsi);
575*572c4311Sfengbojiang     /* Only do rdbSave* when rsiptr is not NULL,
576*572c4311Sfengbojiang      * otherwise slave will miss repl-stream-db. */
577*572c4311Sfengbojiang     if (rsiptr) {
578*572c4311Sfengbojiang         if (socket_target)
579*572c4311Sfengbojiang             retval = rdbSaveToSlavesSockets(rsiptr);
580*572c4311Sfengbojiang         else
581*572c4311Sfengbojiang             retval = rdbSaveBackground(server.rdb_filename,rsiptr);
582*572c4311Sfengbojiang     } else {
583*572c4311Sfengbojiang         serverLog(LL_WARNING,"BGSAVE for replication: replication information not available, can't generate the RDB file right now. Try later.");
584*572c4311Sfengbojiang         retval = C_ERR;
585*572c4311Sfengbojiang     }
586*572c4311Sfengbojiang 
587*572c4311Sfengbojiang     /* If we failed to BGSAVE, remove the slaves waiting for a full
588*572c4311Sfengbojiang      * resynchorinization from the list of salves, inform them with
589*572c4311Sfengbojiang      * an error about what happened, close the connection ASAP. */
590*572c4311Sfengbojiang     if (retval == C_ERR) {
591*572c4311Sfengbojiang         serverLog(LL_WARNING,"BGSAVE for replication failed");
592*572c4311Sfengbojiang         listRewind(server.slaves,&li);
593*572c4311Sfengbojiang         while((ln = listNext(&li))) {
594*572c4311Sfengbojiang             client *slave = ln->value;
595*572c4311Sfengbojiang 
596*572c4311Sfengbojiang             if (slave->replstate == SLAVE_STATE_WAIT_BGSAVE_START) {
597*572c4311Sfengbojiang                 slave->replstate = REPL_STATE_NONE;
598*572c4311Sfengbojiang                 slave->flags &= ~CLIENT_SLAVE;
599*572c4311Sfengbojiang                 listDelNode(server.slaves,ln);
600*572c4311Sfengbojiang                 addReplyError(slave,
601*572c4311Sfengbojiang                     "BGSAVE failed, replication can't continue");
602*572c4311Sfengbojiang                 slave->flags |= CLIENT_CLOSE_AFTER_REPLY;
603*572c4311Sfengbojiang             }
604*572c4311Sfengbojiang         }
605*572c4311Sfengbojiang         return retval;
606*572c4311Sfengbojiang     }
607*572c4311Sfengbojiang 
608*572c4311Sfengbojiang     /* If the target is socket, rdbSaveToSlavesSockets() already setup
609*572c4311Sfengbojiang      * the salves for a full resync. Otherwise for disk target do it now.*/
610*572c4311Sfengbojiang     if (!socket_target) {
611*572c4311Sfengbojiang         listRewind(server.slaves,&li);
612*572c4311Sfengbojiang         while((ln = listNext(&li))) {
613*572c4311Sfengbojiang             client *slave = ln->value;
614*572c4311Sfengbojiang 
615*572c4311Sfengbojiang             if (slave->replstate == SLAVE_STATE_WAIT_BGSAVE_START) {
616*572c4311Sfengbojiang                     replicationSetupSlaveForFullResync(slave,
617*572c4311Sfengbojiang                             getPsyncInitialOffset());
618*572c4311Sfengbojiang             }
619*572c4311Sfengbojiang         }
620*572c4311Sfengbojiang     }
621*572c4311Sfengbojiang 
622*572c4311Sfengbojiang     /* Flush the script cache, since we need that slave differences are
623*572c4311Sfengbojiang      * accumulated without requiring slaves to match our cached scripts. */
624*572c4311Sfengbojiang     if (retval == C_OK) replicationScriptCacheFlush();
625*572c4311Sfengbojiang     return retval;
626*572c4311Sfengbojiang }
627*572c4311Sfengbojiang 
628*572c4311Sfengbojiang /* SYNC and PSYNC command implemenation. */
syncCommand(client * c)629*572c4311Sfengbojiang void syncCommand(client *c) {
630*572c4311Sfengbojiang     /* ignore SYNC if already slave or in monitor mode */
631*572c4311Sfengbojiang     if (c->flags & CLIENT_SLAVE) return;
632*572c4311Sfengbojiang 
633*572c4311Sfengbojiang     /* Refuse SYNC requests if we are a slave but the link with our master
634*572c4311Sfengbojiang      * is not ok... */
635*572c4311Sfengbojiang     if (server.masterhost && server.repl_state != REPL_STATE_CONNECTED) {
636*572c4311Sfengbojiang         addReplySds(c,sdsnew("-NOMASTERLINK Can't SYNC while not connected with my master\r\n"));
637*572c4311Sfengbojiang         return;
638*572c4311Sfengbojiang     }
639*572c4311Sfengbojiang 
640*572c4311Sfengbojiang     /* SYNC can't be issued when the server has pending data to send to
641*572c4311Sfengbojiang      * the client about already issued commands. We need a fresh reply
642*572c4311Sfengbojiang      * buffer registering the differences between the BGSAVE and the current
643*572c4311Sfengbojiang      * dataset, so that we can copy to other slaves if needed. */
644*572c4311Sfengbojiang     if (clientHasPendingReplies(c)) {
645*572c4311Sfengbojiang         addReplyError(c,"SYNC and PSYNC are invalid with pending output");
646*572c4311Sfengbojiang         return;
647*572c4311Sfengbojiang     }
648*572c4311Sfengbojiang 
649*572c4311Sfengbojiang     serverLog(LL_NOTICE,"Replica %s asks for synchronization",
650*572c4311Sfengbojiang         replicationGetSlaveName(c));
651*572c4311Sfengbojiang 
652*572c4311Sfengbojiang     /* Try a partial resynchronization if this is a PSYNC command.
653*572c4311Sfengbojiang      * If it fails, we continue with usual full resynchronization, however
654*572c4311Sfengbojiang      * when this happens masterTryPartialResynchronization() already
655*572c4311Sfengbojiang      * replied with:
656*572c4311Sfengbojiang      *
657*572c4311Sfengbojiang      * +FULLRESYNC <replid> <offset>
658*572c4311Sfengbojiang      *
659*572c4311Sfengbojiang      * So the slave knows the new replid and offset to try a PSYNC later
660*572c4311Sfengbojiang      * if the connection with the master is lost. */
661*572c4311Sfengbojiang     if (!strcasecmp(c->argv[0]->ptr,"psync")) {
662*572c4311Sfengbojiang         if (masterTryPartialResynchronization(c) == C_OK) {
663*572c4311Sfengbojiang             server.stat_sync_partial_ok++;
664*572c4311Sfengbojiang             return; /* No full resync needed, return. */
665*572c4311Sfengbojiang         } else {
666*572c4311Sfengbojiang             char *master_replid = c->argv[1]->ptr;
667*572c4311Sfengbojiang 
668*572c4311Sfengbojiang             /* Increment stats for failed PSYNCs, but only if the
669*572c4311Sfengbojiang              * replid is not "?", as this is used by slaves to force a full
670*572c4311Sfengbojiang              * resync on purpose when they are not albe to partially
671*572c4311Sfengbojiang              * resync. */
672*572c4311Sfengbojiang             if (master_replid[0] != '?') server.stat_sync_partial_err++;
673*572c4311Sfengbojiang         }
674*572c4311Sfengbojiang     } else {
675*572c4311Sfengbojiang         /* If a slave uses SYNC, we are dealing with an old implementation
676*572c4311Sfengbojiang          * of the replication protocol (like redis-cli --slave). Flag the client
677*572c4311Sfengbojiang          * so that we don't expect to receive REPLCONF ACK feedbacks. */
678*572c4311Sfengbojiang         c->flags |= CLIENT_PRE_PSYNC;
679*572c4311Sfengbojiang     }
680*572c4311Sfengbojiang 
681*572c4311Sfengbojiang     /* Full resynchronization. */
682*572c4311Sfengbojiang     server.stat_sync_full++;
683*572c4311Sfengbojiang 
684*572c4311Sfengbojiang     /* Setup the slave as one waiting for BGSAVE to start. The following code
685*572c4311Sfengbojiang      * paths will change the state if we handle the slave differently. */
686*572c4311Sfengbojiang     c->replstate = SLAVE_STATE_WAIT_BGSAVE_START;
687*572c4311Sfengbojiang     if (server.repl_disable_tcp_nodelay)
688*572c4311Sfengbojiang         anetDisableTcpNoDelay(NULL, c->fd); /* Non critical if it fails. */
689*572c4311Sfengbojiang     c->repldbfd = -1;
690*572c4311Sfengbojiang     c->flags |= CLIENT_SLAVE;
691*572c4311Sfengbojiang     listAddNodeTail(server.slaves,c);
692*572c4311Sfengbojiang 
693*572c4311Sfengbojiang     /* Create the replication backlog if needed. */
694*572c4311Sfengbojiang     if (listLength(server.slaves) == 1 && server.repl_backlog == NULL) {
695*572c4311Sfengbojiang         /* When we create the backlog from scratch, we always use a new
696*572c4311Sfengbojiang          * replication ID and clear the ID2, since there is no valid
697*572c4311Sfengbojiang          * past history. */
698*572c4311Sfengbojiang         changeReplicationId();
699*572c4311Sfengbojiang         clearReplicationId2();
700*572c4311Sfengbojiang         createReplicationBacklog();
701*572c4311Sfengbojiang     }
702*572c4311Sfengbojiang 
703*572c4311Sfengbojiang     /* CASE 1: BGSAVE is in progress, with disk target. */
704*572c4311Sfengbojiang     if (server.rdb_child_pid != -1 &&
705*572c4311Sfengbojiang         server.rdb_child_type == RDB_CHILD_TYPE_DISK)
706*572c4311Sfengbojiang     {
707*572c4311Sfengbojiang         /* Ok a background save is in progress. Let's check if it is a good
708*572c4311Sfengbojiang          * one for replication, i.e. if there is another slave that is
709*572c4311Sfengbojiang          * registering differences since the server forked to save. */
710*572c4311Sfengbojiang         client *slave;
711*572c4311Sfengbojiang         listNode *ln;
712*572c4311Sfengbojiang         listIter li;
713*572c4311Sfengbojiang 
714*572c4311Sfengbojiang         listRewind(server.slaves,&li);
715*572c4311Sfengbojiang         while((ln = listNext(&li))) {
716*572c4311Sfengbojiang             slave = ln->value;
717*572c4311Sfengbojiang             if (slave->replstate == SLAVE_STATE_WAIT_BGSAVE_END) break;
718*572c4311Sfengbojiang         }
719*572c4311Sfengbojiang         /* To attach this slave, we check that it has at least all the
720*572c4311Sfengbojiang          * capabilities of the slave that triggered the current BGSAVE. */
721*572c4311Sfengbojiang         if (ln && ((c->slave_capa & slave->slave_capa) == slave->slave_capa)) {
722*572c4311Sfengbojiang             /* Perfect, the server is already registering differences for
723*572c4311Sfengbojiang              * another slave. Set the right state, and copy the buffer. */
724*572c4311Sfengbojiang             copyClientOutputBuffer(c,slave);
725*572c4311Sfengbojiang             replicationSetupSlaveForFullResync(c,slave->psync_initial_offset);
726*572c4311Sfengbojiang             serverLog(LL_NOTICE,"Waiting for end of BGSAVE for SYNC");
727*572c4311Sfengbojiang         } else {
728*572c4311Sfengbojiang             /* No way, we need to wait for the next BGSAVE in order to
729*572c4311Sfengbojiang              * register differences. */
730*572c4311Sfengbojiang             serverLog(LL_NOTICE,"Can't attach the replica to the current BGSAVE. Waiting for next BGSAVE for SYNC");
731*572c4311Sfengbojiang         }
732*572c4311Sfengbojiang 
733*572c4311Sfengbojiang     /* CASE 2: BGSAVE is in progress, with socket target. */
734*572c4311Sfengbojiang     } else if (server.rdb_child_pid != -1 &&
735*572c4311Sfengbojiang                server.rdb_child_type == RDB_CHILD_TYPE_SOCKET)
736*572c4311Sfengbojiang     {
737*572c4311Sfengbojiang         /* There is an RDB child process but it is writing directly to
738*572c4311Sfengbojiang          * children sockets. We need to wait for the next BGSAVE
739*572c4311Sfengbojiang          * in order to synchronize. */
740*572c4311Sfengbojiang         serverLog(LL_NOTICE,"Current BGSAVE has socket target. Waiting for next BGSAVE for SYNC");
741*572c4311Sfengbojiang 
742*572c4311Sfengbojiang     /* CASE 3: There is no BGSAVE is progress. */
743*572c4311Sfengbojiang     } else {
744*572c4311Sfengbojiang         if (server.repl_diskless_sync && (c->slave_capa & SLAVE_CAPA_EOF)) {
745*572c4311Sfengbojiang             /* Diskless replication RDB child is created inside
746*572c4311Sfengbojiang              * replicationCron() since we want to delay its start a
747*572c4311Sfengbojiang              * few seconds to wait for more slaves to arrive. */
748*572c4311Sfengbojiang             if (server.repl_diskless_sync_delay)
749*572c4311Sfengbojiang                 serverLog(LL_NOTICE,"Delay next BGSAVE for diskless SYNC");
750*572c4311Sfengbojiang         } else {
751*572c4311Sfengbojiang             /* Target is disk (or the slave is not capable of supporting
752*572c4311Sfengbojiang              * diskless replication) and we don't have a BGSAVE in progress,
753*572c4311Sfengbojiang              * let's start one. */
754*572c4311Sfengbojiang             if (server.aof_child_pid == -1) {
755*572c4311Sfengbojiang                 startBgsaveForReplication(c->slave_capa);
756*572c4311Sfengbojiang             } else {
757*572c4311Sfengbojiang                 serverLog(LL_NOTICE,
758*572c4311Sfengbojiang                     "No BGSAVE in progress, but an AOF rewrite is active. "
759*572c4311Sfengbojiang                     "BGSAVE for replication delayed");
760*572c4311Sfengbojiang             }
761*572c4311Sfengbojiang         }
762*572c4311Sfengbojiang     }
763*572c4311Sfengbojiang     return;
764*572c4311Sfengbojiang }
765*572c4311Sfengbojiang 
766*572c4311Sfengbojiang /* REPLCONF <option> <value> <option> <value> ...
767*572c4311Sfengbojiang  * This command is used by a slave in order to configure the replication
768*572c4311Sfengbojiang  * process before starting it with the SYNC command.
769*572c4311Sfengbojiang  *
770*572c4311Sfengbojiang  * Currently the only use of this command is to communicate to the master
771*572c4311Sfengbojiang  * what is the listening port of the Slave redis instance, so that the
772*572c4311Sfengbojiang  * master can accurately list slaves and their listening ports in
773*572c4311Sfengbojiang  * the INFO output.
774*572c4311Sfengbojiang  *
775*572c4311Sfengbojiang  * In the future the same command can be used in order to configure
776*572c4311Sfengbojiang  * the replication to initiate an incremental replication instead of a
777*572c4311Sfengbojiang  * full resync. */
replconfCommand(client * c)778*572c4311Sfengbojiang void replconfCommand(client *c) {
779*572c4311Sfengbojiang     int j;
780*572c4311Sfengbojiang 
781*572c4311Sfengbojiang     if ((c->argc % 2) == 0) {
782*572c4311Sfengbojiang         /* Number of arguments must be odd to make sure that every
783*572c4311Sfengbojiang          * option has a corresponding value. */
784*572c4311Sfengbojiang         addReply(c,shared.syntaxerr);
785*572c4311Sfengbojiang         return;
786*572c4311Sfengbojiang     }
787*572c4311Sfengbojiang 
788*572c4311Sfengbojiang     /* Process every option-value pair. */
789*572c4311Sfengbojiang     for (j = 1; j < c->argc; j+=2) {
790*572c4311Sfengbojiang         if (!strcasecmp(c->argv[j]->ptr,"listening-port")) {
791*572c4311Sfengbojiang             long port;
792*572c4311Sfengbojiang 
793*572c4311Sfengbojiang             if ((getLongFromObjectOrReply(c,c->argv[j+1],
794*572c4311Sfengbojiang                     &port,NULL) != C_OK))
795*572c4311Sfengbojiang                 return;
796*572c4311Sfengbojiang             c->slave_listening_port = port;
797*572c4311Sfengbojiang         } else if (!strcasecmp(c->argv[j]->ptr,"ip-address")) {
798*572c4311Sfengbojiang             sds ip = c->argv[j+1]->ptr;
799*572c4311Sfengbojiang             if (sdslen(ip) < sizeof(c->slave_ip)) {
800*572c4311Sfengbojiang                 memcpy(c->slave_ip,ip,sdslen(ip)+1);
801*572c4311Sfengbojiang             } else {
802*572c4311Sfengbojiang                 addReplyErrorFormat(c,"REPLCONF ip-address provided by "
803*572c4311Sfengbojiang                     "replica instance is too long: %zd bytes", sdslen(ip));
804*572c4311Sfengbojiang                 return;
805*572c4311Sfengbojiang             }
806*572c4311Sfengbojiang         } else if (!strcasecmp(c->argv[j]->ptr,"capa")) {
807*572c4311Sfengbojiang             /* Ignore capabilities not understood by this master. */
808*572c4311Sfengbojiang             if (!strcasecmp(c->argv[j+1]->ptr,"eof"))
809*572c4311Sfengbojiang                 c->slave_capa |= SLAVE_CAPA_EOF;
810*572c4311Sfengbojiang             else if (!strcasecmp(c->argv[j+1]->ptr,"psync2"))
811*572c4311Sfengbojiang                 c->slave_capa |= SLAVE_CAPA_PSYNC2;
812*572c4311Sfengbojiang         } else if (!strcasecmp(c->argv[j]->ptr,"ack")) {
813*572c4311Sfengbojiang             /* REPLCONF ACK is used by slave to inform the master the amount
814*572c4311Sfengbojiang              * of replication stream that it processed so far. It is an
815*572c4311Sfengbojiang              * internal only command that normal clients should never use. */
816*572c4311Sfengbojiang             long long offset;
817*572c4311Sfengbojiang 
818*572c4311Sfengbojiang             if (!(c->flags & CLIENT_SLAVE)) return;
819*572c4311Sfengbojiang             if ((getLongLongFromObject(c->argv[j+1], &offset) != C_OK))
820*572c4311Sfengbojiang                 return;
821*572c4311Sfengbojiang             if (offset > c->repl_ack_off)
822*572c4311Sfengbojiang                 c->repl_ack_off = offset;
823*572c4311Sfengbojiang             c->repl_ack_time = server.unixtime;
824*572c4311Sfengbojiang             /* If this was a diskless replication, we need to really put
825*572c4311Sfengbojiang              * the slave online when the first ACK is received (which
826*572c4311Sfengbojiang              * confirms slave is online and ready to get more data). */
827*572c4311Sfengbojiang             if (c->repl_put_online_on_ack && c->replstate == SLAVE_STATE_ONLINE)
828*572c4311Sfengbojiang                 putSlaveOnline(c);
829*572c4311Sfengbojiang             /* Note: this command does not reply anything! */
830*572c4311Sfengbojiang             return;
831*572c4311Sfengbojiang         } else if (!strcasecmp(c->argv[j]->ptr,"getack")) {
832*572c4311Sfengbojiang             /* REPLCONF GETACK is used in order to request an ACK ASAP
833*572c4311Sfengbojiang              * to the slave. */
834*572c4311Sfengbojiang             if (server.masterhost && server.master) replicationSendAck();
835*572c4311Sfengbojiang             return;
836*572c4311Sfengbojiang         } else {
837*572c4311Sfengbojiang             addReplyErrorFormat(c,"Unrecognized REPLCONF option: %s",
838*572c4311Sfengbojiang                 (char*)c->argv[j]->ptr);
839*572c4311Sfengbojiang             return;
840*572c4311Sfengbojiang         }
841*572c4311Sfengbojiang     }
842*572c4311Sfengbojiang     addReply(c,shared.ok);
843*572c4311Sfengbojiang }
844*572c4311Sfengbojiang 
845*572c4311Sfengbojiang /* This function puts a slave in the online state, and should be called just
846*572c4311Sfengbojiang  * after a slave received the RDB file for the initial synchronization, and
847*572c4311Sfengbojiang  * we are finally ready to send the incremental stream of commands.
848*572c4311Sfengbojiang  *
849*572c4311Sfengbojiang  * It does a few things:
850*572c4311Sfengbojiang  *
851*572c4311Sfengbojiang  * 1) Put the slave in ONLINE state (useless when the function is called
852*572c4311Sfengbojiang  *    because state is already ONLINE but repl_put_online_on_ack is true).
853*572c4311Sfengbojiang  * 2) Make sure the writable event is re-installed, since calling the SYNC
854*572c4311Sfengbojiang  *    command disables it, so that we can accumulate output buffer without
855*572c4311Sfengbojiang  *    sending it to the slave.
856*572c4311Sfengbojiang  * 3) Update the count of good slaves. */
putSlaveOnline(client * slave)857*572c4311Sfengbojiang void putSlaveOnline(client *slave) {
858*572c4311Sfengbojiang     slave->replstate = SLAVE_STATE_ONLINE;
859*572c4311Sfengbojiang     slave->repl_put_online_on_ack = 0;
860*572c4311Sfengbojiang     slave->repl_ack_time = server.unixtime; /* Prevent false timeout. */
861*572c4311Sfengbojiang     if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE,
862*572c4311Sfengbojiang         sendReplyToClient, slave) == AE_ERR) {
863*572c4311Sfengbojiang         serverLog(LL_WARNING,"Unable to register writable event for replica bulk transfer: %s", strerror(errno));
864*572c4311Sfengbojiang         freeClient(slave);
865*572c4311Sfengbojiang         return;
866*572c4311Sfengbojiang     }
867*572c4311Sfengbojiang     refreshGoodSlavesCount();
868*572c4311Sfengbojiang     serverLog(LL_NOTICE,"Synchronization with replica %s succeeded",
869*572c4311Sfengbojiang         replicationGetSlaveName(slave));
870*572c4311Sfengbojiang }
871*572c4311Sfengbojiang 
sendBulkToSlave(aeEventLoop * el,int fd,void * privdata,int mask)872*572c4311Sfengbojiang void sendBulkToSlave(aeEventLoop *el, int fd, void *privdata, int mask) {
873*572c4311Sfengbojiang     client *slave = privdata;
874*572c4311Sfengbojiang     UNUSED(el);
875*572c4311Sfengbojiang     UNUSED(mask);
876*572c4311Sfengbojiang     char buf[PROTO_IOBUF_LEN];
877*572c4311Sfengbojiang     ssize_t nwritten, buflen;
878*572c4311Sfengbojiang 
879*572c4311Sfengbojiang     /* Before sending the RDB file, we send the preamble as configured by the
880*572c4311Sfengbojiang      * replication process. Currently the preamble is just the bulk count of
881*572c4311Sfengbojiang      * the file in the form "$<length>\r\n". */
882*572c4311Sfengbojiang     if (slave->replpreamble) {
883*572c4311Sfengbojiang         nwritten = write(fd,slave->replpreamble,sdslen(slave->replpreamble));
884*572c4311Sfengbojiang         if (nwritten == -1) {
885*572c4311Sfengbojiang             serverLog(LL_VERBOSE,"Write error sending RDB preamble to replica: %s",
886*572c4311Sfengbojiang                 strerror(errno));
887*572c4311Sfengbojiang             freeClient(slave);
888*572c4311Sfengbojiang             return;
889*572c4311Sfengbojiang         }
890*572c4311Sfengbojiang         server.stat_net_output_bytes += nwritten;
891*572c4311Sfengbojiang         sdsrange(slave->replpreamble,nwritten,-1);
892*572c4311Sfengbojiang         if (sdslen(slave->replpreamble) == 0) {
893*572c4311Sfengbojiang             sdsfree(slave->replpreamble);
894*572c4311Sfengbojiang             slave->replpreamble = NULL;
895*572c4311Sfengbojiang             /* fall through sending data. */
896*572c4311Sfengbojiang         } else {
897*572c4311Sfengbojiang             return;
898*572c4311Sfengbojiang         }
899*572c4311Sfengbojiang     }
900*572c4311Sfengbojiang 
901*572c4311Sfengbojiang     /* If the preamble was already transferred, send the RDB bulk data. */
902*572c4311Sfengbojiang     lseek(slave->repldbfd,slave->repldboff,SEEK_SET);
903*572c4311Sfengbojiang     buflen = read(slave->repldbfd,buf,PROTO_IOBUF_LEN);
904*572c4311Sfengbojiang     if (buflen <= 0) {
905*572c4311Sfengbojiang         serverLog(LL_WARNING,"Read error sending DB to replica: %s",
906*572c4311Sfengbojiang             (buflen == 0) ? "premature EOF" : strerror(errno));
907*572c4311Sfengbojiang         freeClient(slave);
908*572c4311Sfengbojiang         return;
909*572c4311Sfengbojiang     }
910*572c4311Sfengbojiang     if ((nwritten = write(fd,buf,buflen)) == -1) {
911*572c4311Sfengbojiang         if (errno != EAGAIN) {
912*572c4311Sfengbojiang             serverLog(LL_WARNING,"Write error sending DB to replica: %s",
913*572c4311Sfengbojiang                 strerror(errno));
914*572c4311Sfengbojiang             freeClient(slave);
915*572c4311Sfengbojiang         }
916*572c4311Sfengbojiang         return;
917*572c4311Sfengbojiang     }
918*572c4311Sfengbojiang     slave->repldboff += nwritten;
919*572c4311Sfengbojiang     server.stat_net_output_bytes += nwritten;
920*572c4311Sfengbojiang     if (slave->repldboff == slave->repldbsize) {
921*572c4311Sfengbojiang         close(slave->repldbfd);
922*572c4311Sfengbojiang         slave->repldbfd = -1;
923*572c4311Sfengbojiang         aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
924*572c4311Sfengbojiang         putSlaveOnline(slave);
925*572c4311Sfengbojiang     }
926*572c4311Sfengbojiang }
927*572c4311Sfengbojiang 
928*572c4311Sfengbojiang /* This function is called at the end of every background saving,
929*572c4311Sfengbojiang  * or when the replication RDB transfer strategy is modified from
930*572c4311Sfengbojiang  * disk to socket or the other way around.
931*572c4311Sfengbojiang  *
932*572c4311Sfengbojiang  * The goal of this function is to handle slaves waiting for a successful
933*572c4311Sfengbojiang  * background saving in order to perform non-blocking synchronization, and
934*572c4311Sfengbojiang  * to schedule a new BGSAVE if there are slaves that attached while a
935*572c4311Sfengbojiang  * BGSAVE was in progress, but it was not a good one for replication (no
936*572c4311Sfengbojiang  * other slave was accumulating differences).
937*572c4311Sfengbojiang  *
938*572c4311Sfengbojiang  * The argument bgsaveerr is C_OK if the background saving succeeded
939*572c4311Sfengbojiang  * otherwise C_ERR is passed to the function.
940*572c4311Sfengbojiang  * The 'type' argument is the type of the child that terminated
941*572c4311Sfengbojiang  * (if it had a disk or socket target). */
updateSlavesWaitingBgsave(int bgsaveerr,int type)942*572c4311Sfengbojiang void updateSlavesWaitingBgsave(int bgsaveerr, int type) {
943*572c4311Sfengbojiang     listNode *ln;
944*572c4311Sfengbojiang     int startbgsave = 0;
945*572c4311Sfengbojiang     int mincapa = -1;
946*572c4311Sfengbojiang     listIter li;
947*572c4311Sfengbojiang 
948*572c4311Sfengbojiang     listRewind(server.slaves,&li);
949*572c4311Sfengbojiang     while((ln = listNext(&li))) {
950*572c4311Sfengbojiang         client *slave = ln->value;
951*572c4311Sfengbojiang 
952*572c4311Sfengbojiang         if (slave->replstate == SLAVE_STATE_WAIT_BGSAVE_START) {
953*572c4311Sfengbojiang             startbgsave = 1;
954*572c4311Sfengbojiang             mincapa = (mincapa == -1) ? slave->slave_capa :
955*572c4311Sfengbojiang                                         (mincapa & slave->slave_capa);
956*572c4311Sfengbojiang         } else if (slave->replstate == SLAVE_STATE_WAIT_BGSAVE_END) {
957*572c4311Sfengbojiang             struct redis_stat buf;
958*572c4311Sfengbojiang 
959*572c4311Sfengbojiang             /* If this was an RDB on disk save, we have to prepare to send
960*572c4311Sfengbojiang              * the RDB from disk to the slave socket. Otherwise if this was
961*572c4311Sfengbojiang              * already an RDB -> Slaves socket transfer, used in the case of
962*572c4311Sfengbojiang              * diskless replication, our work is trivial, we can just put
963*572c4311Sfengbojiang              * the slave online. */
964*572c4311Sfengbojiang             if (type == RDB_CHILD_TYPE_SOCKET) {
965*572c4311Sfengbojiang                 serverLog(LL_NOTICE,
966*572c4311Sfengbojiang                     "Streamed RDB transfer with replica %s succeeded (socket). Waiting for REPLCONF ACK from slave to enable streaming",
967*572c4311Sfengbojiang                         replicationGetSlaveName(slave));
968*572c4311Sfengbojiang                 /* Note: we wait for a REPLCONF ACK message from slave in
969*572c4311Sfengbojiang                  * order to really put it online (install the write handler
970*572c4311Sfengbojiang                  * so that the accumulated data can be transferred). However
971*572c4311Sfengbojiang                  * we change the replication state ASAP, since our slave
972*572c4311Sfengbojiang                  * is technically online now. */
973*572c4311Sfengbojiang                 slave->replstate = SLAVE_STATE_ONLINE;
974*572c4311Sfengbojiang                 slave->repl_put_online_on_ack = 1;
975*572c4311Sfengbojiang                 slave->repl_ack_time = server.unixtime; /* Timeout otherwise. */
976*572c4311Sfengbojiang             } else {
977*572c4311Sfengbojiang                 if (bgsaveerr != C_OK) {
978*572c4311Sfengbojiang                     freeClient(slave);
979*572c4311Sfengbojiang                     serverLog(LL_WARNING,"SYNC failed. BGSAVE child returned an error");
980*572c4311Sfengbojiang                     continue;
981*572c4311Sfengbojiang                 }
982*572c4311Sfengbojiang                 if ((slave->repldbfd = open(server.rdb_filename,O_RDONLY)) == -1 ||
983*572c4311Sfengbojiang                     redis_fstat(slave->repldbfd,&buf) == -1) {
984*572c4311Sfengbojiang                     freeClient(slave);
985*572c4311Sfengbojiang                     serverLog(LL_WARNING,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno));
986*572c4311Sfengbojiang                     continue;
987*572c4311Sfengbojiang                 }
988*572c4311Sfengbojiang                 slave->repldboff = 0;
989*572c4311Sfengbojiang                 slave->repldbsize = buf.st_size;
990*572c4311Sfengbojiang                 slave->replstate = SLAVE_STATE_SEND_BULK;
991*572c4311Sfengbojiang                 slave->replpreamble = sdscatprintf(sdsempty(),"$%lld\r\n",
992*572c4311Sfengbojiang                     (unsigned long long) slave->repldbsize);
993*572c4311Sfengbojiang 
994*572c4311Sfengbojiang                 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
995*572c4311Sfengbojiang                 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE, sendBulkToSlave, slave) == AE_ERR) {
996*572c4311Sfengbojiang                     freeClient(slave);
997*572c4311Sfengbojiang                     continue;
998*572c4311Sfengbojiang                 }
999*572c4311Sfengbojiang             }
1000*572c4311Sfengbojiang         }
1001*572c4311Sfengbojiang     }
1002*572c4311Sfengbojiang     if (startbgsave) startBgsaveForReplication(mincapa);
1003*572c4311Sfengbojiang }
1004*572c4311Sfengbojiang 
1005*572c4311Sfengbojiang /* Change the current instance replication ID with a new, random one.
1006*572c4311Sfengbojiang  * This will prevent successful PSYNCs between this master and other
1007*572c4311Sfengbojiang  * slaves, so the command should be called when something happens that
1008*572c4311Sfengbojiang  * alters the current story of the dataset. */
changeReplicationId(void)1009*572c4311Sfengbojiang void changeReplicationId(void) {
1010*572c4311Sfengbojiang     getRandomHexChars(server.replid,CONFIG_RUN_ID_SIZE);
1011*572c4311Sfengbojiang     server.replid[CONFIG_RUN_ID_SIZE] = '\0';
1012*572c4311Sfengbojiang }
1013*572c4311Sfengbojiang 
1014*572c4311Sfengbojiang /* Clear (invalidate) the secondary replication ID. This happens, for
1015*572c4311Sfengbojiang  * example, after a full resynchronization, when we start a new replication
1016*572c4311Sfengbojiang  * history. */
clearReplicationId2(void)1017*572c4311Sfengbojiang void clearReplicationId2(void) {
1018*572c4311Sfengbojiang     memset(server.replid2,'0',sizeof(server.replid));
1019*572c4311Sfengbojiang     server.replid2[CONFIG_RUN_ID_SIZE] = '\0';
1020*572c4311Sfengbojiang     server.second_replid_offset = -1;
1021*572c4311Sfengbojiang }
1022*572c4311Sfengbojiang 
1023*572c4311Sfengbojiang /* Use the current replication ID / offset as secondary replication
1024*572c4311Sfengbojiang  * ID, and change the current one in order to start a new history.
1025*572c4311Sfengbojiang  * This should be used when an instance is switched from slave to master
1026*572c4311Sfengbojiang  * so that it can serve PSYNC requests performed using the master
1027*572c4311Sfengbojiang  * replication ID. */
shiftReplicationId(void)1028*572c4311Sfengbojiang void shiftReplicationId(void) {
1029*572c4311Sfengbojiang     memcpy(server.replid2,server.replid,sizeof(server.replid));
1030*572c4311Sfengbojiang     /* We set the second replid offset to the master offset + 1, since
1031*572c4311Sfengbojiang      * the slave will ask for the first byte it has not yet received, so
1032*572c4311Sfengbojiang      * we need to add one to the offset: for example if, as a slave, we are
1033*572c4311Sfengbojiang      * sure we have the same history as the master for 50 bytes, after we
1034*572c4311Sfengbojiang      * are turned into a master, we can accept a PSYNC request with offset
1035*572c4311Sfengbojiang      * 51, since the slave asking has the same history up to the 50th
1036*572c4311Sfengbojiang      * byte, and is asking for the new bytes starting at offset 51. */
1037*572c4311Sfengbojiang     server.second_replid_offset = server.master_repl_offset+1;
1038*572c4311Sfengbojiang     changeReplicationId();
1039*572c4311Sfengbojiang     serverLog(LL_WARNING,"Setting secondary replication ID to %s, valid up to offset: %lld. New replication ID is %s", server.replid2, server.second_replid_offset, server.replid);
1040*572c4311Sfengbojiang }
1041*572c4311Sfengbojiang 
1042*572c4311Sfengbojiang /* ----------------------------------- SLAVE -------------------------------- */
1043*572c4311Sfengbojiang 
1044*572c4311Sfengbojiang /* Returns 1 if the given replication state is a handshake state,
1045*572c4311Sfengbojiang  * 0 otherwise. */
slaveIsInHandshakeState(void)1046*572c4311Sfengbojiang int slaveIsInHandshakeState(void) {
1047*572c4311Sfengbojiang     return server.repl_state >= REPL_STATE_RECEIVE_PONG &&
1048*572c4311Sfengbojiang            server.repl_state <= REPL_STATE_RECEIVE_PSYNC;
1049*572c4311Sfengbojiang }
1050*572c4311Sfengbojiang 
1051*572c4311Sfengbojiang /* Avoid the master to detect the slave is timing out while loading the
1052*572c4311Sfengbojiang  * RDB file in initial synchronization. We send a single newline character
1053*572c4311Sfengbojiang  * that is valid protocol but is guaranteed to either be sent entirely or
1054*572c4311Sfengbojiang  * not, since the byte is indivisible.
1055*572c4311Sfengbojiang  *
1056*572c4311Sfengbojiang  * The function is called in two contexts: while we flush the current
1057*572c4311Sfengbojiang  * data with emptyDb(), and while we load the new data received as an
1058*572c4311Sfengbojiang  * RDB file from the master. */
replicationSendNewlineToMaster(void)1059*572c4311Sfengbojiang void replicationSendNewlineToMaster(void) {
1060*572c4311Sfengbojiang     static time_t newline_sent;
1061*572c4311Sfengbojiang     if (time(NULL) != newline_sent) {
1062*572c4311Sfengbojiang         newline_sent = time(NULL);
1063*572c4311Sfengbojiang         if (write(server.repl_transfer_s,"\n",1) == -1) {
1064*572c4311Sfengbojiang             /* Pinging back in this stage is best-effort. */
1065*572c4311Sfengbojiang         }
1066*572c4311Sfengbojiang     }
1067*572c4311Sfengbojiang }
1068*572c4311Sfengbojiang 
1069*572c4311Sfengbojiang /* Callback used by emptyDb() while flushing away old data to load
1070*572c4311Sfengbojiang  * the new dataset received by the master. */
replicationEmptyDbCallback(void * privdata)1071*572c4311Sfengbojiang void replicationEmptyDbCallback(void *privdata) {
1072*572c4311Sfengbojiang     UNUSED(privdata);
1073*572c4311Sfengbojiang     replicationSendNewlineToMaster();
1074*572c4311Sfengbojiang }
1075*572c4311Sfengbojiang 
1076*572c4311Sfengbojiang /* Once we have a link with the master and the synchroniziation was
1077*572c4311Sfengbojiang  * performed, this function materializes the master client we store
1078*572c4311Sfengbojiang  * at server.master, starting from the specified file descriptor. */
replicationCreateMasterClient(int fd,int dbid)1079*572c4311Sfengbojiang void replicationCreateMasterClient(int fd, int dbid) {
1080*572c4311Sfengbojiang     server.master = createClient(fd);
1081*572c4311Sfengbojiang     server.master->flags |= CLIENT_MASTER;
1082*572c4311Sfengbojiang     server.master->authenticated = 1;
1083*572c4311Sfengbojiang     server.master->reploff = server.master_initial_offset;
1084*572c4311Sfengbojiang     server.master->read_reploff = server.master->reploff;
1085*572c4311Sfengbojiang     memcpy(server.master->replid, server.master_replid,
1086*572c4311Sfengbojiang         sizeof(server.master_replid));
1087*572c4311Sfengbojiang     /* If master offset is set to -1, this master is old and is not
1088*572c4311Sfengbojiang      * PSYNC capable, so we flag it accordingly. */
1089*572c4311Sfengbojiang     if (server.master->reploff == -1)
1090*572c4311Sfengbojiang         server.master->flags |= CLIENT_PRE_PSYNC;
1091*572c4311Sfengbojiang     if (dbid != -1) selectDb(server.master,dbid);
1092*572c4311Sfengbojiang }
1093*572c4311Sfengbojiang 
1094*572c4311Sfengbojiang /* This function will try to re-enable the AOF file after the
1095*572c4311Sfengbojiang  * master-replica synchronization: if it fails after multiple attempts
1096*572c4311Sfengbojiang  * the replica cannot be considered reliable and exists with an
1097*572c4311Sfengbojiang  * error. */
restartAOFAfterSYNC()1098*572c4311Sfengbojiang void restartAOFAfterSYNC() {
1099*572c4311Sfengbojiang     unsigned int tries, max_tries = 10;
1100*572c4311Sfengbojiang     for (tries = 0; tries < max_tries; ++tries) {
1101*572c4311Sfengbojiang         if (startAppendOnly() == C_OK) break;
1102*572c4311Sfengbojiang         serverLog(LL_WARNING,
1103*572c4311Sfengbojiang             "Failed enabling the AOF after successful master synchronization! "
1104*572c4311Sfengbojiang             "Trying it again in one second.");
1105*572c4311Sfengbojiang         sleep(1);
1106*572c4311Sfengbojiang     }
1107*572c4311Sfengbojiang     if (tries == max_tries) {
1108*572c4311Sfengbojiang         serverLog(LL_WARNING,
1109*572c4311Sfengbojiang             "FATAL: this replica instance finished the synchronization with "
1110*572c4311Sfengbojiang             "its master, but the AOF can't be turned on. Exiting now.");
1111*572c4311Sfengbojiang         exit(1);
1112*572c4311Sfengbojiang     }
1113*572c4311Sfengbojiang }
1114*572c4311Sfengbojiang 
1115*572c4311Sfengbojiang /* Asynchronously read the SYNC payload we receive from a master */
1116*572c4311Sfengbojiang #define REPL_MAX_WRITTEN_BEFORE_FSYNC (1024*1024*8) /* 8 MB */
readSyncBulkPayload(aeEventLoop * el,int fd,void * privdata,int mask)1117*572c4311Sfengbojiang void readSyncBulkPayload(aeEventLoop *el, int fd, void *privdata, int mask) {
1118*572c4311Sfengbojiang     char buf[4096];
1119*572c4311Sfengbojiang     ssize_t nread, readlen, nwritten;
1120*572c4311Sfengbojiang     off_t left;
1121*572c4311Sfengbojiang     UNUSED(el);
1122*572c4311Sfengbojiang     UNUSED(privdata);
1123*572c4311Sfengbojiang     UNUSED(mask);
1124*572c4311Sfengbojiang 
1125*572c4311Sfengbojiang     /* Static vars used to hold the EOF mark, and the last bytes received
1126*572c4311Sfengbojiang      * form the server: when they match, we reached the end of the transfer. */
1127*572c4311Sfengbojiang     static char eofmark[CONFIG_RUN_ID_SIZE];
1128*572c4311Sfengbojiang     static char lastbytes[CONFIG_RUN_ID_SIZE];
1129*572c4311Sfengbojiang     static int usemark = 0;
1130*572c4311Sfengbojiang 
1131*572c4311Sfengbojiang     /* If repl_transfer_size == -1 we still have to read the bulk length
1132*572c4311Sfengbojiang      * from the master reply. */
1133*572c4311Sfengbojiang     if (server.repl_transfer_size == -1) {
1134*572c4311Sfengbojiang         if (syncReadLine(fd,buf,1024,server.repl_syncio_timeout*1000) == -1) {
1135*572c4311Sfengbojiang             serverLog(LL_WARNING,
1136*572c4311Sfengbojiang                 "I/O error reading bulk count from MASTER: %s",
1137*572c4311Sfengbojiang                 strerror(errno));
1138*572c4311Sfengbojiang             goto error;
1139*572c4311Sfengbojiang         }
1140*572c4311Sfengbojiang 
1141*572c4311Sfengbojiang         if (buf[0] == '-') {
1142*572c4311Sfengbojiang             serverLog(LL_WARNING,
1143*572c4311Sfengbojiang                 "MASTER aborted replication with an error: %s",
1144*572c4311Sfengbojiang                 buf+1);
1145*572c4311Sfengbojiang             goto error;
1146*572c4311Sfengbojiang         } else if (buf[0] == '\0') {
1147*572c4311Sfengbojiang             /* At this stage just a newline works as a PING in order to take
1148*572c4311Sfengbojiang              * the connection live. So we refresh our last interaction
1149*572c4311Sfengbojiang              * timestamp. */
1150*572c4311Sfengbojiang             server.repl_transfer_lastio = server.unixtime;
1151*572c4311Sfengbojiang             return;
1152*572c4311Sfengbojiang         } else if (buf[0] != '$') {
1153*572c4311Sfengbojiang             serverLog(LL_WARNING,"Bad protocol from MASTER, the first byte is not '$' (we received '%s'), are you sure the host and port are right?", buf);
1154*572c4311Sfengbojiang             goto error;
1155*572c4311Sfengbojiang         }
1156*572c4311Sfengbojiang 
1157*572c4311Sfengbojiang         /* There are two possible forms for the bulk payload. One is the
1158*572c4311Sfengbojiang          * usual $<count> bulk format. The other is used for diskless transfers
1159*572c4311Sfengbojiang          * when the master does not know beforehand the size of the file to
1160*572c4311Sfengbojiang          * transfer. In the latter case, the following format is used:
1161*572c4311Sfengbojiang          *
1162*572c4311Sfengbojiang          * $EOF:<40 bytes delimiter>
1163*572c4311Sfengbojiang          *
1164*572c4311Sfengbojiang          * At the end of the file the announced delimiter is transmitted. The
1165*572c4311Sfengbojiang          * delimiter is long and random enough that the probability of a
1166*572c4311Sfengbojiang          * collision with the actual file content can be ignored. */
1167*572c4311Sfengbojiang         if (strncmp(buf+1,"EOF:",4) == 0 && strlen(buf+5) >= CONFIG_RUN_ID_SIZE) {
1168*572c4311Sfengbojiang             usemark = 1;
1169*572c4311Sfengbojiang             memcpy(eofmark,buf+5,CONFIG_RUN_ID_SIZE);
1170*572c4311Sfengbojiang             memset(lastbytes,0,CONFIG_RUN_ID_SIZE);
1171*572c4311Sfengbojiang             /* Set any repl_transfer_size to avoid entering this code path
1172*572c4311Sfengbojiang              * at the next call. */
1173*572c4311Sfengbojiang             server.repl_transfer_size = 0;
1174*572c4311Sfengbojiang             serverLog(LL_NOTICE,
1175*572c4311Sfengbojiang                 "MASTER <-> REPLICA sync: receiving streamed RDB from master");
1176*572c4311Sfengbojiang         } else {
1177*572c4311Sfengbojiang             usemark = 0;
1178*572c4311Sfengbojiang             server.repl_transfer_size = strtol(buf+1,NULL,10);
1179*572c4311Sfengbojiang             serverLog(LL_NOTICE,
1180*572c4311Sfengbojiang                 "MASTER <-> REPLICA sync: receiving %lld bytes from master",
1181*572c4311Sfengbojiang                 (long long) server.repl_transfer_size);
1182*572c4311Sfengbojiang         }
1183*572c4311Sfengbojiang         return;
1184*572c4311Sfengbojiang     }
1185*572c4311Sfengbojiang 
1186*572c4311Sfengbojiang     /* Read bulk data */
1187*572c4311Sfengbojiang     if (usemark) {
1188*572c4311Sfengbojiang         readlen = sizeof(buf);
1189*572c4311Sfengbojiang     } else {
1190*572c4311Sfengbojiang         left = server.repl_transfer_size - server.repl_transfer_read;
1191*572c4311Sfengbojiang         readlen = (left < (signed)sizeof(buf)) ? left : (signed)sizeof(buf);
1192*572c4311Sfengbojiang     }
1193*572c4311Sfengbojiang 
1194*572c4311Sfengbojiang     nread = read(fd,buf,readlen);
1195*572c4311Sfengbojiang     if (nread <= 0) {
1196*572c4311Sfengbojiang         serverLog(LL_WARNING,"I/O error trying to sync with MASTER: %s",
1197*572c4311Sfengbojiang             (nread == -1) ? strerror(errno) : "connection lost");
1198*572c4311Sfengbojiang         cancelReplicationHandshake();
1199*572c4311Sfengbojiang         return;
1200*572c4311Sfengbojiang     }
1201*572c4311Sfengbojiang     server.stat_net_input_bytes += nread;
1202*572c4311Sfengbojiang 
1203*572c4311Sfengbojiang     /* When a mark is used, we want to detect EOF asap in order to avoid
1204*572c4311Sfengbojiang      * writing the EOF mark into the file... */
1205*572c4311Sfengbojiang     int eof_reached = 0;
1206*572c4311Sfengbojiang 
1207*572c4311Sfengbojiang     if (usemark) {
1208*572c4311Sfengbojiang         /* Update the last bytes array, and check if it matches our delimiter.*/
1209*572c4311Sfengbojiang         if (nread >= CONFIG_RUN_ID_SIZE) {
1210*572c4311Sfengbojiang             memcpy(lastbytes,buf+nread-CONFIG_RUN_ID_SIZE,CONFIG_RUN_ID_SIZE);
1211*572c4311Sfengbojiang         } else {
1212*572c4311Sfengbojiang             int rem = CONFIG_RUN_ID_SIZE-nread;
1213*572c4311Sfengbojiang             memmove(lastbytes,lastbytes+nread,rem);
1214*572c4311Sfengbojiang             memcpy(lastbytes+rem,buf,nread);
1215*572c4311Sfengbojiang         }
1216*572c4311Sfengbojiang         if (memcmp(lastbytes,eofmark,CONFIG_RUN_ID_SIZE) == 0) eof_reached = 1;
1217*572c4311Sfengbojiang     }
1218*572c4311Sfengbojiang 
1219*572c4311Sfengbojiang     server.repl_transfer_lastio = server.unixtime;
1220*572c4311Sfengbojiang     if ((nwritten = write(server.repl_transfer_fd,buf,nread)) != nread) {
1221*572c4311Sfengbojiang         serverLog(LL_WARNING,"Write error or short write writing to the DB dump file needed for MASTER <-> REPLICA synchronization: %s",
1222*572c4311Sfengbojiang             (nwritten == -1) ? strerror(errno) : "short write");
1223*572c4311Sfengbojiang         goto error;
1224*572c4311Sfengbojiang     }
1225*572c4311Sfengbojiang     server.repl_transfer_read += nread;
1226*572c4311Sfengbojiang 
1227*572c4311Sfengbojiang     /* Delete the last 40 bytes from the file if we reached EOF. */
1228*572c4311Sfengbojiang     if (usemark && eof_reached) {
1229*572c4311Sfengbojiang         if (ftruncate(server.repl_transfer_fd,
1230*572c4311Sfengbojiang             server.repl_transfer_read - CONFIG_RUN_ID_SIZE) == -1)
1231*572c4311Sfengbojiang         {
1232*572c4311Sfengbojiang             serverLog(LL_WARNING,"Error truncating the RDB file received from the master for SYNC: %s", strerror(errno));
1233*572c4311Sfengbojiang             goto error;
1234*572c4311Sfengbojiang         }
1235*572c4311Sfengbojiang     }
1236*572c4311Sfengbojiang 
1237*572c4311Sfengbojiang     /* Sync data on disk from time to time, otherwise at the end of the transfer
1238*572c4311Sfengbojiang      * we may suffer a big delay as the memory buffers are copied into the
1239*572c4311Sfengbojiang      * actual disk. */
1240*572c4311Sfengbojiang     if (server.repl_transfer_read >=
1241*572c4311Sfengbojiang         server.repl_transfer_last_fsync_off + REPL_MAX_WRITTEN_BEFORE_FSYNC)
1242*572c4311Sfengbojiang     {
1243*572c4311Sfengbojiang         off_t sync_size = server.repl_transfer_read -
1244*572c4311Sfengbojiang                           server.repl_transfer_last_fsync_off;
1245*572c4311Sfengbojiang         rdb_fsync_range(server.repl_transfer_fd,
1246*572c4311Sfengbojiang             server.repl_transfer_last_fsync_off, sync_size);
1247*572c4311Sfengbojiang         server.repl_transfer_last_fsync_off += sync_size;
1248*572c4311Sfengbojiang     }
1249*572c4311Sfengbojiang 
1250*572c4311Sfengbojiang     /* Check if the transfer is now complete */
1251*572c4311Sfengbojiang     if (!usemark) {
1252*572c4311Sfengbojiang         if (server.repl_transfer_read == server.repl_transfer_size)
1253*572c4311Sfengbojiang             eof_reached = 1;
1254*572c4311Sfengbojiang     }
1255*572c4311Sfengbojiang 
1256*572c4311Sfengbojiang     if (eof_reached) {
1257*572c4311Sfengbojiang         int aof_is_enabled = server.aof_state != AOF_OFF;
1258*572c4311Sfengbojiang 
1259*572c4311Sfengbojiang         /* Ensure background save doesn't overwrite synced data */
1260*572c4311Sfengbojiang         if (server.rdb_child_pid != -1) {
1261*572c4311Sfengbojiang             serverLog(LL_NOTICE,
1262*572c4311Sfengbojiang                 "Replica is about to load the RDB file received from the "
1263*572c4311Sfengbojiang                 "master, but there is a pending RDB child running. "
1264*572c4311Sfengbojiang                 "Killing process %ld and removing its temp file to avoid "
1265*572c4311Sfengbojiang                 "any race",
1266*572c4311Sfengbojiang                     (long) server.rdb_child_pid);
1267*572c4311Sfengbojiang             kill(server.rdb_child_pid,SIGUSR1);
1268*572c4311Sfengbojiang             rdbRemoveTempFile(server.rdb_child_pid);
1269*572c4311Sfengbojiang         }
1270*572c4311Sfengbojiang 
1271*572c4311Sfengbojiang         if (rename(server.repl_transfer_tmpfile,server.rdb_filename) == -1) {
1272*572c4311Sfengbojiang             serverLog(LL_WARNING,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> REPLICA synchronization: %s", strerror(errno));
1273*572c4311Sfengbojiang             cancelReplicationHandshake();
1274*572c4311Sfengbojiang             return;
1275*572c4311Sfengbojiang         }
1276*572c4311Sfengbojiang         serverLog(LL_NOTICE, "MASTER <-> REPLICA sync: Flushing old data");
1277*572c4311Sfengbojiang         /* We need to stop any AOFRW fork before flusing and parsing
1278*572c4311Sfengbojiang          * RDB, otherwise we'll create a copy-on-write disaster. */
1279*572c4311Sfengbojiang         if(aof_is_enabled) stopAppendOnly();
1280*572c4311Sfengbojiang         signalFlushedDb(-1);
1281*572c4311Sfengbojiang         emptyDb(
1282*572c4311Sfengbojiang             -1,
1283*572c4311Sfengbojiang             server.repl_slave_lazy_flush ? EMPTYDB_ASYNC : EMPTYDB_NO_FLAGS,
1284*572c4311Sfengbojiang             replicationEmptyDbCallback);
1285*572c4311Sfengbojiang         /* Before loading the DB into memory we need to delete the readable
1286*572c4311Sfengbojiang          * handler, otherwise it will get called recursively since
1287*572c4311Sfengbojiang          * rdbLoad() will call the event loop to process events from time to
1288*572c4311Sfengbojiang          * time for non blocking loading. */
1289*572c4311Sfengbojiang         aeDeleteFileEvent(server.el,server.repl_transfer_s,AE_READABLE);
1290*572c4311Sfengbojiang         serverLog(LL_NOTICE, "MASTER <-> REPLICA sync: Loading DB in memory");
1291*572c4311Sfengbojiang         rdbSaveInfo rsi = RDB_SAVE_INFO_INIT;
1292*572c4311Sfengbojiang         if (rdbLoad(server.rdb_filename,&rsi) != C_OK) {
1293*572c4311Sfengbojiang             serverLog(LL_WARNING,"Failed trying to load the MASTER synchronization DB from disk");
1294*572c4311Sfengbojiang             cancelReplicationHandshake();
1295*572c4311Sfengbojiang             /* Re-enable the AOF if we disabled it earlier, in order to restore
1296*572c4311Sfengbojiang              * the original configuration. */
1297*572c4311Sfengbojiang             if (aof_is_enabled) restartAOFAfterSYNC();
1298*572c4311Sfengbojiang             return;
1299*572c4311Sfengbojiang         }
1300*572c4311Sfengbojiang         /* Final setup of the connected slave <- master link */
1301*572c4311Sfengbojiang         zfree(server.repl_transfer_tmpfile);
1302*572c4311Sfengbojiang         close(server.repl_transfer_fd);
1303*572c4311Sfengbojiang         replicationCreateMasterClient(server.repl_transfer_s,rsi.repl_stream_db);
1304*572c4311Sfengbojiang         server.repl_state = REPL_STATE_CONNECTED;
1305*572c4311Sfengbojiang         server.repl_down_since = 0;
1306*572c4311Sfengbojiang         /* After a full resynchroniziation we use the replication ID and
1307*572c4311Sfengbojiang          * offset of the master. The secondary ID / offset are cleared since
1308*572c4311Sfengbojiang          * we are starting a new history. */
1309*572c4311Sfengbojiang         memcpy(server.replid,server.master->replid,sizeof(server.replid));
1310*572c4311Sfengbojiang         server.master_repl_offset = server.master->reploff;
1311*572c4311Sfengbojiang         clearReplicationId2();
1312*572c4311Sfengbojiang         /* Let's create the replication backlog if needed. Slaves need to
1313*572c4311Sfengbojiang          * accumulate the backlog regardless of the fact they have sub-slaves
1314*572c4311Sfengbojiang          * or not, in order to behave correctly if they are promoted to
1315*572c4311Sfengbojiang          * masters after a failover. */
1316*572c4311Sfengbojiang         if (server.repl_backlog == NULL) createReplicationBacklog();
1317*572c4311Sfengbojiang 
1318*572c4311Sfengbojiang         serverLog(LL_NOTICE, "MASTER <-> REPLICA sync: Finished with success");
1319*572c4311Sfengbojiang         /* Restart the AOF subsystem now that we finished the sync. This
1320*572c4311Sfengbojiang          * will trigger an AOF rewrite, and when done will start appending
1321*572c4311Sfengbojiang          * to the new file. */
1322*572c4311Sfengbojiang         if (aof_is_enabled) restartAOFAfterSYNC();
1323*572c4311Sfengbojiang     }
1324*572c4311Sfengbojiang     return;
1325*572c4311Sfengbojiang 
1326*572c4311Sfengbojiang error:
1327*572c4311Sfengbojiang     cancelReplicationHandshake();
1328*572c4311Sfengbojiang     return;
1329*572c4311Sfengbojiang }
1330*572c4311Sfengbojiang 
1331*572c4311Sfengbojiang /* Send a synchronous command to the master. Used to send AUTH and
1332*572c4311Sfengbojiang  * REPLCONF commands before starting the replication with SYNC.
1333*572c4311Sfengbojiang  *
1334*572c4311Sfengbojiang  * The command returns an sds string representing the result of the
1335*572c4311Sfengbojiang  * operation. On error the first byte is a "-".
1336*572c4311Sfengbojiang  */
1337*572c4311Sfengbojiang #define SYNC_CMD_READ (1<<0)
1338*572c4311Sfengbojiang #define SYNC_CMD_WRITE (1<<1)
1339*572c4311Sfengbojiang #define SYNC_CMD_FULL (SYNC_CMD_READ|SYNC_CMD_WRITE)
sendSynchronousCommand(int flags,int fd,...)1340*572c4311Sfengbojiang char *sendSynchronousCommand(int flags, int fd, ...) {
1341*572c4311Sfengbojiang 
1342*572c4311Sfengbojiang     /* Create the command to send to the master, we use redis binary
1343*572c4311Sfengbojiang      * protocol to make sure correct arguments are sent. This function
1344*572c4311Sfengbojiang      * is not safe for all binary data. */
1345*572c4311Sfengbojiang     if (flags & SYNC_CMD_WRITE) {
1346*572c4311Sfengbojiang         char *arg;
1347*572c4311Sfengbojiang         va_list ap;
1348*572c4311Sfengbojiang         sds cmd = sdsempty();
1349*572c4311Sfengbojiang         sds cmdargs = sdsempty();
1350*572c4311Sfengbojiang         size_t argslen = 0;
1351*572c4311Sfengbojiang         va_start(ap,fd);
1352*572c4311Sfengbojiang 
1353*572c4311Sfengbojiang         while(1) {
1354*572c4311Sfengbojiang             arg = va_arg(ap, char*);
1355*572c4311Sfengbojiang             if (arg == NULL) break;
1356*572c4311Sfengbojiang 
1357*572c4311Sfengbojiang             cmdargs = sdscatprintf(cmdargs,"$%zu\r\n%s\r\n",strlen(arg),arg);
1358*572c4311Sfengbojiang             argslen++;
1359*572c4311Sfengbojiang         }
1360*572c4311Sfengbojiang 
1361*572c4311Sfengbojiang         va_end(ap);
1362*572c4311Sfengbojiang 
1363*572c4311Sfengbojiang         cmd = sdscatprintf(cmd,"*%zu\r\n",argslen);
1364*572c4311Sfengbojiang         cmd = sdscatsds(cmd,cmdargs);
1365*572c4311Sfengbojiang         sdsfree(cmdargs);
1366*572c4311Sfengbojiang 
1367*572c4311Sfengbojiang         /* Transfer command to the server. */
1368*572c4311Sfengbojiang         if (syncWrite(fd,cmd,sdslen(cmd),server.repl_syncio_timeout*1000)
1369*572c4311Sfengbojiang             == -1)
1370*572c4311Sfengbojiang         {
1371*572c4311Sfengbojiang             sdsfree(cmd);
1372*572c4311Sfengbojiang             return sdscatprintf(sdsempty(),"-Writing to master: %s",
1373*572c4311Sfengbojiang                     strerror(errno));
1374*572c4311Sfengbojiang         }
1375*572c4311Sfengbojiang         sdsfree(cmd);
1376*572c4311Sfengbojiang     }
1377*572c4311Sfengbojiang 
1378*572c4311Sfengbojiang     /* Read the reply from the server. */
1379*572c4311Sfengbojiang     if (flags & SYNC_CMD_READ) {
1380*572c4311Sfengbojiang         char buf[256];
1381*572c4311Sfengbojiang 
1382*572c4311Sfengbojiang         if (syncReadLine(fd,buf,sizeof(buf),server.repl_syncio_timeout*1000)
1383*572c4311Sfengbojiang             == -1)
1384*572c4311Sfengbojiang         {
1385*572c4311Sfengbojiang             return sdscatprintf(sdsempty(),"-Reading from master: %s",
1386*572c4311Sfengbojiang                     strerror(errno));
1387*572c4311Sfengbojiang         }
1388*572c4311Sfengbojiang         server.repl_transfer_lastio = server.unixtime;
1389*572c4311Sfengbojiang         return sdsnew(buf);
1390*572c4311Sfengbojiang     }
1391*572c4311Sfengbojiang     return NULL;
1392*572c4311Sfengbojiang }
1393*572c4311Sfengbojiang 
1394*572c4311Sfengbojiang /* Try a partial resynchronization with the master if we are about to reconnect.
1395*572c4311Sfengbojiang  * If there is no cached master structure, at least try to issue a
1396*572c4311Sfengbojiang  * "PSYNC ? -1" command in order to trigger a full resync using the PSYNC
1397*572c4311Sfengbojiang  * command in order to obtain the master run id and the master replication
1398*572c4311Sfengbojiang  * global offset.
1399*572c4311Sfengbojiang  *
1400*572c4311Sfengbojiang  * This function is designed to be called from syncWithMaster(), so the
1401*572c4311Sfengbojiang  * following assumptions are made:
1402*572c4311Sfengbojiang  *
1403*572c4311Sfengbojiang  * 1) We pass the function an already connected socket "fd".
1404*572c4311Sfengbojiang  * 2) This function does not close the file descriptor "fd". However in case
1405*572c4311Sfengbojiang  *    of successful partial resynchronization, the function will reuse
1406*572c4311Sfengbojiang  *    'fd' as file descriptor of the server.master client structure.
1407*572c4311Sfengbojiang  *
1408*572c4311Sfengbojiang  * The function is split in two halves: if read_reply is 0, the function
1409*572c4311Sfengbojiang  * writes the PSYNC command on the socket, and a new function call is
1410*572c4311Sfengbojiang  * needed, with read_reply set to 1, in order to read the reply of the
1411*572c4311Sfengbojiang  * command. This is useful in order to support non blocking operations, so
1412*572c4311Sfengbojiang  * that we write, return into the event loop, and read when there are data.
1413*572c4311Sfengbojiang  *
1414*572c4311Sfengbojiang  * When read_reply is 0 the function returns PSYNC_WRITE_ERR if there
1415*572c4311Sfengbojiang  * was a write error, or PSYNC_WAIT_REPLY to signal we need another call
1416*572c4311Sfengbojiang  * with read_reply set to 1. However even when read_reply is set to 1
1417*572c4311Sfengbojiang  * the function may return PSYNC_WAIT_REPLY again to signal there were
1418*572c4311Sfengbojiang  * insufficient data to read to complete its work. We should re-enter
1419*572c4311Sfengbojiang  * into the event loop and wait in such a case.
1420*572c4311Sfengbojiang  *
1421*572c4311Sfengbojiang  * The function returns:
1422*572c4311Sfengbojiang  *
1423*572c4311Sfengbojiang  * PSYNC_CONTINUE: If the PSYNC command succeeded and we can continue.
1424*572c4311Sfengbojiang  * PSYNC_FULLRESYNC: If PSYNC is supported but a full resync is needed.
1425*572c4311Sfengbojiang  *                   In this case the master run_id and global replication
1426*572c4311Sfengbojiang  *                   offset is saved.
1427*572c4311Sfengbojiang  * PSYNC_NOT_SUPPORTED: If the server does not understand PSYNC at all and
1428*572c4311Sfengbojiang  *                      the caller should fall back to SYNC.
1429*572c4311Sfengbojiang  * PSYNC_WRITE_ERROR: There was an error writing the command to the socket.
1430*572c4311Sfengbojiang  * PSYNC_WAIT_REPLY: Call again the function with read_reply set to 1.
1431*572c4311Sfengbojiang  * PSYNC_TRY_LATER: Master is currently in a transient error condition.
1432*572c4311Sfengbojiang  *
1433*572c4311Sfengbojiang  * Notable side effects:
1434*572c4311Sfengbojiang  *
1435*572c4311Sfengbojiang  * 1) As a side effect of the function call the function removes the readable
1436*572c4311Sfengbojiang  *    event handler from "fd", unless the return value is PSYNC_WAIT_REPLY.
1437*572c4311Sfengbojiang  * 2) server.master_initial_offset is set to the right value according
1438*572c4311Sfengbojiang  *    to the master reply. This will be used to populate the 'server.master'
1439*572c4311Sfengbojiang  *    structure replication offset.
1440*572c4311Sfengbojiang  */
1441*572c4311Sfengbojiang 
1442*572c4311Sfengbojiang #define PSYNC_WRITE_ERROR 0
1443*572c4311Sfengbojiang #define PSYNC_WAIT_REPLY 1
1444*572c4311Sfengbojiang #define PSYNC_CONTINUE 2
1445*572c4311Sfengbojiang #define PSYNC_FULLRESYNC 3
1446*572c4311Sfengbojiang #define PSYNC_NOT_SUPPORTED 4
1447*572c4311Sfengbojiang #define PSYNC_TRY_LATER 5
slaveTryPartialResynchronization(int fd,int read_reply)1448*572c4311Sfengbojiang int slaveTryPartialResynchronization(int fd, int read_reply) {
1449*572c4311Sfengbojiang     char *psync_replid;
1450*572c4311Sfengbojiang     char psync_offset[32];
1451*572c4311Sfengbojiang     sds reply;
1452*572c4311Sfengbojiang 
1453*572c4311Sfengbojiang     /* Writing half */
1454*572c4311Sfengbojiang     if (!read_reply) {
1455*572c4311Sfengbojiang         /* Initially set master_initial_offset to -1 to mark the current
1456*572c4311Sfengbojiang          * master run_id and offset as not valid. Later if we'll be able to do
1457*572c4311Sfengbojiang          * a FULL resync using the PSYNC command we'll set the offset at the
1458*572c4311Sfengbojiang          * right value, so that this information will be propagated to the
1459*572c4311Sfengbojiang          * client structure representing the master into server.master. */
1460*572c4311Sfengbojiang         server.master_initial_offset = -1;
1461*572c4311Sfengbojiang 
1462*572c4311Sfengbojiang         if (server.cached_master) {
1463*572c4311Sfengbojiang             psync_replid = server.cached_master->replid;
1464*572c4311Sfengbojiang             snprintf(psync_offset,sizeof(psync_offset),"%lld", server.cached_master->reploff+1);
1465*572c4311Sfengbojiang             serverLog(LL_NOTICE,"Trying a partial resynchronization (request %s:%s).", psync_replid, psync_offset);
1466*572c4311Sfengbojiang         } else {
1467*572c4311Sfengbojiang             serverLog(LL_NOTICE,"Partial resynchronization not possible (no cached master)");
1468*572c4311Sfengbojiang             psync_replid = "?";
1469*572c4311Sfengbojiang             memcpy(psync_offset,"-1",3);
1470*572c4311Sfengbojiang         }
1471*572c4311Sfengbojiang 
1472*572c4311Sfengbojiang         /* Issue the PSYNC command */
1473*572c4311Sfengbojiang         reply = sendSynchronousCommand(SYNC_CMD_WRITE,fd,"PSYNC",psync_replid,psync_offset,NULL);
1474*572c4311Sfengbojiang         if (reply != NULL) {
1475*572c4311Sfengbojiang             serverLog(LL_WARNING,"Unable to send PSYNC to master: %s",reply);
1476*572c4311Sfengbojiang             sdsfree(reply);
1477*572c4311Sfengbojiang             aeDeleteFileEvent(server.el,fd,AE_READABLE);
1478*572c4311Sfengbojiang             return PSYNC_WRITE_ERROR;
1479*572c4311Sfengbojiang         }
1480*572c4311Sfengbojiang         return PSYNC_WAIT_REPLY;
1481*572c4311Sfengbojiang     }
1482*572c4311Sfengbojiang 
1483*572c4311Sfengbojiang     /* Reading half */
1484*572c4311Sfengbojiang     reply = sendSynchronousCommand(SYNC_CMD_READ,fd,NULL);
1485*572c4311Sfengbojiang     if (sdslen(reply) == 0) {
1486*572c4311Sfengbojiang         /* The master may send empty newlines after it receives PSYNC
1487*572c4311Sfengbojiang          * and before to reply, just to keep the connection alive. */
1488*572c4311Sfengbojiang         sdsfree(reply);
1489*572c4311Sfengbojiang         return PSYNC_WAIT_REPLY;
1490*572c4311Sfengbojiang     }
1491*572c4311Sfengbojiang 
1492*572c4311Sfengbojiang     aeDeleteFileEvent(server.el,fd,AE_READABLE);
1493*572c4311Sfengbojiang 
1494*572c4311Sfengbojiang     if (!strncmp(reply,"+FULLRESYNC",11)) {
1495*572c4311Sfengbojiang         char *replid = NULL, *offset = NULL;
1496*572c4311Sfengbojiang 
1497*572c4311Sfengbojiang         /* FULL RESYNC, parse the reply in order to extract the run id
1498*572c4311Sfengbojiang          * and the replication offset. */
1499*572c4311Sfengbojiang         replid = strchr(reply,' ');
1500*572c4311Sfengbojiang         if (replid) {
1501*572c4311Sfengbojiang             replid++;
1502*572c4311Sfengbojiang             offset = strchr(replid,' ');
1503*572c4311Sfengbojiang             if (offset) offset++;
1504*572c4311Sfengbojiang         }
1505*572c4311Sfengbojiang         if (!replid || !offset || (offset-replid-1) != CONFIG_RUN_ID_SIZE) {
1506*572c4311Sfengbojiang             serverLog(LL_WARNING,
1507*572c4311Sfengbojiang                 "Master replied with wrong +FULLRESYNC syntax.");
1508*572c4311Sfengbojiang             /* This is an unexpected condition, actually the +FULLRESYNC
1509*572c4311Sfengbojiang              * reply means that the master supports PSYNC, but the reply
1510*572c4311Sfengbojiang              * format seems wrong. To stay safe we blank the master
1511*572c4311Sfengbojiang              * replid to make sure next PSYNCs will fail. */
1512*572c4311Sfengbojiang             memset(server.master_replid,0,CONFIG_RUN_ID_SIZE+1);
1513*572c4311Sfengbojiang         } else {
1514*572c4311Sfengbojiang             memcpy(server.master_replid, replid, offset-replid-1);
1515*572c4311Sfengbojiang             server.master_replid[CONFIG_RUN_ID_SIZE] = '\0';
1516*572c4311Sfengbojiang             server.master_initial_offset = strtoll(offset,NULL,10);
1517*572c4311Sfengbojiang             serverLog(LL_NOTICE,"Full resync from master: %s:%lld",
1518*572c4311Sfengbojiang                 server.master_replid,
1519*572c4311Sfengbojiang                 server.master_initial_offset);
1520*572c4311Sfengbojiang         }
1521*572c4311Sfengbojiang         /* We are going to full resync, discard the cached master structure. */
1522*572c4311Sfengbojiang         replicationDiscardCachedMaster();
1523*572c4311Sfengbojiang         sdsfree(reply);
1524*572c4311Sfengbojiang         return PSYNC_FULLRESYNC;
1525*572c4311Sfengbojiang     }
1526*572c4311Sfengbojiang 
1527*572c4311Sfengbojiang     if (!strncmp(reply,"+CONTINUE",9)) {
1528*572c4311Sfengbojiang         /* Partial resync was accepted. */
1529*572c4311Sfengbojiang         serverLog(LL_NOTICE,
1530*572c4311Sfengbojiang             "Successful partial resynchronization with master.");
1531*572c4311Sfengbojiang 
1532*572c4311Sfengbojiang         /* Check the new replication ID advertised by the master. If it
1533*572c4311Sfengbojiang          * changed, we need to set the new ID as primary ID, and set or
1534*572c4311Sfengbojiang          * secondary ID as the old master ID up to the current offset, so
1535*572c4311Sfengbojiang          * that our sub-slaves will be able to PSYNC with us after a
1536*572c4311Sfengbojiang          * disconnection. */
1537*572c4311Sfengbojiang         char *start = reply+10;
1538*572c4311Sfengbojiang         char *end = reply+9;
1539*572c4311Sfengbojiang         while(end[0] != '\r' && end[0] != '\n' && end[0] != '\0') end++;
1540*572c4311Sfengbojiang         if (end-start == CONFIG_RUN_ID_SIZE) {
1541*572c4311Sfengbojiang             char new[CONFIG_RUN_ID_SIZE+1];
1542*572c4311Sfengbojiang             memcpy(new,start,CONFIG_RUN_ID_SIZE);
1543*572c4311Sfengbojiang             new[CONFIG_RUN_ID_SIZE] = '\0';
1544*572c4311Sfengbojiang 
1545*572c4311Sfengbojiang             if (strcmp(new,server.cached_master->replid)) {
1546*572c4311Sfengbojiang                 /* Master ID changed. */
1547*572c4311Sfengbojiang                 serverLog(LL_WARNING,"Master replication ID changed to %s",new);
1548*572c4311Sfengbojiang 
1549*572c4311Sfengbojiang                 /* Set the old ID as our ID2, up to the current offset+1. */
1550*572c4311Sfengbojiang                 memcpy(server.replid2,server.cached_master->replid,
1551*572c4311Sfengbojiang                     sizeof(server.replid2));
1552*572c4311Sfengbojiang                 server.second_replid_offset = server.master_repl_offset+1;
1553*572c4311Sfengbojiang 
1554*572c4311Sfengbojiang                 /* Update the cached master ID and our own primary ID to the
1555*572c4311Sfengbojiang                  * new one. */
1556*572c4311Sfengbojiang                 memcpy(server.replid,new,sizeof(server.replid));
1557*572c4311Sfengbojiang                 memcpy(server.cached_master->replid,new,sizeof(server.replid));
1558*572c4311Sfengbojiang 
1559*572c4311Sfengbojiang                 /* Disconnect all the sub-slaves: they need to be notified. */
1560*572c4311Sfengbojiang                 disconnectSlaves();
1561*572c4311Sfengbojiang             }
1562*572c4311Sfengbojiang         }
1563*572c4311Sfengbojiang 
1564*572c4311Sfengbojiang         /* Setup the replication to continue. */
1565*572c4311Sfengbojiang         sdsfree(reply);
1566*572c4311Sfengbojiang         replicationResurrectCachedMaster(fd);
1567*572c4311Sfengbojiang 
1568*572c4311Sfengbojiang         /* If this instance was restarted and we read the metadata to
1569*572c4311Sfengbojiang          * PSYNC from the persistence file, our replication backlog could
1570*572c4311Sfengbojiang          * be still not initialized. Create it. */
1571*572c4311Sfengbojiang         if (server.repl_backlog == NULL) createReplicationBacklog();
1572*572c4311Sfengbojiang         return PSYNC_CONTINUE;
1573*572c4311Sfengbojiang     }
1574*572c4311Sfengbojiang 
1575*572c4311Sfengbojiang     /* If we reach this point we received either an error (since the master does
1576*572c4311Sfengbojiang      * not understand PSYNC or because it is in a special state and cannot
1577*572c4311Sfengbojiang      * serve our request), or an unexpected reply from the master.
1578*572c4311Sfengbojiang      *
1579*572c4311Sfengbojiang      * Return PSYNC_NOT_SUPPORTED on errors we don't understand, otherwise
1580*572c4311Sfengbojiang      * return PSYNC_TRY_LATER if we believe this is a transient error. */
1581*572c4311Sfengbojiang 
1582*572c4311Sfengbojiang     if (!strncmp(reply,"-NOMASTERLINK",13) ||
1583*572c4311Sfengbojiang         !strncmp(reply,"-LOADING",8))
1584*572c4311Sfengbojiang     {
1585*572c4311Sfengbojiang         serverLog(LL_NOTICE,
1586*572c4311Sfengbojiang             "Master is currently unable to PSYNC "
1587*572c4311Sfengbojiang             "but should be in the future: %s", reply);
1588*572c4311Sfengbojiang         sdsfree(reply);
1589*572c4311Sfengbojiang         return PSYNC_TRY_LATER;
1590*572c4311Sfengbojiang     }
1591*572c4311Sfengbojiang 
1592*572c4311Sfengbojiang     if (strncmp(reply,"-ERR",4)) {
1593*572c4311Sfengbojiang         /* If it's not an error, log the unexpected event. */
1594*572c4311Sfengbojiang         serverLog(LL_WARNING,
1595*572c4311Sfengbojiang             "Unexpected reply to PSYNC from master: %s", reply);
1596*572c4311Sfengbojiang     } else {
1597*572c4311Sfengbojiang         serverLog(LL_NOTICE,
1598*572c4311Sfengbojiang             "Master does not support PSYNC or is in "
1599*572c4311Sfengbojiang             "error state (reply: %s)", reply);
1600*572c4311Sfengbojiang     }
1601*572c4311Sfengbojiang     sdsfree(reply);
1602*572c4311Sfengbojiang     replicationDiscardCachedMaster();
1603*572c4311Sfengbojiang     return PSYNC_NOT_SUPPORTED;
1604*572c4311Sfengbojiang }
1605*572c4311Sfengbojiang 
1606*572c4311Sfengbojiang /* This handler fires when the non blocking connect was able to
1607*572c4311Sfengbojiang  * establish a connection with the master. */
syncWithMaster(aeEventLoop * el,int fd,void * privdata,int mask)1608*572c4311Sfengbojiang void syncWithMaster(aeEventLoop *el, int fd, void *privdata, int mask) {
1609*572c4311Sfengbojiang     char tmpfile[256], *err = NULL;
1610*572c4311Sfengbojiang     int dfd = -1, maxtries = 5;
1611*572c4311Sfengbojiang     int sockerr = 0, psync_result;
1612*572c4311Sfengbojiang     socklen_t errlen = sizeof(sockerr);
1613*572c4311Sfengbojiang     UNUSED(el);
1614*572c4311Sfengbojiang     UNUSED(privdata);
1615*572c4311Sfengbojiang     UNUSED(mask);
1616*572c4311Sfengbojiang 
1617*572c4311Sfengbojiang     /* If this event fired after the user turned the instance into a master
1618*572c4311Sfengbojiang      * with SLAVEOF NO ONE we must just return ASAP. */
1619*572c4311Sfengbojiang     if (server.repl_state == REPL_STATE_NONE) {
1620*572c4311Sfengbojiang         close(fd);
1621*572c4311Sfengbojiang         return;
1622*572c4311Sfengbojiang     }
1623*572c4311Sfengbojiang 
1624*572c4311Sfengbojiang     /* Check for errors in the socket: after a non blocking connect() we
1625*572c4311Sfengbojiang      * may find that the socket is in error state. */
1626*572c4311Sfengbojiang     if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &sockerr, &errlen) == -1)
1627*572c4311Sfengbojiang         sockerr = errno;
1628*572c4311Sfengbojiang     if (sockerr) {
1629*572c4311Sfengbojiang         serverLog(LL_WARNING,"Error condition on socket for SYNC: %s",
1630*572c4311Sfengbojiang             strerror(sockerr));
1631*572c4311Sfengbojiang         goto error;
1632*572c4311Sfengbojiang     }
1633*572c4311Sfengbojiang 
1634*572c4311Sfengbojiang     /* Send a PING to check the master is able to reply without errors. */
1635*572c4311Sfengbojiang     if (server.repl_state == REPL_STATE_CONNECTING) {
1636*572c4311Sfengbojiang         serverLog(LL_NOTICE,"Non blocking connect for SYNC fired the event.");
1637*572c4311Sfengbojiang         /* Delete the writable event so that the readable event remains
1638*572c4311Sfengbojiang          * registered and we can wait for the PONG reply. */
1639*572c4311Sfengbojiang         aeDeleteFileEvent(server.el,fd,AE_WRITABLE);
1640*572c4311Sfengbojiang         server.repl_state = REPL_STATE_RECEIVE_PONG;
1641*572c4311Sfengbojiang         /* Send the PING, don't check for errors at all, we have the timeout
1642*572c4311Sfengbojiang          * that will take care about this. */
1643*572c4311Sfengbojiang         err = sendSynchronousCommand(SYNC_CMD_WRITE,fd,"PING",NULL);
1644*572c4311Sfengbojiang         if (err) goto write_error;
1645*572c4311Sfengbojiang         return;
1646*572c4311Sfengbojiang     }
1647*572c4311Sfengbojiang 
1648*572c4311Sfengbojiang     /* Receive the PONG command. */
1649*572c4311Sfengbojiang     if (server.repl_state == REPL_STATE_RECEIVE_PONG) {
1650*572c4311Sfengbojiang         err = sendSynchronousCommand(SYNC_CMD_READ,fd,NULL);
1651*572c4311Sfengbojiang 
1652*572c4311Sfengbojiang         /* We accept only two replies as valid, a positive +PONG reply
1653*572c4311Sfengbojiang          * (we just check for "+") or an authentication error.
1654*572c4311Sfengbojiang          * Note that older versions of Redis replied with "operation not
1655*572c4311Sfengbojiang          * permitted" instead of using a proper error code, so we test
1656*572c4311Sfengbojiang          * both. */
1657*572c4311Sfengbojiang         if (err[0] != '+' &&
1658*572c4311Sfengbojiang             strncmp(err,"-NOAUTH",7) != 0 &&
1659*572c4311Sfengbojiang             strncmp(err,"-ERR operation not permitted",28) != 0)
1660*572c4311Sfengbojiang         {
1661*572c4311Sfengbojiang             serverLog(LL_WARNING,"Error reply to PING from master: '%s'",err);
1662*572c4311Sfengbojiang             sdsfree(err);
1663*572c4311Sfengbojiang             goto error;
1664*572c4311Sfengbojiang         } else {
1665*572c4311Sfengbojiang             serverLog(LL_NOTICE,
1666*572c4311Sfengbojiang                 "Master replied to PING, replication can continue...");
1667*572c4311Sfengbojiang         }
1668*572c4311Sfengbojiang         sdsfree(err);
1669*572c4311Sfengbojiang         server.repl_state = REPL_STATE_SEND_AUTH;
1670*572c4311Sfengbojiang     }
1671*572c4311Sfengbojiang 
1672*572c4311Sfengbojiang     /* AUTH with the master if required. */
1673*572c4311Sfengbojiang     if (server.repl_state == REPL_STATE_SEND_AUTH) {
1674*572c4311Sfengbojiang         if (server.masterauth) {
1675*572c4311Sfengbojiang             err = sendSynchronousCommand(SYNC_CMD_WRITE,fd,"AUTH",server.masterauth,NULL);
1676*572c4311Sfengbojiang             if (err) goto write_error;
1677*572c4311Sfengbojiang             server.repl_state = REPL_STATE_RECEIVE_AUTH;
1678*572c4311Sfengbojiang             return;
1679*572c4311Sfengbojiang         } else {
1680*572c4311Sfengbojiang             server.repl_state = REPL_STATE_SEND_PORT;
1681*572c4311Sfengbojiang         }
1682*572c4311Sfengbojiang     }
1683*572c4311Sfengbojiang 
1684*572c4311Sfengbojiang     /* Receive AUTH reply. */
1685*572c4311Sfengbojiang     if (server.repl_state == REPL_STATE_RECEIVE_AUTH) {
1686*572c4311Sfengbojiang         err = sendSynchronousCommand(SYNC_CMD_READ,fd,NULL);
1687*572c4311Sfengbojiang         if (err[0] == '-') {
1688*572c4311Sfengbojiang             serverLog(LL_WARNING,"Unable to AUTH to MASTER: %s",err);
1689*572c4311Sfengbojiang             sdsfree(err);
1690*572c4311Sfengbojiang             goto error;
1691*572c4311Sfengbojiang         }
1692*572c4311Sfengbojiang         sdsfree(err);
1693*572c4311Sfengbojiang         server.repl_state = REPL_STATE_SEND_PORT;
1694*572c4311Sfengbojiang     }
1695*572c4311Sfengbojiang 
1696*572c4311Sfengbojiang     /* Set the slave port, so that Master's INFO command can list the
1697*572c4311Sfengbojiang      * slave listening port correctly. */
1698*572c4311Sfengbojiang     if (server.repl_state == REPL_STATE_SEND_PORT) {
1699*572c4311Sfengbojiang         sds port = sdsfromlonglong(server.slave_announce_port ?
1700*572c4311Sfengbojiang             server.slave_announce_port : server.port);
1701*572c4311Sfengbojiang         err = sendSynchronousCommand(SYNC_CMD_WRITE,fd,"REPLCONF",
1702*572c4311Sfengbojiang                 "listening-port",port, NULL);
1703*572c4311Sfengbojiang         sdsfree(port);
1704*572c4311Sfengbojiang         if (err) goto write_error;
1705*572c4311Sfengbojiang         sdsfree(err);
1706*572c4311Sfengbojiang         server.repl_state = REPL_STATE_RECEIVE_PORT;
1707*572c4311Sfengbojiang         return;
1708*572c4311Sfengbojiang     }
1709*572c4311Sfengbojiang 
1710*572c4311Sfengbojiang     /* Receive REPLCONF listening-port reply. */
1711*572c4311Sfengbojiang     if (server.repl_state == REPL_STATE_RECEIVE_PORT) {
1712*572c4311Sfengbojiang         err = sendSynchronousCommand(SYNC_CMD_READ,fd,NULL);
1713*572c4311Sfengbojiang         /* Ignore the error if any, not all the Redis versions support
1714*572c4311Sfengbojiang          * REPLCONF listening-port. */
1715*572c4311Sfengbojiang         if (err[0] == '-') {
1716*572c4311Sfengbojiang             serverLog(LL_NOTICE,"(Non critical) Master does not understand "
1717*572c4311Sfengbojiang                                 "REPLCONF listening-port: %s", err);
1718*572c4311Sfengbojiang         }
1719*572c4311Sfengbojiang         sdsfree(err);
1720*572c4311Sfengbojiang         server.repl_state = REPL_STATE_SEND_IP;
1721*572c4311Sfengbojiang     }
1722*572c4311Sfengbojiang 
1723*572c4311Sfengbojiang     /* Skip REPLCONF ip-address if there is no slave-announce-ip option set. */
1724*572c4311Sfengbojiang     if (server.repl_state == REPL_STATE_SEND_IP &&
1725*572c4311Sfengbojiang         server.slave_announce_ip == NULL)
1726*572c4311Sfengbojiang     {
1727*572c4311Sfengbojiang             server.repl_state = REPL_STATE_SEND_CAPA;
1728*572c4311Sfengbojiang     }
1729*572c4311Sfengbojiang 
1730*572c4311Sfengbojiang     /* Set the slave ip, so that Master's INFO command can list the
1731*572c4311Sfengbojiang      * slave IP address port correctly in case of port forwarding or NAT. */
1732*572c4311Sfengbojiang     if (server.repl_state == REPL_STATE_SEND_IP) {
1733*572c4311Sfengbojiang         err = sendSynchronousCommand(SYNC_CMD_WRITE,fd,"REPLCONF",
1734*572c4311Sfengbojiang                 "ip-address",server.slave_announce_ip, NULL);
1735*572c4311Sfengbojiang         if (err) goto write_error;
1736*572c4311Sfengbojiang         sdsfree(err);
1737*572c4311Sfengbojiang         server.repl_state = REPL_STATE_RECEIVE_IP;
1738*572c4311Sfengbojiang         return;
1739*572c4311Sfengbojiang     }
1740*572c4311Sfengbojiang 
1741*572c4311Sfengbojiang     /* Receive REPLCONF ip-address reply. */
1742*572c4311Sfengbojiang     if (server.repl_state == REPL_STATE_RECEIVE_IP) {
1743*572c4311Sfengbojiang         err = sendSynchronousCommand(SYNC_CMD_READ,fd,NULL);
1744*572c4311Sfengbojiang         /* Ignore the error if any, not all the Redis versions support
1745*572c4311Sfengbojiang          * REPLCONF listening-port. */
1746*572c4311Sfengbojiang         if (err[0] == '-') {
1747*572c4311Sfengbojiang             serverLog(LL_NOTICE,"(Non critical) Master does not understand "
1748*572c4311Sfengbojiang                                 "REPLCONF ip-address: %s", err);
1749*572c4311Sfengbojiang         }
1750*572c4311Sfengbojiang         sdsfree(err);
1751*572c4311Sfengbojiang         server.repl_state = REPL_STATE_SEND_CAPA;
1752*572c4311Sfengbojiang     }
1753*572c4311Sfengbojiang 
1754*572c4311Sfengbojiang     /* Inform the master of our (slave) capabilities.
1755*572c4311Sfengbojiang      *
1756*572c4311Sfengbojiang      * EOF: supports EOF-style RDB transfer for diskless replication.
1757*572c4311Sfengbojiang      * PSYNC2: supports PSYNC v2, so understands +CONTINUE <new repl ID>.
1758*572c4311Sfengbojiang      *
1759*572c4311Sfengbojiang      * The master will ignore capabilities it does not understand. */
1760*572c4311Sfengbojiang     if (server.repl_state == REPL_STATE_SEND_CAPA) {
1761*572c4311Sfengbojiang         err = sendSynchronousCommand(SYNC_CMD_WRITE,fd,"REPLCONF",
1762*572c4311Sfengbojiang                 "capa","eof","capa","psync2",NULL);
1763*572c4311Sfengbojiang         if (err) goto write_error;
1764*572c4311Sfengbojiang         sdsfree(err);
1765*572c4311Sfengbojiang         server.repl_state = REPL_STATE_RECEIVE_CAPA;
1766*572c4311Sfengbojiang         return;
1767*572c4311Sfengbojiang     }
1768*572c4311Sfengbojiang 
1769*572c4311Sfengbojiang     /* Receive CAPA reply. */
1770*572c4311Sfengbojiang     if (server.repl_state == REPL_STATE_RECEIVE_CAPA) {
1771*572c4311Sfengbojiang         err = sendSynchronousCommand(SYNC_CMD_READ,fd,NULL);
1772*572c4311Sfengbojiang         /* Ignore the error if any, not all the Redis versions support
1773*572c4311Sfengbojiang          * REPLCONF capa. */
1774*572c4311Sfengbojiang         if (err[0] == '-') {
1775*572c4311Sfengbojiang             serverLog(LL_NOTICE,"(Non critical) Master does not understand "
1776*572c4311Sfengbojiang                                   "REPLCONF capa: %s", err);
1777*572c4311Sfengbojiang         }
1778*572c4311Sfengbojiang         sdsfree(err);
1779*572c4311Sfengbojiang         server.repl_state = REPL_STATE_SEND_PSYNC;
1780*572c4311Sfengbojiang     }
1781*572c4311Sfengbojiang 
1782*572c4311Sfengbojiang     /* Try a partial resynchonization. If we don't have a cached master
1783*572c4311Sfengbojiang      * slaveTryPartialResynchronization() will at least try to use PSYNC
1784*572c4311Sfengbojiang      * to start a full resynchronization so that we get the master run id
1785*572c4311Sfengbojiang      * and the global offset, to try a partial resync at the next
1786*572c4311Sfengbojiang      * reconnection attempt. */
1787*572c4311Sfengbojiang     if (server.repl_state == REPL_STATE_SEND_PSYNC) {
1788*572c4311Sfengbojiang         if (slaveTryPartialResynchronization(fd,0) == PSYNC_WRITE_ERROR) {
1789*572c4311Sfengbojiang             err = sdsnew("Write error sending the PSYNC command.");
1790*572c4311Sfengbojiang             goto write_error;
1791*572c4311Sfengbojiang         }
1792*572c4311Sfengbojiang         server.repl_state = REPL_STATE_RECEIVE_PSYNC;
1793*572c4311Sfengbojiang         return;
1794*572c4311Sfengbojiang     }
1795*572c4311Sfengbojiang 
1796*572c4311Sfengbojiang     /* If reached this point, we should be in REPL_STATE_RECEIVE_PSYNC. */
1797*572c4311Sfengbojiang     if (server.repl_state != REPL_STATE_RECEIVE_PSYNC) {
1798*572c4311Sfengbojiang         serverLog(LL_WARNING,"syncWithMaster(): state machine error, "
1799*572c4311Sfengbojiang                              "state should be RECEIVE_PSYNC but is %d",
1800*572c4311Sfengbojiang                              server.repl_state);
1801*572c4311Sfengbojiang         goto error;
1802*572c4311Sfengbojiang     }
1803*572c4311Sfengbojiang 
1804*572c4311Sfengbojiang     psync_result = slaveTryPartialResynchronization(fd,1);
1805*572c4311Sfengbojiang     if (psync_result == PSYNC_WAIT_REPLY) return; /* Try again later... */
1806*572c4311Sfengbojiang 
1807*572c4311Sfengbojiang     /* If the master is in an transient error, we should try to PSYNC
1808*572c4311Sfengbojiang      * from scratch later, so go to the error path. This happens when
1809*572c4311Sfengbojiang      * the server is loading the dataset or is not connected with its
1810*572c4311Sfengbojiang      * master and so forth. */
1811*572c4311Sfengbojiang     if (psync_result == PSYNC_TRY_LATER) goto error;
1812*572c4311Sfengbojiang 
1813*572c4311Sfengbojiang     /* Note: if PSYNC does not return WAIT_REPLY, it will take care of
1814*572c4311Sfengbojiang      * uninstalling the read handler from the file descriptor. */
1815*572c4311Sfengbojiang 
1816*572c4311Sfengbojiang     if (psync_result == PSYNC_CONTINUE) {
1817*572c4311Sfengbojiang         serverLog(LL_NOTICE, "MASTER <-> REPLICA sync: Master accepted a Partial Resynchronization.");
1818*572c4311Sfengbojiang         return;
1819*572c4311Sfengbojiang     }
1820*572c4311Sfengbojiang 
1821*572c4311Sfengbojiang     /* PSYNC failed or is not supported: we want our slaves to resync with us
1822*572c4311Sfengbojiang      * as well, if we have any sub-slaves. The master may transfer us an
1823*572c4311Sfengbojiang      * entirely different data set and we have no way to incrementally feed
1824*572c4311Sfengbojiang      * our slaves after that. */
1825*572c4311Sfengbojiang     disconnectSlaves(); /* Force our slaves to resync with us as well. */
1826*572c4311Sfengbojiang     freeReplicationBacklog(); /* Don't allow our chained slaves to PSYNC. */
1827*572c4311Sfengbojiang 
1828*572c4311Sfengbojiang     /* Fall back to SYNC if needed. Otherwise psync_result == PSYNC_FULLRESYNC
1829*572c4311Sfengbojiang      * and the server.master_replid and master_initial_offset are
1830*572c4311Sfengbojiang      * already populated. */
1831*572c4311Sfengbojiang     if (psync_result == PSYNC_NOT_SUPPORTED) {
1832*572c4311Sfengbojiang         serverLog(LL_NOTICE,"Retrying with SYNC...");
1833*572c4311Sfengbojiang         if (syncWrite(fd,"SYNC\r\n",6,server.repl_syncio_timeout*1000) == -1) {
1834*572c4311Sfengbojiang             serverLog(LL_WARNING,"I/O error writing to MASTER: %s",
1835*572c4311Sfengbojiang                 strerror(errno));
1836*572c4311Sfengbojiang             goto error;
1837*572c4311Sfengbojiang         }
1838*572c4311Sfengbojiang     }
1839*572c4311Sfengbojiang 
1840*572c4311Sfengbojiang     /* Prepare a suitable temp file for bulk transfer */
1841*572c4311Sfengbojiang     while(maxtries--) {
1842*572c4311Sfengbojiang         snprintf(tmpfile,256,
1843*572c4311Sfengbojiang             "temp-%d.%ld.rdb",(int)server.unixtime,(long int)getpid());
1844*572c4311Sfengbojiang         dfd = open(tmpfile,O_CREAT|O_WRONLY|O_EXCL,0644);
1845*572c4311Sfengbojiang         if (dfd != -1) break;
1846*572c4311Sfengbojiang         sleep(1);
1847*572c4311Sfengbojiang     }
1848*572c4311Sfengbojiang     if (dfd == -1) {
1849*572c4311Sfengbojiang         serverLog(LL_WARNING,"Opening the temp file needed for MASTER <-> REPLICA synchronization: %s",strerror(errno));
1850*572c4311Sfengbojiang         goto error;
1851*572c4311Sfengbojiang     }
1852*572c4311Sfengbojiang 
1853*572c4311Sfengbojiang     /* Setup the non blocking download of the bulk file. */
1854*572c4311Sfengbojiang     if (aeCreateFileEvent(server.el,fd, AE_READABLE,readSyncBulkPayload,NULL)
1855*572c4311Sfengbojiang             == AE_ERR)
1856*572c4311Sfengbojiang     {
1857*572c4311Sfengbojiang         serverLog(LL_WARNING,
1858*572c4311Sfengbojiang             "Can't create readable event for SYNC: %s (fd=%d)",
1859*572c4311Sfengbojiang             strerror(errno),fd);
1860*572c4311Sfengbojiang         goto error;
1861*572c4311Sfengbojiang     }
1862*572c4311Sfengbojiang 
1863*572c4311Sfengbojiang     server.repl_state = REPL_STATE_TRANSFER;
1864*572c4311Sfengbojiang     server.repl_transfer_size = -1;
1865*572c4311Sfengbojiang     server.repl_transfer_read = 0;
1866*572c4311Sfengbojiang     server.repl_transfer_last_fsync_off = 0;
1867*572c4311Sfengbojiang     server.repl_transfer_fd = dfd;
1868*572c4311Sfengbojiang     server.repl_transfer_lastio = server.unixtime;
1869*572c4311Sfengbojiang     server.repl_transfer_tmpfile = zstrdup(tmpfile);
1870*572c4311Sfengbojiang     return;
1871*572c4311Sfengbojiang 
1872*572c4311Sfengbojiang error:
1873*572c4311Sfengbojiang     aeDeleteFileEvent(server.el,fd,AE_READABLE|AE_WRITABLE);
1874*572c4311Sfengbojiang     if (dfd != -1) close(dfd);
1875*572c4311Sfengbojiang     close(fd);
1876*572c4311Sfengbojiang     server.repl_transfer_s = -1;
1877*572c4311Sfengbojiang     server.repl_state = REPL_STATE_CONNECT;
1878*572c4311Sfengbojiang     return;
1879*572c4311Sfengbojiang 
1880*572c4311Sfengbojiang write_error: /* Handle sendSynchronousCommand(SYNC_CMD_WRITE) errors. */
1881*572c4311Sfengbojiang     serverLog(LL_WARNING,"Sending command to master in replication handshake: %s", err);
1882*572c4311Sfengbojiang     sdsfree(err);
1883*572c4311Sfengbojiang     goto error;
1884*572c4311Sfengbojiang }
1885*572c4311Sfengbojiang 
connectWithMaster(void)1886*572c4311Sfengbojiang int connectWithMaster(void) {
1887*572c4311Sfengbojiang     int fd;
1888*572c4311Sfengbojiang 
1889*572c4311Sfengbojiang     fd = anetTcpNonBlockBestEffortBindConnect(NULL,
1890*572c4311Sfengbojiang         server.masterhost,server.masterport,NET_FIRST_BIND_ADDR);
1891*572c4311Sfengbojiang     if (fd == -1) {
1892*572c4311Sfengbojiang         serverLog(LL_WARNING,"Unable to connect to MASTER: %s",
1893*572c4311Sfengbojiang             strerror(errno));
1894*572c4311Sfengbojiang         return C_ERR;
1895*572c4311Sfengbojiang     }
1896*572c4311Sfengbojiang 
1897*572c4311Sfengbojiang     if (aeCreateFileEvent(server.el,fd,AE_READABLE|AE_WRITABLE,syncWithMaster,NULL) ==
1898*572c4311Sfengbojiang             AE_ERR)
1899*572c4311Sfengbojiang     {
1900*572c4311Sfengbojiang         close(fd);
1901*572c4311Sfengbojiang         serverLog(LL_WARNING,"Can't create readable event for SYNC");
1902*572c4311Sfengbojiang         return C_ERR;
1903*572c4311Sfengbojiang     }
1904*572c4311Sfengbojiang 
1905*572c4311Sfengbojiang     server.repl_transfer_lastio = server.unixtime;
1906*572c4311Sfengbojiang     server.repl_transfer_s = fd;
1907*572c4311Sfengbojiang     server.repl_state = REPL_STATE_CONNECTING;
1908*572c4311Sfengbojiang     return C_OK;
1909*572c4311Sfengbojiang }
1910*572c4311Sfengbojiang 
1911*572c4311Sfengbojiang /* This function can be called when a non blocking connection is currently
1912*572c4311Sfengbojiang  * in progress to undo it.
1913*572c4311Sfengbojiang  * Never call this function directly, use cancelReplicationHandshake() instead.
1914*572c4311Sfengbojiang  */
undoConnectWithMaster(void)1915*572c4311Sfengbojiang void undoConnectWithMaster(void) {
1916*572c4311Sfengbojiang     int fd = server.repl_transfer_s;
1917*572c4311Sfengbojiang 
1918*572c4311Sfengbojiang     aeDeleteFileEvent(server.el,fd,AE_READABLE|AE_WRITABLE);
1919*572c4311Sfengbojiang     close(fd);
1920*572c4311Sfengbojiang     server.repl_transfer_s = -1;
1921*572c4311Sfengbojiang }
1922*572c4311Sfengbojiang 
1923*572c4311Sfengbojiang /* Abort the async download of the bulk dataset while SYNC-ing with master.
1924*572c4311Sfengbojiang  * Never call this function directly, use cancelReplicationHandshake() instead.
1925*572c4311Sfengbojiang  */
replicationAbortSyncTransfer(void)1926*572c4311Sfengbojiang void replicationAbortSyncTransfer(void) {
1927*572c4311Sfengbojiang     serverAssert(server.repl_state == REPL_STATE_TRANSFER);
1928*572c4311Sfengbojiang     undoConnectWithMaster();
1929*572c4311Sfengbojiang     close(server.repl_transfer_fd);
1930*572c4311Sfengbojiang     unlink(server.repl_transfer_tmpfile);
1931*572c4311Sfengbojiang     zfree(server.repl_transfer_tmpfile);
1932*572c4311Sfengbojiang }
1933*572c4311Sfengbojiang 
1934*572c4311Sfengbojiang /* This function aborts a non blocking replication attempt if there is one
1935*572c4311Sfengbojiang  * in progress, by canceling the non-blocking connect attempt or
1936*572c4311Sfengbojiang  * the initial bulk transfer.
1937*572c4311Sfengbojiang  *
1938*572c4311Sfengbojiang  * If there was a replication handshake in progress 1 is returned and
1939*572c4311Sfengbojiang  * the replication state (server.repl_state) set to REPL_STATE_CONNECT.
1940*572c4311Sfengbojiang  *
1941*572c4311Sfengbojiang  * Otherwise zero is returned and no operation is perforemd at all. */
cancelReplicationHandshake(void)1942*572c4311Sfengbojiang int cancelReplicationHandshake(void) {
1943*572c4311Sfengbojiang     if (server.repl_state == REPL_STATE_TRANSFER) {
1944*572c4311Sfengbojiang         replicationAbortSyncTransfer();
1945*572c4311Sfengbojiang         server.repl_state = REPL_STATE_CONNECT;
1946*572c4311Sfengbojiang     } else if (server.repl_state == REPL_STATE_CONNECTING ||
1947*572c4311Sfengbojiang                slaveIsInHandshakeState())
1948*572c4311Sfengbojiang     {
1949*572c4311Sfengbojiang         undoConnectWithMaster();
1950*572c4311Sfengbojiang         server.repl_state = REPL_STATE_CONNECT;
1951*572c4311Sfengbojiang     } else {
1952*572c4311Sfengbojiang         return 0;
1953*572c4311Sfengbojiang     }
1954*572c4311Sfengbojiang     return 1;
1955*572c4311Sfengbojiang }
1956*572c4311Sfengbojiang 
1957*572c4311Sfengbojiang /* Set replication to the specified master address and port. */
replicationSetMaster(char * ip,int port)1958*572c4311Sfengbojiang void replicationSetMaster(char *ip, int port) {
1959*572c4311Sfengbojiang     int was_master = server.masterhost == NULL;
1960*572c4311Sfengbojiang 
1961*572c4311Sfengbojiang     sdsfree(server.masterhost);
1962*572c4311Sfengbojiang     server.masterhost = sdsnew(ip);
1963*572c4311Sfengbojiang     server.masterport = port;
1964*572c4311Sfengbojiang     if (server.master) {
1965*572c4311Sfengbojiang         freeClient(server.master);
1966*572c4311Sfengbojiang     }
1967*572c4311Sfengbojiang     disconnectAllBlockedClients(); /* Clients blocked in master, now slave. */
1968*572c4311Sfengbojiang 
1969*572c4311Sfengbojiang     /* Force our slaves to resync with us as well. They may hopefully be able
1970*572c4311Sfengbojiang      * to partially resync with us, but we can notify the replid change. */
1971*572c4311Sfengbojiang     disconnectSlaves();
1972*572c4311Sfengbojiang     cancelReplicationHandshake();
1973*572c4311Sfengbojiang     /* Before destroying our master state, create a cached master using
1974*572c4311Sfengbojiang      * our own parameters, to later PSYNC with the new master. */
1975*572c4311Sfengbojiang     if (was_master) replicationCacheMasterUsingMyself();
1976*572c4311Sfengbojiang     server.repl_state = REPL_STATE_CONNECT;
1977*572c4311Sfengbojiang }
1978*572c4311Sfengbojiang 
1979*572c4311Sfengbojiang /* Cancel replication, setting the instance as a master itself. */
replicationUnsetMaster(void)1980*572c4311Sfengbojiang void replicationUnsetMaster(void) {
1981*572c4311Sfengbojiang     if (server.masterhost == NULL) return; /* Nothing to do. */
1982*572c4311Sfengbojiang     sdsfree(server.masterhost);
1983*572c4311Sfengbojiang     server.masterhost = NULL;
1984*572c4311Sfengbojiang     /* When a slave is turned into a master, the current replication ID
1985*572c4311Sfengbojiang      * (that was inherited from the master at synchronization time) is
1986*572c4311Sfengbojiang      * used as secondary ID up to the current offset, and a new replication
1987*572c4311Sfengbojiang      * ID is created to continue with a new replication history. */
1988*572c4311Sfengbojiang     shiftReplicationId();
1989*572c4311Sfengbojiang     if (server.master) freeClient(server.master);
1990*572c4311Sfengbojiang     replicationDiscardCachedMaster();
1991*572c4311Sfengbojiang     cancelReplicationHandshake();
1992*572c4311Sfengbojiang     /* Disconnecting all the slaves is required: we need to inform slaves
1993*572c4311Sfengbojiang      * of the replication ID change (see shiftReplicationId() call). However
1994*572c4311Sfengbojiang      * the slaves will be able to partially resync with us, so it will be
1995*572c4311Sfengbojiang      * a very fast reconnection. */
1996*572c4311Sfengbojiang     disconnectSlaves();
1997*572c4311Sfengbojiang     server.repl_state = REPL_STATE_NONE;
1998*572c4311Sfengbojiang 
1999*572c4311Sfengbojiang     /* We need to make sure the new master will start the replication stream
2000*572c4311Sfengbojiang      * with a SELECT statement. This is forced after a full resync, but
2001*572c4311Sfengbojiang      * with PSYNC version 2, there is no need for full resync after a
2002*572c4311Sfengbojiang      * master switch. */
2003*572c4311Sfengbojiang     server.slaveseldb = -1;
2004*572c4311Sfengbojiang 
2005*572c4311Sfengbojiang     /* Once we turn from slave to master, we consider the starting time without
2006*572c4311Sfengbojiang      * slaves (that is used to count the replication backlog time to live) as
2007*572c4311Sfengbojiang      * starting from now. Otherwise the backlog will be freed after a
2008*572c4311Sfengbojiang      * failover if slaves do not connect immediately. */
2009*572c4311Sfengbojiang     server.repl_no_slaves_since = server.unixtime;
2010*572c4311Sfengbojiang }
2011*572c4311Sfengbojiang 
2012*572c4311Sfengbojiang /* This function is called when the slave lose the connection with the
2013*572c4311Sfengbojiang  * master into an unexpected way. */
replicationHandleMasterDisconnection(void)2014*572c4311Sfengbojiang void replicationHandleMasterDisconnection(void) {
2015*572c4311Sfengbojiang     server.master = NULL;
2016*572c4311Sfengbojiang     server.repl_state = REPL_STATE_CONNECT;
2017*572c4311Sfengbojiang     server.repl_down_since = server.unixtime;
2018*572c4311Sfengbojiang     /* We lost connection with our master, don't disconnect slaves yet,
2019*572c4311Sfengbojiang      * maybe we'll be able to PSYNC with our master later. We'll disconnect
2020*572c4311Sfengbojiang      * the slaves only if we'll have to do a full resync with our master. */
2021*572c4311Sfengbojiang }
2022*572c4311Sfengbojiang 
replicaofCommand(client * c)2023*572c4311Sfengbojiang void replicaofCommand(client *c) {
2024*572c4311Sfengbojiang     /* SLAVEOF is not allowed in cluster mode as replication is automatically
2025*572c4311Sfengbojiang      * configured using the current address of the master node. */
2026*572c4311Sfengbojiang     if (server.cluster_enabled) {
2027*572c4311Sfengbojiang         addReplyError(c,"REPLICAOF not allowed in cluster mode.");
2028*572c4311Sfengbojiang         return;
2029*572c4311Sfengbojiang     }
2030*572c4311Sfengbojiang 
2031*572c4311Sfengbojiang     /* The special host/port combination "NO" "ONE" turns the instance
2032*572c4311Sfengbojiang      * into a master. Otherwise the new master address is set. */
2033*572c4311Sfengbojiang     if (!strcasecmp(c->argv[1]->ptr,"no") &&
2034*572c4311Sfengbojiang         !strcasecmp(c->argv[2]->ptr,"one")) {
2035*572c4311Sfengbojiang         if (server.masterhost) {
2036*572c4311Sfengbojiang             replicationUnsetMaster();
2037*572c4311Sfengbojiang             sds client = catClientInfoString(sdsempty(),c);
2038*572c4311Sfengbojiang             serverLog(LL_NOTICE,"MASTER MODE enabled (user request from '%s')",
2039*572c4311Sfengbojiang                 client);
2040*572c4311Sfengbojiang             sdsfree(client);
2041*572c4311Sfengbojiang         }
2042*572c4311Sfengbojiang     } else {
2043*572c4311Sfengbojiang         long port;
2044*572c4311Sfengbojiang 
2045*572c4311Sfengbojiang         if (c->flags & CLIENT_SLAVE)
2046*572c4311Sfengbojiang         {
2047*572c4311Sfengbojiang             /* If a client is already a replica they cannot run this command,
2048*572c4311Sfengbojiang              * because it involves flushing all replicas (including this
2049*572c4311Sfengbojiang              * client) */
2050*572c4311Sfengbojiang             addReplyError(c, "Command is not valid when client is a replica.");
2051*572c4311Sfengbojiang             return;
2052*572c4311Sfengbojiang         }
2053*572c4311Sfengbojiang 
2054*572c4311Sfengbojiang         if ((getLongFromObjectOrReply(c, c->argv[2], &port, NULL) != C_OK))
2055*572c4311Sfengbojiang             return;
2056*572c4311Sfengbojiang 
2057*572c4311Sfengbojiang         /* Check if we are already attached to the specified slave */
2058*572c4311Sfengbojiang         if (server.masterhost && !strcasecmp(server.masterhost,c->argv[1]->ptr)
2059*572c4311Sfengbojiang             && server.masterport == port) {
2060*572c4311Sfengbojiang             serverLog(LL_NOTICE,"REPLICAOF would result into synchronization with the master we are already connected with. No operation performed.");
2061*572c4311Sfengbojiang             addReplySds(c,sdsnew("+OK Already connected to specified master\r\n"));
2062*572c4311Sfengbojiang             return;
2063*572c4311Sfengbojiang         }
2064*572c4311Sfengbojiang         /* There was no previous master or the user specified a different one,
2065*572c4311Sfengbojiang          * we can continue. */
2066*572c4311Sfengbojiang         replicationSetMaster(c->argv[1]->ptr, port);
2067*572c4311Sfengbojiang         sds client = catClientInfoString(sdsempty(),c);
2068*572c4311Sfengbojiang         serverLog(LL_NOTICE,"REPLICAOF %s:%d enabled (user request from '%s')",
2069*572c4311Sfengbojiang             server.masterhost, server.masterport, client);
2070*572c4311Sfengbojiang         sdsfree(client);
2071*572c4311Sfengbojiang     }
2072*572c4311Sfengbojiang     addReply(c,shared.ok);
2073*572c4311Sfengbojiang }
2074*572c4311Sfengbojiang 
2075*572c4311Sfengbojiang /* ROLE command: provide information about the role of the instance
2076*572c4311Sfengbojiang  * (master or slave) and additional information related to replication
2077*572c4311Sfengbojiang  * in an easy to process format. */
roleCommand(client * c)2078*572c4311Sfengbojiang void roleCommand(client *c) {
2079*572c4311Sfengbojiang     if (server.masterhost == NULL) {
2080*572c4311Sfengbojiang         listIter li;
2081*572c4311Sfengbojiang         listNode *ln;
2082*572c4311Sfengbojiang         void *mbcount;
2083*572c4311Sfengbojiang         int slaves = 0;
2084*572c4311Sfengbojiang 
2085*572c4311Sfengbojiang         addReplyMultiBulkLen(c,3);
2086*572c4311Sfengbojiang         addReplyBulkCBuffer(c,"master",6);
2087*572c4311Sfengbojiang         addReplyLongLong(c,server.master_repl_offset);
2088*572c4311Sfengbojiang         mbcount = addDeferredMultiBulkLength(c);
2089*572c4311Sfengbojiang         listRewind(server.slaves,&li);
2090*572c4311Sfengbojiang         while((ln = listNext(&li))) {
2091*572c4311Sfengbojiang             client *slave = ln->value;
2092*572c4311Sfengbojiang             char ip[NET_IP_STR_LEN], *slaveip = slave->slave_ip;
2093*572c4311Sfengbojiang 
2094*572c4311Sfengbojiang             if (slaveip[0] == '\0') {
2095*572c4311Sfengbojiang                 if (anetPeerToString(slave->fd,ip,sizeof(ip),NULL) == -1)
2096*572c4311Sfengbojiang                     continue;
2097*572c4311Sfengbojiang                 slaveip = ip;
2098*572c4311Sfengbojiang             }
2099*572c4311Sfengbojiang             if (slave->replstate != SLAVE_STATE_ONLINE) continue;
2100*572c4311Sfengbojiang             addReplyMultiBulkLen(c,3);
2101*572c4311Sfengbojiang             addReplyBulkCString(c,slaveip);
2102*572c4311Sfengbojiang             addReplyBulkLongLong(c,slave->slave_listening_port);
2103*572c4311Sfengbojiang             addReplyBulkLongLong(c,slave->repl_ack_off);
2104*572c4311Sfengbojiang             slaves++;
2105*572c4311Sfengbojiang         }
2106*572c4311Sfengbojiang         setDeferredMultiBulkLength(c,mbcount,slaves);
2107*572c4311Sfengbojiang     } else {
2108*572c4311Sfengbojiang         char *slavestate = NULL;
2109*572c4311Sfengbojiang 
2110*572c4311Sfengbojiang         addReplyMultiBulkLen(c,5);
2111*572c4311Sfengbojiang         addReplyBulkCBuffer(c,"slave",5);
2112*572c4311Sfengbojiang         addReplyBulkCString(c,server.masterhost);
2113*572c4311Sfengbojiang         addReplyLongLong(c,server.masterport);
2114*572c4311Sfengbojiang         if (slaveIsInHandshakeState()) {
2115*572c4311Sfengbojiang             slavestate = "handshake";
2116*572c4311Sfengbojiang         } else {
2117*572c4311Sfengbojiang             switch(server.repl_state) {
2118*572c4311Sfengbojiang             case REPL_STATE_NONE: slavestate = "none"; break;
2119*572c4311Sfengbojiang             case REPL_STATE_CONNECT: slavestate = "connect"; break;
2120*572c4311Sfengbojiang             case REPL_STATE_CONNECTING: slavestate = "connecting"; break;
2121*572c4311Sfengbojiang             case REPL_STATE_TRANSFER: slavestate = "sync"; break;
2122*572c4311Sfengbojiang             case REPL_STATE_CONNECTED: slavestate = "connected"; break;
2123*572c4311Sfengbojiang             default: slavestate = "unknown"; break;
2124*572c4311Sfengbojiang             }
2125*572c4311Sfengbojiang         }
2126*572c4311Sfengbojiang         addReplyBulkCString(c,slavestate);
2127*572c4311Sfengbojiang         addReplyLongLong(c,server.master ? server.master->reploff : -1);
2128*572c4311Sfengbojiang     }
2129*572c4311Sfengbojiang }
2130*572c4311Sfengbojiang 
2131*572c4311Sfengbojiang /* Send a REPLCONF ACK command to the master to inform it about the current
2132*572c4311Sfengbojiang  * processed offset. If we are not connected with a master, the command has
2133*572c4311Sfengbojiang  * no effects. */
replicationSendAck(void)2134*572c4311Sfengbojiang void replicationSendAck(void) {
2135*572c4311Sfengbojiang     client *c = server.master;
2136*572c4311Sfengbojiang 
2137*572c4311Sfengbojiang     if (c != NULL) {
2138*572c4311Sfengbojiang         c->flags |= CLIENT_MASTER_FORCE_REPLY;
2139*572c4311Sfengbojiang         addReplyMultiBulkLen(c,3);
2140*572c4311Sfengbojiang         addReplyBulkCString(c,"REPLCONF");
2141*572c4311Sfengbojiang         addReplyBulkCString(c,"ACK");
2142*572c4311Sfengbojiang         addReplyBulkLongLong(c,c->reploff);
2143*572c4311Sfengbojiang         c->flags &= ~CLIENT_MASTER_FORCE_REPLY;
2144*572c4311Sfengbojiang     }
2145*572c4311Sfengbojiang }
2146*572c4311Sfengbojiang 
2147*572c4311Sfengbojiang /* ---------------------- MASTER CACHING FOR PSYNC -------------------------- */
2148*572c4311Sfengbojiang 
2149*572c4311Sfengbojiang /* In order to implement partial synchronization we need to be able to cache
2150*572c4311Sfengbojiang  * our master's client structure after a transient disconnection.
2151*572c4311Sfengbojiang  * It is cached into server.cached_master and flushed away using the following
2152*572c4311Sfengbojiang  * functions. */
2153*572c4311Sfengbojiang 
2154*572c4311Sfengbojiang /* This function is called by freeClient() in order to cache the master
2155*572c4311Sfengbojiang  * client structure instead of destroying it. freeClient() will return
2156*572c4311Sfengbojiang  * ASAP after this function returns, so every action needed to avoid problems
2157*572c4311Sfengbojiang  * with a client that is really "suspended" has to be done by this function.
2158*572c4311Sfengbojiang  *
2159*572c4311Sfengbojiang  * The other functions that will deal with the cached master are:
2160*572c4311Sfengbojiang  *
2161*572c4311Sfengbojiang  * replicationDiscardCachedMaster() that will make sure to kill the client
2162*572c4311Sfengbojiang  * as for some reason we don't want to use it in the future.
2163*572c4311Sfengbojiang  *
2164*572c4311Sfengbojiang  * replicationResurrectCachedMaster() that is used after a successful PSYNC
2165*572c4311Sfengbojiang  * handshake in order to reactivate the cached master.
2166*572c4311Sfengbojiang  */
replicationCacheMaster(client * c)2167*572c4311Sfengbojiang void replicationCacheMaster(client *c) {
2168*572c4311Sfengbojiang     serverAssert(server.master != NULL && server.cached_master == NULL);
2169*572c4311Sfengbojiang     serverLog(LL_NOTICE,"Caching the disconnected master state.");
2170*572c4311Sfengbojiang 
2171*572c4311Sfengbojiang     /* Unlink the client from the server structures. */
2172*572c4311Sfengbojiang     unlinkClient(c);
2173*572c4311Sfengbojiang 
2174*572c4311Sfengbojiang     /* Reset the master client so that's ready to accept new commands:
2175*572c4311Sfengbojiang      * we want to discard te non processed query buffers and non processed
2176*572c4311Sfengbojiang      * offsets, including pending transactions, already populated arguments,
2177*572c4311Sfengbojiang      * pending outputs to the master. */
2178*572c4311Sfengbojiang     sdsclear(server.master->querybuf);
2179*572c4311Sfengbojiang     sdsclear(server.master->pending_querybuf);
2180*572c4311Sfengbojiang     server.master->read_reploff = server.master->reploff;
2181*572c4311Sfengbojiang     if (c->flags & CLIENT_MULTI) discardTransaction(c);
2182*572c4311Sfengbojiang     listEmpty(c->reply);
2183*572c4311Sfengbojiang     c->sentlen = 0;
2184*572c4311Sfengbojiang     c->reply_bytes = 0;
2185*572c4311Sfengbojiang     c->bufpos = 0;
2186*572c4311Sfengbojiang     resetClient(c);
2187*572c4311Sfengbojiang 
2188*572c4311Sfengbojiang     /* Save the master. Server.master will be set to null later by
2189*572c4311Sfengbojiang      * replicationHandleMasterDisconnection(). */
2190*572c4311Sfengbojiang     server.cached_master = server.master;
2191*572c4311Sfengbojiang 
2192*572c4311Sfengbojiang     /* Invalidate the Peer ID cache. */
2193*572c4311Sfengbojiang     if (c->peerid) {
2194*572c4311Sfengbojiang         sdsfree(c->peerid);
2195*572c4311Sfengbojiang         c->peerid = NULL;
2196*572c4311Sfengbojiang     }
2197*572c4311Sfengbojiang 
2198*572c4311Sfengbojiang     /* Caching the master happens instead of the actual freeClient() call,
2199*572c4311Sfengbojiang      * so make sure to adjust the replication state. This function will
2200*572c4311Sfengbojiang      * also set server.master to NULL. */
2201*572c4311Sfengbojiang     replicationHandleMasterDisconnection();
2202*572c4311Sfengbojiang }
2203*572c4311Sfengbojiang 
2204*572c4311Sfengbojiang /* This function is called when a master is turend into a slave, in order to
2205*572c4311Sfengbojiang  * create from scratch a cached master for the new client, that will allow
2206*572c4311Sfengbojiang  * to PSYNC with the slave that was promoted as the new master after a
2207*572c4311Sfengbojiang  * failover.
2208*572c4311Sfengbojiang  *
2209*572c4311Sfengbojiang  * Assuming this instance was previously the master instance of the new master,
2210*572c4311Sfengbojiang  * the new master will accept its replication ID, and potentiall also the
2211*572c4311Sfengbojiang  * current offset if no data was lost during the failover. So we use our
2212*572c4311Sfengbojiang  * current replication ID and offset in order to synthesize a cached master. */
replicationCacheMasterUsingMyself(void)2213*572c4311Sfengbojiang void replicationCacheMasterUsingMyself(void) {
2214*572c4311Sfengbojiang     /* The master client we create can be set to any DBID, because
2215*572c4311Sfengbojiang      * the new master will start its replication stream with SELECT. */
2216*572c4311Sfengbojiang     server.master_initial_offset = server.master_repl_offset;
2217*572c4311Sfengbojiang     replicationCreateMasterClient(-1,-1);
2218*572c4311Sfengbojiang 
2219*572c4311Sfengbojiang     /* Use our own ID / offset. */
2220*572c4311Sfengbojiang     memcpy(server.master->replid, server.replid, sizeof(server.replid));
2221*572c4311Sfengbojiang 
2222*572c4311Sfengbojiang     /* Set as cached master. */
2223*572c4311Sfengbojiang     unlinkClient(server.master);
2224*572c4311Sfengbojiang     server.cached_master = server.master;
2225*572c4311Sfengbojiang     server.master = NULL;
2226*572c4311Sfengbojiang     serverLog(LL_NOTICE,"Before turning into a replica, using my master parameters to synthesize a cached master: I may be able to synchronize with the new master with just a partial transfer.");
2227*572c4311Sfengbojiang }
2228*572c4311Sfengbojiang 
2229*572c4311Sfengbojiang /* Free a cached master, called when there are no longer the conditions for
2230*572c4311Sfengbojiang  * a partial resync on reconnection. */
replicationDiscardCachedMaster(void)2231*572c4311Sfengbojiang void replicationDiscardCachedMaster(void) {
2232*572c4311Sfengbojiang     if (server.cached_master == NULL) return;
2233*572c4311Sfengbojiang 
2234*572c4311Sfengbojiang     serverLog(LL_NOTICE,"Discarding previously cached master state.");
2235*572c4311Sfengbojiang     server.cached_master->flags &= ~CLIENT_MASTER;
2236*572c4311Sfengbojiang     freeClient(server.cached_master);
2237*572c4311Sfengbojiang     server.cached_master = NULL;
2238*572c4311Sfengbojiang }
2239*572c4311Sfengbojiang 
2240*572c4311Sfengbojiang /* Turn the cached master into the current master, using the file descriptor
2241*572c4311Sfengbojiang  * passed as argument as the socket for the new master.
2242*572c4311Sfengbojiang  *
2243*572c4311Sfengbojiang  * This function is called when successfully setup a partial resynchronization
2244*572c4311Sfengbojiang  * so the stream of data that we'll receive will start from were this
2245*572c4311Sfengbojiang  * master left. */
replicationResurrectCachedMaster(int newfd)2246*572c4311Sfengbojiang void replicationResurrectCachedMaster(int newfd) {
2247*572c4311Sfengbojiang     server.master = server.cached_master;
2248*572c4311Sfengbojiang     server.cached_master = NULL;
2249*572c4311Sfengbojiang     server.master->fd = newfd;
2250*572c4311Sfengbojiang     server.master->flags &= ~(CLIENT_CLOSE_AFTER_REPLY|CLIENT_CLOSE_ASAP);
2251*572c4311Sfengbojiang     server.master->authenticated = 1;
2252*572c4311Sfengbojiang     server.master->lastinteraction = server.unixtime;
2253*572c4311Sfengbojiang     server.repl_state = REPL_STATE_CONNECTED;
2254*572c4311Sfengbojiang     server.repl_down_since = 0;
2255*572c4311Sfengbojiang 
2256*572c4311Sfengbojiang     /* Re-add to the list of clients. */
2257*572c4311Sfengbojiang     linkClient(server.master);
2258*572c4311Sfengbojiang     if (aeCreateFileEvent(server.el, newfd, AE_READABLE,
2259*572c4311Sfengbojiang                           readQueryFromClient, server.master)) {
2260*572c4311Sfengbojiang         serverLog(LL_WARNING,"Error resurrecting the cached master, impossible to add the readable handler: %s", strerror(errno));
2261*572c4311Sfengbojiang         freeClientAsync(server.master); /* Close ASAP. */
2262*572c4311Sfengbojiang     }
2263*572c4311Sfengbojiang 
2264*572c4311Sfengbojiang     /* We may also need to install the write handler as well if there is
2265*572c4311Sfengbojiang      * pending data in the write buffers. */
2266*572c4311Sfengbojiang     if (clientHasPendingReplies(server.master)) {
2267*572c4311Sfengbojiang         if (aeCreateFileEvent(server.el, newfd, AE_WRITABLE,
2268*572c4311Sfengbojiang                           sendReplyToClient, server.master)) {
2269*572c4311Sfengbojiang             serverLog(LL_WARNING,"Error resurrecting the cached master, impossible to add the writable handler: %s", strerror(errno));
2270*572c4311Sfengbojiang             freeClientAsync(server.master); /* Close ASAP. */
2271*572c4311Sfengbojiang         }
2272*572c4311Sfengbojiang     }
2273*572c4311Sfengbojiang }
2274*572c4311Sfengbojiang 
2275*572c4311Sfengbojiang /* ------------------------- MIN-SLAVES-TO-WRITE  --------------------------- */
2276*572c4311Sfengbojiang 
2277*572c4311Sfengbojiang /* This function counts the number of slaves with lag <= min-slaves-max-lag.
2278*572c4311Sfengbojiang  * If the option is active, the server will prevent writes if there are not
2279*572c4311Sfengbojiang  * enough connected slaves with the specified lag (or less). */
refreshGoodSlavesCount(void)2280*572c4311Sfengbojiang void refreshGoodSlavesCount(void) {
2281*572c4311Sfengbojiang     listIter li;
2282*572c4311Sfengbojiang     listNode *ln;
2283*572c4311Sfengbojiang     int good = 0;
2284*572c4311Sfengbojiang 
2285*572c4311Sfengbojiang     if (!server.repl_min_slaves_to_write ||
2286*572c4311Sfengbojiang         !server.repl_min_slaves_max_lag) return;
2287*572c4311Sfengbojiang 
2288*572c4311Sfengbojiang     listRewind(server.slaves,&li);
2289*572c4311Sfengbojiang     while((ln = listNext(&li))) {
2290*572c4311Sfengbojiang         client *slave = ln->value;
2291*572c4311Sfengbojiang         time_t lag = server.unixtime - slave->repl_ack_time;
2292*572c4311Sfengbojiang 
2293*572c4311Sfengbojiang         if (slave->replstate == SLAVE_STATE_ONLINE &&
2294*572c4311Sfengbojiang             lag <= server.repl_min_slaves_max_lag) good++;
2295*572c4311Sfengbojiang     }
2296*572c4311Sfengbojiang     server.repl_good_slaves_count = good;
2297*572c4311Sfengbojiang }
2298*572c4311Sfengbojiang 
2299*572c4311Sfengbojiang /* ----------------------- REPLICATION SCRIPT CACHE --------------------------
2300*572c4311Sfengbojiang  * The goal of this code is to keep track of scripts already sent to every
2301*572c4311Sfengbojiang  * connected slave, in order to be able to replicate EVALSHA as it is without
2302*572c4311Sfengbojiang  * translating it to EVAL every time it is possible.
2303*572c4311Sfengbojiang  *
2304*572c4311Sfengbojiang  * We use a capped collection implemented by a hash table for fast lookup
2305*572c4311Sfengbojiang  * of scripts we can send as EVALSHA, plus a linked list that is used for
2306*572c4311Sfengbojiang  * eviction of the oldest entry when the max number of items is reached.
2307*572c4311Sfengbojiang  *
2308*572c4311Sfengbojiang  * We don't care about taking a different cache for every different slave
2309*572c4311Sfengbojiang  * since to fill the cache again is not very costly, the goal of this code
2310*572c4311Sfengbojiang  * is to avoid that the same big script is trasmitted a big number of times
2311*572c4311Sfengbojiang  * per second wasting bandwidth and processor speed, but it is not a problem
2312*572c4311Sfengbojiang  * if we need to rebuild the cache from scratch from time to time, every used
2313*572c4311Sfengbojiang  * script will need to be transmitted a single time to reappear in the cache.
2314*572c4311Sfengbojiang  *
2315*572c4311Sfengbojiang  * This is how the system works:
2316*572c4311Sfengbojiang  *
2317*572c4311Sfengbojiang  * 1) Every time a new slave connects, we flush the whole script cache.
2318*572c4311Sfengbojiang  * 2) We only send as EVALSHA what was sent to the master as EVALSHA, without
2319*572c4311Sfengbojiang  *    trying to convert EVAL into EVALSHA specifically for slaves.
2320*572c4311Sfengbojiang  * 3) Every time we trasmit a script as EVAL to the slaves, we also add the
2321*572c4311Sfengbojiang  *    corresponding SHA1 of the script into the cache as we are sure every
2322*572c4311Sfengbojiang  *    slave knows about the script starting from now.
2323*572c4311Sfengbojiang  * 4) On SCRIPT FLUSH command, we replicate the command to all the slaves
2324*572c4311Sfengbojiang  *    and at the same time flush the script cache.
2325*572c4311Sfengbojiang  * 5) When the last slave disconnects, flush the cache.
2326*572c4311Sfengbojiang  * 6) We handle SCRIPT LOAD as well since that's how scripts are loaded
2327*572c4311Sfengbojiang  *    in the master sometimes.
2328*572c4311Sfengbojiang  */
2329*572c4311Sfengbojiang 
2330*572c4311Sfengbojiang /* Initialize the script cache, only called at startup. */
replicationScriptCacheInit(void)2331*572c4311Sfengbojiang void replicationScriptCacheInit(void) {
2332*572c4311Sfengbojiang     server.repl_scriptcache_size = 10000;
2333*572c4311Sfengbojiang     server.repl_scriptcache_dict = dictCreate(&replScriptCacheDictType,NULL);
2334*572c4311Sfengbojiang     server.repl_scriptcache_fifo = listCreate();
2335*572c4311Sfengbojiang }
2336*572c4311Sfengbojiang 
2337*572c4311Sfengbojiang /* Empty the script cache. Should be called every time we are no longer sure
2338*572c4311Sfengbojiang  * that every slave knows about all the scripts in our set, or when the
2339*572c4311Sfengbojiang  * current AOF "context" is no longer aware of the script. In general we
2340*572c4311Sfengbojiang  * should flush the cache:
2341*572c4311Sfengbojiang  *
2342*572c4311Sfengbojiang  * 1) Every time a new slave reconnects to this master and performs a
2343*572c4311Sfengbojiang  *    full SYNC (PSYNC does not require flushing).
2344*572c4311Sfengbojiang  * 2) Every time an AOF rewrite is performed.
2345*572c4311Sfengbojiang  * 3) Every time we are left without slaves at all, and AOF is off, in order
2346*572c4311Sfengbojiang  *    to reclaim otherwise unused memory.
2347*572c4311Sfengbojiang  */
replicationScriptCacheFlush(void)2348*572c4311Sfengbojiang void replicationScriptCacheFlush(void) {
2349*572c4311Sfengbojiang     dictEmpty(server.repl_scriptcache_dict,NULL);
2350*572c4311Sfengbojiang     listRelease(server.repl_scriptcache_fifo);
2351*572c4311Sfengbojiang     server.repl_scriptcache_fifo = listCreate();
2352*572c4311Sfengbojiang }
2353*572c4311Sfengbojiang 
2354*572c4311Sfengbojiang /* Add an entry into the script cache, if we reach max number of entries the
2355*572c4311Sfengbojiang  * oldest is removed from the list. */
replicationScriptCacheAdd(sds sha1)2356*572c4311Sfengbojiang void replicationScriptCacheAdd(sds sha1) {
2357*572c4311Sfengbojiang     int retval;
2358*572c4311Sfengbojiang     sds key = sdsdup(sha1);
2359*572c4311Sfengbojiang 
2360*572c4311Sfengbojiang     /* Evict oldest. */
2361*572c4311Sfengbojiang     if (listLength(server.repl_scriptcache_fifo) == server.repl_scriptcache_size)
2362*572c4311Sfengbojiang     {
2363*572c4311Sfengbojiang         listNode *ln = listLast(server.repl_scriptcache_fifo);
2364*572c4311Sfengbojiang         sds oldest = listNodeValue(ln);
2365*572c4311Sfengbojiang 
2366*572c4311Sfengbojiang         retval = dictDelete(server.repl_scriptcache_dict,oldest);
2367*572c4311Sfengbojiang         serverAssert(retval == DICT_OK);
2368*572c4311Sfengbojiang         listDelNode(server.repl_scriptcache_fifo,ln);
2369*572c4311Sfengbojiang     }
2370*572c4311Sfengbojiang 
2371*572c4311Sfengbojiang     /* Add current. */
2372*572c4311Sfengbojiang     retval = dictAdd(server.repl_scriptcache_dict,key,NULL);
2373*572c4311Sfengbojiang     listAddNodeHead(server.repl_scriptcache_fifo,key);
2374*572c4311Sfengbojiang     serverAssert(retval == DICT_OK);
2375*572c4311Sfengbojiang }
2376*572c4311Sfengbojiang 
2377*572c4311Sfengbojiang /* Returns non-zero if the specified entry exists inside the cache, that is,
2378*572c4311Sfengbojiang  * if all the slaves are aware of this script SHA1. */
replicationScriptCacheExists(sds sha1)2379*572c4311Sfengbojiang int replicationScriptCacheExists(sds sha1) {
2380*572c4311Sfengbojiang     return dictFind(server.repl_scriptcache_dict,sha1) != NULL;
2381*572c4311Sfengbojiang }
2382*572c4311Sfengbojiang 
2383*572c4311Sfengbojiang /* ----------------------- SYNCHRONOUS REPLICATION --------------------------
2384*572c4311Sfengbojiang  * Redis synchronous replication design can be summarized in points:
2385*572c4311Sfengbojiang  *
2386*572c4311Sfengbojiang  * - Redis masters have a global replication offset, used by PSYNC.
2387*572c4311Sfengbojiang  * - Master increment the offset every time new commands are sent to slaves.
2388*572c4311Sfengbojiang  * - Slaves ping back masters with the offset processed so far.
2389*572c4311Sfengbojiang  *
2390*572c4311Sfengbojiang  * So synchronous replication adds a new WAIT command in the form:
2391*572c4311Sfengbojiang  *
2392*572c4311Sfengbojiang  *   WAIT <num_replicas> <milliseconds_timeout>
2393*572c4311Sfengbojiang  *
2394*572c4311Sfengbojiang  * That returns the number of replicas that processed the query when
2395*572c4311Sfengbojiang  * we finally have at least num_replicas, or when the timeout was
2396*572c4311Sfengbojiang  * reached.
2397*572c4311Sfengbojiang  *
2398*572c4311Sfengbojiang  * The command is implemented in this way:
2399*572c4311Sfengbojiang  *
2400*572c4311Sfengbojiang  * - Every time a client processes a command, we remember the replication
2401*572c4311Sfengbojiang  *   offset after sending that command to the slaves.
2402*572c4311Sfengbojiang  * - When WAIT is called, we ask slaves to send an acknowledgement ASAP.
2403*572c4311Sfengbojiang  *   The client is blocked at the same time (see blocked.c).
2404*572c4311Sfengbojiang  * - Once we receive enough ACKs for a given offset or when the timeout
2405*572c4311Sfengbojiang  *   is reached, the WAIT command is unblocked and the reply sent to the
2406*572c4311Sfengbojiang  *   client.
2407*572c4311Sfengbojiang  */
2408*572c4311Sfengbojiang 
2409*572c4311Sfengbojiang /* This just set a flag so that we broadcast a REPLCONF GETACK command
2410*572c4311Sfengbojiang  * to all the slaves in the beforeSleep() function. Note that this way
2411*572c4311Sfengbojiang  * we "group" all the clients that want to wait for synchronouns replication
2412*572c4311Sfengbojiang  * in a given event loop iteration, and send a single GETACK for them all. */
replicationRequestAckFromSlaves(void)2413*572c4311Sfengbojiang void replicationRequestAckFromSlaves(void) {
2414*572c4311Sfengbojiang     server.get_ack_from_slaves = 1;
2415*572c4311Sfengbojiang }
2416*572c4311Sfengbojiang 
2417*572c4311Sfengbojiang /* Return the number of slaves that already acknowledged the specified
2418*572c4311Sfengbojiang  * replication offset. */
replicationCountAcksByOffset(long long offset)2419*572c4311Sfengbojiang int replicationCountAcksByOffset(long long offset) {
2420*572c4311Sfengbojiang     listIter li;
2421*572c4311Sfengbojiang     listNode *ln;
2422*572c4311Sfengbojiang     int count = 0;
2423*572c4311Sfengbojiang 
2424*572c4311Sfengbojiang     listRewind(server.slaves,&li);
2425*572c4311Sfengbojiang     while((ln = listNext(&li))) {
2426*572c4311Sfengbojiang         client *slave = ln->value;
2427*572c4311Sfengbojiang 
2428*572c4311Sfengbojiang         if (slave->replstate != SLAVE_STATE_ONLINE) continue;
2429*572c4311Sfengbojiang         if (slave->repl_ack_off >= offset) count++;
2430*572c4311Sfengbojiang     }
2431*572c4311Sfengbojiang     return count;
2432*572c4311Sfengbojiang }
2433*572c4311Sfengbojiang 
2434*572c4311Sfengbojiang /* WAIT for N replicas to acknowledge the processing of our latest
2435*572c4311Sfengbojiang  * write command (and all the previous commands). */
waitCommand(client * c)2436*572c4311Sfengbojiang void waitCommand(client *c) {
2437*572c4311Sfengbojiang     mstime_t timeout;
2438*572c4311Sfengbojiang     long numreplicas, ackreplicas;
2439*572c4311Sfengbojiang     long long offset = c->woff;
2440*572c4311Sfengbojiang 
2441*572c4311Sfengbojiang     if (server.masterhost) {
2442*572c4311Sfengbojiang         addReplyError(c,"WAIT cannot be used with replica instances. Please also note that since Redis 4.0 if a replica is configured to be writable (which is not the default) writes to replicas are just local and are not propagated.");
2443*572c4311Sfengbojiang         return;
2444*572c4311Sfengbojiang     }
2445*572c4311Sfengbojiang 
2446*572c4311Sfengbojiang     /* Argument parsing. */
2447*572c4311Sfengbojiang     if (getLongFromObjectOrReply(c,c->argv[1],&numreplicas,NULL) != C_OK)
2448*572c4311Sfengbojiang         return;
2449*572c4311Sfengbojiang     if (getTimeoutFromObjectOrReply(c,c->argv[2],&timeout,UNIT_MILLISECONDS)
2450*572c4311Sfengbojiang         != C_OK) return;
2451*572c4311Sfengbojiang 
2452*572c4311Sfengbojiang     /* First try without blocking at all. */
2453*572c4311Sfengbojiang     ackreplicas = replicationCountAcksByOffset(c->woff);
2454*572c4311Sfengbojiang     if (ackreplicas >= numreplicas || c->flags & CLIENT_MULTI) {
2455*572c4311Sfengbojiang         addReplyLongLong(c,ackreplicas);
2456*572c4311Sfengbojiang         return;
2457*572c4311Sfengbojiang     }
2458*572c4311Sfengbojiang 
2459*572c4311Sfengbojiang     /* Otherwise block the client and put it into our list of clients
2460*572c4311Sfengbojiang      * waiting for ack from slaves. */
2461*572c4311Sfengbojiang     c->bpop.timeout = timeout;
2462*572c4311Sfengbojiang     c->bpop.reploffset = offset;
2463*572c4311Sfengbojiang     c->bpop.numreplicas = numreplicas;
2464*572c4311Sfengbojiang     listAddNodeTail(server.clients_waiting_acks,c);
2465*572c4311Sfengbojiang     blockClient(c,BLOCKED_WAIT);
2466*572c4311Sfengbojiang 
2467*572c4311Sfengbojiang     /* Make sure that the server will send an ACK request to all the slaves
2468*572c4311Sfengbojiang      * before returning to the event loop. */
2469*572c4311Sfengbojiang     replicationRequestAckFromSlaves();
2470*572c4311Sfengbojiang }
2471*572c4311Sfengbojiang 
2472*572c4311Sfengbojiang /* This is called by unblockClient() to perform the blocking op type
2473*572c4311Sfengbojiang  * specific cleanup. We just remove the client from the list of clients
2474*572c4311Sfengbojiang  * waiting for replica acks. Never call it directly, call unblockClient()
2475*572c4311Sfengbojiang  * instead. */
unblockClientWaitingReplicas(client * c)2476*572c4311Sfengbojiang void unblockClientWaitingReplicas(client *c) {
2477*572c4311Sfengbojiang     listNode *ln = listSearchKey(server.clients_waiting_acks,c);
2478*572c4311Sfengbojiang     serverAssert(ln != NULL);
2479*572c4311Sfengbojiang     listDelNode(server.clients_waiting_acks,ln);
2480*572c4311Sfengbojiang }
2481*572c4311Sfengbojiang 
2482*572c4311Sfengbojiang /* Check if there are clients blocked in WAIT that can be unblocked since
2483*572c4311Sfengbojiang  * we received enough ACKs from slaves. */
processClientsWaitingReplicas(void)2484*572c4311Sfengbojiang void processClientsWaitingReplicas(void) {
2485*572c4311Sfengbojiang     long long last_offset = 0;
2486*572c4311Sfengbojiang     int last_numreplicas = 0;
2487*572c4311Sfengbojiang 
2488*572c4311Sfengbojiang     listIter li;
2489*572c4311Sfengbojiang     listNode *ln;
2490*572c4311Sfengbojiang 
2491*572c4311Sfengbojiang     listRewind(server.clients_waiting_acks,&li);
2492*572c4311Sfengbojiang     while((ln = listNext(&li))) {
2493*572c4311Sfengbojiang         client *c = ln->value;
2494*572c4311Sfengbojiang 
2495*572c4311Sfengbojiang         /* Every time we find a client that is satisfied for a given
2496*572c4311Sfengbojiang          * offset and number of replicas, we remember it so the next client
2497*572c4311Sfengbojiang          * may be unblocked without calling replicationCountAcksByOffset()
2498*572c4311Sfengbojiang          * if the requested offset / replicas were equal or less. */
2499*572c4311Sfengbojiang         if (last_offset && last_offset > c->bpop.reploffset &&
2500*572c4311Sfengbojiang                            last_numreplicas > c->bpop.numreplicas)
2501*572c4311Sfengbojiang         {
2502*572c4311Sfengbojiang             unblockClient(c);
2503*572c4311Sfengbojiang             addReplyLongLong(c,last_numreplicas);
2504*572c4311Sfengbojiang         } else {
2505*572c4311Sfengbojiang             int numreplicas = replicationCountAcksByOffset(c->bpop.reploffset);
2506*572c4311Sfengbojiang 
2507*572c4311Sfengbojiang             if (numreplicas >= c->bpop.numreplicas) {
2508*572c4311Sfengbojiang                 last_offset = c->bpop.reploffset;
2509*572c4311Sfengbojiang                 last_numreplicas = numreplicas;
2510*572c4311Sfengbojiang                 unblockClient(c);
2511*572c4311Sfengbojiang                 addReplyLongLong(c,numreplicas);
2512*572c4311Sfengbojiang             }
2513*572c4311Sfengbojiang         }
2514*572c4311Sfengbojiang     }
2515*572c4311Sfengbojiang }
2516*572c4311Sfengbojiang 
2517*572c4311Sfengbojiang /* Return the slave replication offset for this instance, that is
2518*572c4311Sfengbojiang  * the offset for which we already processed the master replication stream. */
replicationGetSlaveOffset(void)2519*572c4311Sfengbojiang long long replicationGetSlaveOffset(void) {
2520*572c4311Sfengbojiang     long long offset = 0;
2521*572c4311Sfengbojiang 
2522*572c4311Sfengbojiang     if (server.masterhost != NULL) {
2523*572c4311Sfengbojiang         if (server.master) {
2524*572c4311Sfengbojiang             offset = server.master->reploff;
2525*572c4311Sfengbojiang         } else if (server.cached_master) {
2526*572c4311Sfengbojiang             offset = server.cached_master->reploff;
2527*572c4311Sfengbojiang         }
2528*572c4311Sfengbojiang     }
2529*572c4311Sfengbojiang     /* offset may be -1 when the master does not support it at all, however
2530*572c4311Sfengbojiang      * this function is designed to return an offset that can express the
2531*572c4311Sfengbojiang      * amount of data processed by the master, so we return a positive
2532*572c4311Sfengbojiang      * integer. */
2533*572c4311Sfengbojiang     if (offset < 0) offset = 0;
2534*572c4311Sfengbojiang     return offset;
2535*572c4311Sfengbojiang }
2536*572c4311Sfengbojiang 
2537*572c4311Sfengbojiang /* --------------------------- REPLICATION CRON  ---------------------------- */
2538*572c4311Sfengbojiang 
2539*572c4311Sfengbojiang /* Replication cron function, called 1 time per second. */
replicationCron(void)2540*572c4311Sfengbojiang void replicationCron(void) {
2541*572c4311Sfengbojiang     static long long replication_cron_loops = 0;
2542*572c4311Sfengbojiang 
2543*572c4311Sfengbojiang     /* Non blocking connection timeout? */
2544*572c4311Sfengbojiang     if (server.masterhost &&
2545*572c4311Sfengbojiang         (server.repl_state == REPL_STATE_CONNECTING ||
2546*572c4311Sfengbojiang          slaveIsInHandshakeState()) &&
2547*572c4311Sfengbojiang          (time(NULL)-server.repl_transfer_lastio) > server.repl_timeout)
2548*572c4311Sfengbojiang     {
2549*572c4311Sfengbojiang         serverLog(LL_WARNING,"Timeout connecting to the MASTER...");
2550*572c4311Sfengbojiang         cancelReplicationHandshake();
2551*572c4311Sfengbojiang     }
2552*572c4311Sfengbojiang 
2553*572c4311Sfengbojiang     /* Bulk transfer I/O timeout? */
2554*572c4311Sfengbojiang     if (server.masterhost && server.repl_state == REPL_STATE_TRANSFER &&
2555*572c4311Sfengbojiang         (time(NULL)-server.repl_transfer_lastio) > server.repl_timeout)
2556*572c4311Sfengbojiang     {
2557*572c4311Sfengbojiang         serverLog(LL_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.");
2558*572c4311Sfengbojiang         cancelReplicationHandshake();
2559*572c4311Sfengbojiang     }
2560*572c4311Sfengbojiang 
2561*572c4311Sfengbojiang     /* Timed out master when we are an already connected slave? */
2562*572c4311Sfengbojiang     if (server.masterhost && server.repl_state == REPL_STATE_CONNECTED &&
2563*572c4311Sfengbojiang         (time(NULL)-server.master->lastinteraction) > server.repl_timeout)
2564*572c4311Sfengbojiang     {
2565*572c4311Sfengbojiang         serverLog(LL_WARNING,"MASTER timeout: no data nor PING received...");
2566*572c4311Sfengbojiang         freeClient(server.master);
2567*572c4311Sfengbojiang     }
2568*572c4311Sfengbojiang 
2569*572c4311Sfengbojiang     /* Check if we should connect to a MASTER */
2570*572c4311Sfengbojiang     if (server.repl_state == REPL_STATE_CONNECT) {
2571*572c4311Sfengbojiang         serverLog(LL_NOTICE,"Connecting to MASTER %s:%d",
2572*572c4311Sfengbojiang             server.masterhost, server.masterport);
2573*572c4311Sfengbojiang         if (connectWithMaster() == C_OK) {
2574*572c4311Sfengbojiang             serverLog(LL_NOTICE,"MASTER <-> REPLICA sync started");
2575*572c4311Sfengbojiang         }
2576*572c4311Sfengbojiang     }
2577*572c4311Sfengbojiang 
2578*572c4311Sfengbojiang     /* Send ACK to master from time to time.
2579*572c4311Sfengbojiang      * Note that we do not send periodic acks to masters that don't
2580*572c4311Sfengbojiang      * support PSYNC and replication offsets. */
2581*572c4311Sfengbojiang     if (server.masterhost && server.master &&
2582*572c4311Sfengbojiang         !(server.master->flags & CLIENT_PRE_PSYNC))
2583*572c4311Sfengbojiang         replicationSendAck();
2584*572c4311Sfengbojiang 
2585*572c4311Sfengbojiang     /* If we have attached slaves, PING them from time to time.
2586*572c4311Sfengbojiang      * So slaves can implement an explicit timeout to masters, and will
2587*572c4311Sfengbojiang      * be able to detect a link disconnection even if the TCP connection
2588*572c4311Sfengbojiang      * will not actually go down. */
2589*572c4311Sfengbojiang     listIter li;
2590*572c4311Sfengbojiang     listNode *ln;
2591*572c4311Sfengbojiang     robj *ping_argv[1];
2592*572c4311Sfengbojiang 
2593*572c4311Sfengbojiang     /* First, send PING according to ping_slave_period. */
2594*572c4311Sfengbojiang     if ((replication_cron_loops % server.repl_ping_slave_period) == 0 &&
2595*572c4311Sfengbojiang         listLength(server.slaves))
2596*572c4311Sfengbojiang     {
2597*572c4311Sfengbojiang         /* Note that we don't send the PING if the clients are paused during
2598*572c4311Sfengbojiang          * a Redis Cluster manual failover: the PING we send will otherwise
2599*572c4311Sfengbojiang          * alter the replication offsets of master and slave, and will no longer
2600*572c4311Sfengbojiang          * match the one stored into 'mf_master_offset' state. */
2601*572c4311Sfengbojiang         int manual_failover_in_progress =
2602*572c4311Sfengbojiang             server.cluster_enabled &&
2603*572c4311Sfengbojiang             server.cluster->mf_end &&
2604*572c4311Sfengbojiang             clientsArePaused();
2605*572c4311Sfengbojiang 
2606*572c4311Sfengbojiang         if (!manual_failover_in_progress) {
2607*572c4311Sfengbojiang             ping_argv[0] = createStringObject("PING",4);
2608*572c4311Sfengbojiang             replicationFeedSlaves(server.slaves, server.slaveseldb,
2609*572c4311Sfengbojiang                 ping_argv, 1);
2610*572c4311Sfengbojiang             decrRefCount(ping_argv[0]);
2611*572c4311Sfengbojiang         }
2612*572c4311Sfengbojiang     }
2613*572c4311Sfengbojiang 
2614*572c4311Sfengbojiang     /* Second, send a newline to all the slaves in pre-synchronization
2615*572c4311Sfengbojiang      * stage, that is, slaves waiting for the master to create the RDB file.
2616*572c4311Sfengbojiang      *
2617*572c4311Sfengbojiang      * Also send the a newline to all the chained slaves we have, if we lost
2618*572c4311Sfengbojiang      * connection from our master, to keep the slaves aware that their
2619*572c4311Sfengbojiang      * master is online. This is needed since sub-slaves only receive proxied
2620*572c4311Sfengbojiang      * data from top-level masters, so there is no explicit pinging in order
2621*572c4311Sfengbojiang      * to avoid altering the replication offsets. This special out of band
2622*572c4311Sfengbojiang      * pings (newlines) can be sent, they will have no effect in the offset.
2623*572c4311Sfengbojiang      *
2624*572c4311Sfengbojiang      * The newline will be ignored by the slave but will refresh the
2625*572c4311Sfengbojiang      * last interaction timer preventing a timeout. In this case we ignore the
2626*572c4311Sfengbojiang      * ping period and refresh the connection once per second since certain
2627*572c4311Sfengbojiang      * timeouts are set at a few seconds (example: PSYNC response). */
2628*572c4311Sfengbojiang     listRewind(server.slaves,&li);
2629*572c4311Sfengbojiang     while((ln = listNext(&li))) {
2630*572c4311Sfengbojiang         client *slave = ln->value;
2631*572c4311Sfengbojiang 
2632*572c4311Sfengbojiang         int is_presync =
2633*572c4311Sfengbojiang             (slave->replstate == SLAVE_STATE_WAIT_BGSAVE_START ||
2634*572c4311Sfengbojiang             (slave->replstate == SLAVE_STATE_WAIT_BGSAVE_END &&
2635*572c4311Sfengbojiang              server.rdb_child_type != RDB_CHILD_TYPE_SOCKET));
2636*572c4311Sfengbojiang 
2637*572c4311Sfengbojiang         if (is_presync) {
2638*572c4311Sfengbojiang             if (write(slave->fd, "\n", 1) == -1) {
2639*572c4311Sfengbojiang                 /* Don't worry about socket errors, it's just a ping. */
2640*572c4311Sfengbojiang             }
2641*572c4311Sfengbojiang         }
2642*572c4311Sfengbojiang     }
2643*572c4311Sfengbojiang 
2644*572c4311Sfengbojiang     /* Disconnect timedout slaves. */
2645*572c4311Sfengbojiang     if (listLength(server.slaves)) {
2646*572c4311Sfengbojiang         listIter li;
2647*572c4311Sfengbojiang         listNode *ln;
2648*572c4311Sfengbojiang 
2649*572c4311Sfengbojiang         listRewind(server.slaves,&li);
2650*572c4311Sfengbojiang         while((ln = listNext(&li))) {
2651*572c4311Sfengbojiang             client *slave = ln->value;
2652*572c4311Sfengbojiang 
2653*572c4311Sfengbojiang             if (slave->replstate != SLAVE_STATE_ONLINE) continue;
2654*572c4311Sfengbojiang             if (slave->flags & CLIENT_PRE_PSYNC) continue;
2655*572c4311Sfengbojiang             if ((server.unixtime - slave->repl_ack_time) > server.repl_timeout)
2656*572c4311Sfengbojiang             {
2657*572c4311Sfengbojiang                 serverLog(LL_WARNING, "Disconnecting timedout replica: %s",
2658*572c4311Sfengbojiang                     replicationGetSlaveName(slave));
2659*572c4311Sfengbojiang                 freeClient(slave);
2660*572c4311Sfengbojiang             }
2661*572c4311Sfengbojiang         }
2662*572c4311Sfengbojiang     }
2663*572c4311Sfengbojiang 
2664*572c4311Sfengbojiang     /* If this is a master without attached slaves and there is a replication
2665*572c4311Sfengbojiang      * backlog active, in order to reclaim memory we can free it after some
2666*572c4311Sfengbojiang      * (configured) time. Note that this cannot be done for slaves: slaves
2667*572c4311Sfengbojiang      * without sub-slaves attached should still accumulate data into the
2668*572c4311Sfengbojiang      * backlog, in order to reply to PSYNC queries if they are turned into
2669*572c4311Sfengbojiang      * masters after a failover. */
2670*572c4311Sfengbojiang     if (listLength(server.slaves) == 0 && server.repl_backlog_time_limit &&
2671*572c4311Sfengbojiang         server.repl_backlog && server.masterhost == NULL)
2672*572c4311Sfengbojiang     {
2673*572c4311Sfengbojiang         time_t idle = server.unixtime - server.repl_no_slaves_since;
2674*572c4311Sfengbojiang 
2675*572c4311Sfengbojiang         if (idle > server.repl_backlog_time_limit) {
2676*572c4311Sfengbojiang             /* When we free the backlog, we always use a new
2677*572c4311Sfengbojiang              * replication ID and clear the ID2. This is needed
2678*572c4311Sfengbojiang              * because when there is no backlog, the master_repl_offset
2679*572c4311Sfengbojiang              * is not updated, but we would still retain our replication
2680*572c4311Sfengbojiang              * ID, leading to the following problem:
2681*572c4311Sfengbojiang              *
2682*572c4311Sfengbojiang              * 1. We are a master instance.
2683*572c4311Sfengbojiang              * 2. Our slave is promoted to master. It's repl-id-2 will
2684*572c4311Sfengbojiang              *    be the same as our repl-id.
2685*572c4311Sfengbojiang              * 3. We, yet as master, receive some updates, that will not
2686*572c4311Sfengbojiang              *    increment the master_repl_offset.
2687*572c4311Sfengbojiang              * 4. Later we are turned into a slave, connect to the new
2688*572c4311Sfengbojiang              *    master that will accept our PSYNC request by second
2689*572c4311Sfengbojiang              *    replication ID, but there will be data inconsistency
2690*572c4311Sfengbojiang              *    because we received writes. */
2691*572c4311Sfengbojiang             changeReplicationId();
2692*572c4311Sfengbojiang             clearReplicationId2();
2693*572c4311Sfengbojiang             freeReplicationBacklog();
2694*572c4311Sfengbojiang             serverLog(LL_NOTICE,
2695*572c4311Sfengbojiang                 "Replication backlog freed after %d seconds "
2696*572c4311Sfengbojiang                 "without connected replicas.",
2697*572c4311Sfengbojiang                 (int) server.repl_backlog_time_limit);
2698*572c4311Sfengbojiang         }
2699*572c4311Sfengbojiang     }
2700*572c4311Sfengbojiang 
2701*572c4311Sfengbojiang     /* If AOF is disabled and we no longer have attached slaves, we can
2702*572c4311Sfengbojiang      * free our Replication Script Cache as there is no need to propagate
2703*572c4311Sfengbojiang      * EVALSHA at all. */
2704*572c4311Sfengbojiang     if (listLength(server.slaves) == 0 &&
2705*572c4311Sfengbojiang         server.aof_state == AOF_OFF &&
2706*572c4311Sfengbojiang         listLength(server.repl_scriptcache_fifo) != 0)
2707*572c4311Sfengbojiang     {
2708*572c4311Sfengbojiang         replicationScriptCacheFlush();
2709*572c4311Sfengbojiang     }
2710*572c4311Sfengbojiang 
2711*572c4311Sfengbojiang     /* Start a BGSAVE good for replication if we have slaves in
2712*572c4311Sfengbojiang      * WAIT_BGSAVE_START state.
2713*572c4311Sfengbojiang      *
2714*572c4311Sfengbojiang      * In case of diskless replication, we make sure to wait the specified
2715*572c4311Sfengbojiang      * number of seconds (according to configuration) so that other slaves
2716*572c4311Sfengbojiang      * have the time to arrive before we start streaming. */
2717*572c4311Sfengbojiang     if (server.rdb_child_pid == -1 && server.aof_child_pid == -1) {
2718*572c4311Sfengbojiang         time_t idle, max_idle = 0;
2719*572c4311Sfengbojiang         int slaves_waiting = 0;
2720*572c4311Sfengbojiang         int mincapa = -1;
2721*572c4311Sfengbojiang         listNode *ln;
2722*572c4311Sfengbojiang         listIter li;
2723*572c4311Sfengbojiang 
2724*572c4311Sfengbojiang         listRewind(server.slaves,&li);
2725*572c4311Sfengbojiang         while((ln = listNext(&li))) {
2726*572c4311Sfengbojiang             client *slave = ln->value;
2727*572c4311Sfengbojiang             if (slave->replstate == SLAVE_STATE_WAIT_BGSAVE_START) {
2728*572c4311Sfengbojiang                 idle = server.unixtime - slave->lastinteraction;
2729*572c4311Sfengbojiang                 if (idle > max_idle) max_idle = idle;
2730*572c4311Sfengbojiang                 slaves_waiting++;
2731*572c4311Sfengbojiang                 mincapa = (mincapa == -1) ? slave->slave_capa :
2732*572c4311Sfengbojiang                                             (mincapa & slave->slave_capa);
2733*572c4311Sfengbojiang             }
2734*572c4311Sfengbojiang         }
2735*572c4311Sfengbojiang 
2736*572c4311Sfengbojiang         if (slaves_waiting &&
2737*572c4311Sfengbojiang             (!server.repl_diskless_sync ||
2738*572c4311Sfengbojiang              max_idle > server.repl_diskless_sync_delay))
2739*572c4311Sfengbojiang         {
2740*572c4311Sfengbojiang             /* Start the BGSAVE. The called function may start a
2741*572c4311Sfengbojiang              * BGSAVE with socket target or disk target depending on the
2742*572c4311Sfengbojiang              * configuration and slaves capabilities. */
2743*572c4311Sfengbojiang             startBgsaveForReplication(mincapa);
2744*572c4311Sfengbojiang         }
2745*572c4311Sfengbojiang     }
2746*572c4311Sfengbojiang 
2747*572c4311Sfengbojiang     /* Refresh the number of slaves with lag <= min-slaves-max-lag. */
2748*572c4311Sfengbojiang     refreshGoodSlavesCount();
2749*572c4311Sfengbojiang     replication_cron_loops++; /* Incremented with frequency 1 HZ. */
2750*572c4311Sfengbojiang }
2751