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