xref: /redis-3.2.3/src/replication.c (revision 897adc1c)
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 "redis.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 
44 /* ---------------------------------- MASTER -------------------------------- */
45 
46 void createReplicationBacklog(void) {
47     redisAssert(server.repl_backlog == NULL);
48     server.repl_backlog = zmalloc(server.repl_backlog_size);
49     server.repl_backlog_histlen = 0;
50     server.repl_backlog_idx = 0;
51     /* When a new backlog buffer is created, we increment the replication
52      * offset by one to make sure we'll not be able to PSYNC with any
53      * previous slave. This is needed because we avoid incrementing the
54      * master_repl_offset if no backlog exists nor slaves are attached. */
55     server.master_repl_offset++;
56 
57     /* We don't have any data inside our buffer, but virtually the first
58      * byte we have is the next byte that will be generated for the
59      * replication stream. */
60     server.repl_backlog_off = server.master_repl_offset+1;
61 }
62 
63 /* This function is called when the user modifies the replication backlog
64  * size at runtime. It is up to the function to both update the
65  * server.repl_backlog_size and to resize the buffer and setup it so that
66  * it contains the same data as the previous one (possibly less data, but
67  * the most recent bytes, or the same data and more free space in case the
68  * buffer is enlarged). */
69 void resizeReplicationBacklog(long long newsize) {
70     if (newsize < REDIS_REPL_BACKLOG_MIN_SIZE)
71         newsize = REDIS_REPL_BACKLOG_MIN_SIZE;
72     if (server.repl_backlog_size == newsize) return;
73 
74     server.repl_backlog_size = newsize;
75     if (server.repl_backlog != NULL) {
76         /* What we actually do is to flush the old buffer and realloc a new
77          * empty one. It will refill with new data incrementally.
78          * The reason is that copying a few gigabytes adds latency and even
79          * worse often we need to alloc additional space before freeing the
80          * old buffer. */
81         zfree(server.repl_backlog);
82         server.repl_backlog = zmalloc(server.repl_backlog_size);
83         server.repl_backlog_histlen = 0;
84         server.repl_backlog_idx = 0;
85         /* Next byte we have is... the next since the buffer is emtpy. */
86         server.repl_backlog_off = server.master_repl_offset+1;
87     }
88 }
89 
90 void freeReplicationBacklog(void) {
91     redisAssert(listLength(server.slaves) == 0);
92     zfree(server.repl_backlog);
93     server.repl_backlog = NULL;
94 }
95 
96 /* Add data to the replication backlog.
97  * This function also increments the global replication offset stored at
98  * server.master_repl_offset, because there is no case where we want to feed
99  * the backlog without incrementing the buffer. */
100 void feedReplicationBacklog(void *ptr, size_t len) {
101     unsigned char *p = ptr;
102 
103     server.master_repl_offset += len;
104 
105     /* This is a circular buffer, so write as much data we can at every
106      * iteration and rewind the "idx" index if we reach the limit. */
107     while(len) {
108         size_t thislen = server.repl_backlog_size - server.repl_backlog_idx;
109         if (thislen > len) thislen = len;
110         memcpy(server.repl_backlog+server.repl_backlog_idx,p,thislen);
111         server.repl_backlog_idx += thislen;
112         if (server.repl_backlog_idx == server.repl_backlog_size)
113             server.repl_backlog_idx = 0;
114         len -= thislen;
115         p += thislen;
116         server.repl_backlog_histlen += thislen;
117     }
118     if (server.repl_backlog_histlen > server.repl_backlog_size)
119         server.repl_backlog_histlen = server.repl_backlog_size;
120     /* Set the offset of the first byte we have in the backlog. */
121     server.repl_backlog_off = server.master_repl_offset -
122                               server.repl_backlog_histlen + 1;
123 }
124 
125 /* Wrapper for feedReplicationBacklog() that takes Redis string objects
126  * as input. */
127 void feedReplicationBacklogWithObject(robj *o) {
128     char llstr[REDIS_LONGSTR_SIZE];
129     void *p;
130     size_t len;
131 
132     if (o->encoding == REDIS_ENCODING_INT) {
133         len = ll2string(llstr,sizeof(llstr),(long)o->ptr);
134         p = llstr;
135     } else {
136         len = sdslen(o->ptr);
137         p = o->ptr;
138     }
139     feedReplicationBacklog(p,len);
140 }
141 
142 void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc) {
143     listNode *ln;
144     listIter li;
145     int j, len;
146     char llstr[REDIS_LONGSTR_SIZE];
147 
148     /* If there aren't slaves, and there is no backlog buffer to populate,
149      * we can return ASAP. */
150     if (server.repl_backlog == NULL && listLength(slaves) == 0) return;
151 
152     /* We can't have slaves attached and no backlog. */
153     redisAssert(!(listLength(slaves) != 0 && server.repl_backlog == NULL));
154 
155     /* Send SELECT command to every slave if needed. */
156     if (server.slaveseldb != dictid) {
157         robj *selectcmd;
158 
159         /* For a few DBs we have pre-computed SELECT command. */
160         if (dictid >= 0 && dictid < REDIS_SHARED_SELECT_CMDS) {
161             selectcmd = shared.select[dictid];
162         } else {
163             int dictid_len;
164 
165             dictid_len = ll2string(llstr,sizeof(llstr),dictid);
166             selectcmd = createObject(REDIS_STRING,
167                 sdscatprintf(sdsempty(),
168                 "*2\r\n$6\r\nSELECT\r\n$%d\r\n%s\r\n",
169                 dictid_len, llstr));
170         }
171 
172         /* Add the SELECT command into the backlog. */
173         if (server.repl_backlog) feedReplicationBacklogWithObject(selectcmd);
174 
175         /* Send it to slaves. */
176         listRewind(slaves,&li);
177         while((ln = listNext(&li))) {
178             redisClient *slave = ln->value;
179             addReply(slave,selectcmd);
180         }
181 
182         if (dictid < 0 || dictid >= REDIS_SHARED_SELECT_CMDS)
183             decrRefCount(selectcmd);
184     }
185     server.slaveseldb = dictid;
186 
187     /* Write the command to the replication backlog if any. */
188     if (server.repl_backlog) {
189         char aux[REDIS_LONGSTR_SIZE+3];
190 
191         /* Add the multi bulk reply length. */
192         aux[0] = '*';
193         len = ll2string(aux+1,sizeof(aux)-1,argc);
194         aux[len+1] = '\r';
195         aux[len+2] = '\n';
196         feedReplicationBacklog(aux,len+3);
197 
198         for (j = 0; j < argc; j++) {
199             long objlen = stringObjectLen(argv[j]);
200 
201             /* We need to feed the buffer with the object as a bulk reply
202              * not just as a plain string, so create the $..CRLF payload len
203              * ad add the final CRLF */
204             aux[0] = '$';
205             len = ll2string(aux+1,sizeof(aux)-1,objlen);
206             aux[len+1] = '\r';
207             aux[len+2] = '\n';
208             feedReplicationBacklog(aux,len+3);
209             feedReplicationBacklogWithObject(argv[j]);
210             feedReplicationBacklog(aux+len+1,2);
211         }
212     }
213 
214     /* Write the command to every slave. */
215     listRewind(slaves,&li);
216     while((ln = listNext(&li))) {
217         redisClient *slave = ln->value;
218 
219         /* Don't feed slaves that are still waiting for BGSAVE to start */
220         if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) continue;
221 
222         /* Feed slaves that are waiting for the initial SYNC (so these commands
223          * are queued in the output buffer until the initial SYNC completes),
224          * or are already in sync with the master. */
225 
226         /* Add the multi bulk length. */
227         addReplyMultiBulkLen(slave,argc);
228 
229         /* Finally any additional argument that was not stored inside the
230          * static buffer if any (from j to argc). */
231         for (j = 0; j < argc; j++)
232             addReplyBulk(slave,argv[j]);
233     }
234 }
235 
236 void replicationFeedMonitors(redisClient *c, list *monitors, int dictid, robj **argv, int argc) {
237     listNode *ln;
238     listIter li;
239     int j;
240     sds cmdrepr = sdsnew("+");
241     robj *cmdobj;
242     char peerid[REDIS_PEER_ID_LEN];
243     struct timeval tv;
244 
245     gettimeofday(&tv,NULL);
246     cmdrepr = sdscatprintf(cmdrepr,"%ld.%06ld ",(long)tv.tv_sec,(long)tv.tv_usec);
247     if (c->flags & REDIS_LUA_CLIENT) {
248         cmdrepr = sdscatprintf(cmdrepr,"[%d lua] ",dictid);
249     } else if (c->flags & REDIS_UNIX_SOCKET) {
250         cmdrepr = sdscatprintf(cmdrepr,"[%d unix:%s] ",dictid,server.unixsocket);
251     } else {
252         getClientPeerId(c,peerid,sizeof(peerid));
253         cmdrepr = sdscatprintf(cmdrepr,"[%d %s] ",dictid,peerid);
254     }
255 
256     for (j = 0; j < argc; j++) {
257         if (argv[j]->encoding == REDIS_ENCODING_INT) {
258             cmdrepr = sdscatprintf(cmdrepr, "\"%ld\"", (long)argv[j]->ptr);
259         } else {
260             cmdrepr = sdscatrepr(cmdrepr,(char*)argv[j]->ptr,
261                         sdslen(argv[j]->ptr));
262         }
263         if (j != argc-1)
264             cmdrepr = sdscatlen(cmdrepr," ",1);
265     }
266     cmdrepr = sdscatlen(cmdrepr,"\r\n",2);
267     cmdobj = createObject(REDIS_STRING,cmdrepr);
268 
269     listRewind(monitors,&li);
270     while((ln = listNext(&li))) {
271         redisClient *monitor = ln->value;
272         addReply(monitor,cmdobj);
273     }
274     decrRefCount(cmdobj);
275 }
276 
277 /* Feed the slave 'c' with the replication backlog starting from the
278  * specified 'offset' up to the end of the backlog. */
279 long long addReplyReplicationBacklog(redisClient *c, long long offset) {
280     long long j, skip, len;
281 
282     redisLog(REDIS_DEBUG, "[PSYNC] Slave request offset: %lld", offset);
283 
284     if (server.repl_backlog_histlen == 0) {
285         redisLog(REDIS_DEBUG, "[PSYNC] Backlog history len is zero");
286         return 0;
287     }
288 
289     redisLog(REDIS_DEBUG, "[PSYNC] Backlog size: %lld",
290              server.repl_backlog_size);
291     redisLog(REDIS_DEBUG, "[PSYNC] First byte: %lld",
292              server.repl_backlog_off);
293     redisLog(REDIS_DEBUG, "[PSYNC] History len: %lld",
294              server.repl_backlog_histlen);
295     redisLog(REDIS_DEBUG, "[PSYNC] Current index: %lld",
296              server.repl_backlog_idx);
297 
298     /* Compute the amount of bytes we need to discard. */
299     skip = offset - server.repl_backlog_off;
300     redisLog(REDIS_DEBUG, "[PSYNC] Skipping: %lld", skip);
301 
302     /* Point j to the oldest byte, that is actaully our
303      * server.repl_backlog_off byte. */
304     j = (server.repl_backlog_idx +
305         (server.repl_backlog_size-server.repl_backlog_histlen)) %
306         server.repl_backlog_size;
307     redisLog(REDIS_DEBUG, "[PSYNC] Index of first byte: %lld", j);
308 
309     /* Discard the amount of data to seek to the specified 'offset'. */
310     j = (j + skip) % server.repl_backlog_size;
311 
312     /* Feed slave with data. Since it is a circular buffer we have to
313      * split the reply in two parts if we are cross-boundary. */
314     len = server.repl_backlog_histlen - skip;
315     redisLog(REDIS_DEBUG, "[PSYNC] Reply total length: %lld", len);
316     while(len) {
317         long long thislen =
318             ((server.repl_backlog_size - j) < len) ?
319             (server.repl_backlog_size - j) : len;
320 
321         redisLog(REDIS_DEBUG, "[PSYNC] addReply() length: %lld", thislen);
322         addReplySds(c,sdsnewlen(server.repl_backlog + j, thislen));
323         len -= thislen;
324         j = 0;
325     }
326     return server.repl_backlog_histlen - skip;
327 }
328 
329 /* This function handles the PSYNC command from the point of view of a
330  * master receiving a request for partial resynchronization.
331  *
332  * On success return REDIS_OK, otherwise REDIS_ERR is returned and we proceed
333  * with the usual full resync. */
334 int masterTryPartialResynchronization(redisClient *c) {
335     long long psync_offset, psync_len;
336     char *master_runid = c->argv[1]->ptr;
337     char buf[128];
338     int buflen;
339 
340     /* Is the runid of this master the same advertised by the wannabe slave
341      * via PSYNC? If runid changed this master is a different instance and
342      * there is no way to continue. */
343     if (strcasecmp(master_runid, server.runid)) {
344         /* Run id "?" is used by slaves that want to force a full resync. */
345         if (master_runid[0] != '?') {
346             redisLog(REDIS_NOTICE,"Partial resynchronization not accepted: "
347                 "Runid mismatch (Client asked for runid '%s', my runid is '%s')",
348                 master_runid, server.runid);
349         } else {
350             redisLog(REDIS_NOTICE,"Full resync requested by slave.");
351         }
352         goto need_full_resync;
353     }
354 
355     /* We still have the data our slave is asking for? */
356     if (getLongLongFromObjectOrReply(c,c->argv[2],&psync_offset,NULL) !=
357        REDIS_OK) goto need_full_resync;
358     if (!server.repl_backlog ||
359         psync_offset < server.repl_backlog_off ||
360         psync_offset > (server.repl_backlog_off + server.repl_backlog_histlen))
361     {
362         redisLog(REDIS_NOTICE,
363             "Unable to partial resync with the slave for lack of backlog (Slave request was: %lld).", psync_offset);
364         if (psync_offset > server.master_repl_offset) {
365             redisLog(REDIS_WARNING,
366                 "Warning: slave tried to PSYNC with an offset that is greater than the master replication offset.");
367         }
368         goto need_full_resync;
369     }
370 
371     /* If we reached this point, we are able to perform a partial resync:
372      * 1) Set client state to make it a slave.
373      * 2) Inform the client we can continue with +CONTINUE
374      * 3) Send the backlog data (from the offset to the end) to the slave. */
375     c->flags |= REDIS_SLAVE;
376     c->replstate = REDIS_REPL_ONLINE;
377     c->repl_ack_time = server.unixtime;
378     listAddNodeTail(server.slaves,c);
379     /* We can't use the connection buffers since they are used to accumulate
380      * new commands at this stage. But we are sure the socket send buffer is
381      * emtpy so this write will never fail actually. */
382     buflen = snprintf(buf,sizeof(buf),"+CONTINUE\r\n");
383     if (write(c->fd,buf,buflen) != buflen) {
384         freeClientAsync(c);
385         return REDIS_OK;
386     }
387     psync_len = addReplyReplicationBacklog(c,psync_offset);
388     redisLog(REDIS_NOTICE,
389         "Partial resynchronization request accepted. Sending %lld bytes of backlog starting from offset %lld.", psync_len, psync_offset);
390     /* Note that we don't need to set the selected DB at server.slaveseldb
391      * to -1 to force the master to emit SELECT, since the slave already
392      * has this state from the previous connection with the master. */
393 
394     refreshGoodSlavesCount();
395     return REDIS_OK; /* The caller can return, no full resync needed. */
396 
397 need_full_resync:
398     /* We need a full resync for some reason... notify the client. */
399     psync_offset = server.master_repl_offset;
400     /* Add 1 to psync_offset if it the replication backlog does not exists
401      * as when it will be created later we'll increment the offset by one. */
402     if (server.repl_backlog == NULL) psync_offset++;
403     /* Again, we can't use the connection buffers (see above). */
404     buflen = snprintf(buf,sizeof(buf),"+FULLRESYNC %s %lld\r\n",
405                       server.runid,psync_offset);
406     if (write(c->fd,buf,buflen) != buflen) {
407         freeClientAsync(c);
408         return REDIS_OK;
409     }
410     return REDIS_ERR;
411 }
412 
413 /* SYNC ad PSYNC command implemenation. */
414 void syncCommand(redisClient *c) {
415     /* ignore SYNC if already slave or in monitor mode */
416     if (c->flags & REDIS_SLAVE) return;
417 
418     /* Refuse SYNC requests if we are a slave but the link with our master
419      * is not ok... */
420     if (server.masterhost && server.repl_state != REDIS_REPL_CONNECTED) {
421         addReplyError(c,"Can't SYNC while not connected with my master");
422         return;
423     }
424 
425     /* SYNC can't be issued when the server has pending data to send to
426      * the client about already issued commands. We need a fresh reply
427      * buffer registering the differences between the BGSAVE and the current
428      * dataset, so that we can copy to other slaves if needed. */
429     if (listLength(c->reply) != 0 || c->bufpos != 0) {
430         addReplyError(c,"SYNC and PSYNC are invalid with pending output");
431         return;
432     }
433 
434     redisLog(REDIS_NOTICE,"Slave asks for synchronization");
435 
436     /* Try a partial resynchronization if this is a PSYNC command.
437      * If it fails, we continue with usual full resynchronization, however
438      * when this happens masterTryPartialResynchronization() already
439      * replied with:
440      *
441      * +FULLRESYNC <runid> <offset>
442      *
443      * So the slave knows the new runid and offset to try a PSYNC later
444      * if the connection with the master is lost. */
445     if (!strcasecmp(c->argv[0]->ptr,"psync")) {
446         if (masterTryPartialResynchronization(c) == REDIS_OK) {
447             server.stat_sync_partial_ok++;
448             return; /* No full resync needed, return. */
449         } else {
450             char *master_runid = c->argv[1]->ptr;
451 
452             /* Increment stats for failed PSYNCs, but only if the
453              * runid is not "?", as this is used by slaves to force a full
454              * resync on purpose when they are not albe to partially
455              * resync. */
456             if (master_runid[0] != '?') server.stat_sync_partial_err++;
457         }
458     } else {
459         /* If a slave uses SYNC, we are dealing with an old implementation
460          * of the replication protocol (like redis-cli --slave). Flag the client
461          * so that we don't expect to receive REPLCONF ACK feedbacks. */
462         c->flags |= REDIS_PRE_PSYNC;
463     }
464 
465     /* Full resynchronization. */
466     server.stat_sync_full++;
467 
468     /* Here we need to check if there is a background saving operation
469      * in progress, or if it is required to start one */
470     if (server.rdb_child_pid != -1) {
471         /* Ok a background save is in progress. Let's check if it is a good
472          * one for replication, i.e. if there is another slave that is
473          * registering differences since the server forked to save */
474         redisClient *slave;
475         listNode *ln;
476         listIter li;
477 
478         listRewind(server.slaves,&li);
479         while((ln = listNext(&li))) {
480             slave = ln->value;
481             if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) break;
482         }
483         if (ln) {
484             /* Perfect, the server is already registering differences for
485              * another slave. Set the right state, and copy the buffer. */
486             copyClientOutputBuffer(c,slave);
487             c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
488             redisLog(REDIS_NOTICE,"Waiting for end of BGSAVE for SYNC");
489         } else {
490             /* No way, we need to wait for the next BGSAVE in order to
491              * register differences */
492             c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
493             redisLog(REDIS_NOTICE,"Waiting for next BGSAVE for SYNC");
494         }
495     } else {
496         /* Ok we don't have a BGSAVE in progress, let's start one */
497         redisLog(REDIS_NOTICE,"Starting BGSAVE for SYNC");
498         if (rdbSaveBackground(server.rdb_filename) != REDIS_OK) {
499             redisLog(REDIS_NOTICE,"Replication failed, can't BGSAVE");
500             addReplyError(c,"Unable to perform background save");
501             return;
502         }
503         c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
504         /* Flush the script cache for the new slave. */
505         replicationScriptCacheFlush();
506     }
507 
508     if (server.repl_disable_tcp_nodelay)
509         anetDisableTcpNoDelay(NULL, c->fd); /* Non critical if it fails. */
510     c->repldbfd = -1;
511     c->flags |= REDIS_SLAVE;
512     server.slaveseldb = -1; /* Force to re-emit the SELECT command. */
513     listAddNodeTail(server.slaves,c);
514     if (listLength(server.slaves) == 1 && server.repl_backlog == NULL)
515         createReplicationBacklog();
516     return;
517 }
518 
519 /* REPLCONF <option> <value> <option> <value> ...
520  * This command is used by a slave in order to configure the replication
521  * process before starting it with the SYNC command.
522  *
523  * Currently the only use of this command is to communicate to the master
524  * what is the listening port of the Slave redis instance, so that the
525  * master can accurately list slaves and their listening ports in
526  * the INFO output.
527  *
528  * In the future the same command can be used in order to configure
529  * the replication to initiate an incremental replication instead of a
530  * full resync. */
531 void replconfCommand(redisClient *c) {
532     int j;
533 
534     if ((c->argc % 2) == 0) {
535         /* Number of arguments must be odd to make sure that every
536          * option has a corresponding value. */
537         addReply(c,shared.syntaxerr);
538         return;
539     }
540 
541     /* Process every option-value pair. */
542     for (j = 1; j < c->argc; j+=2) {
543         if (!strcasecmp(c->argv[j]->ptr,"listening-port")) {
544             long port;
545 
546             if ((getLongFromObjectOrReply(c,c->argv[j+1],
547                     &port,NULL) != REDIS_OK))
548                 return;
549             c->slave_listening_port = port;
550         } else if (!strcasecmp(c->argv[j]->ptr,"ack")) {
551             /* REPLCONF ACK is used by slave to inform the master the amount
552              * of replication stream that it processed so far. It is an
553              * internal only command that normal clients should never use. */
554             long long offset;
555 
556             if (!(c->flags & REDIS_SLAVE)) return;
557             if ((getLongLongFromObject(c->argv[j+1], &offset) != REDIS_OK))
558                 return;
559             if (offset > c->repl_ack_off)
560                 c->repl_ack_off = offset;
561             c->repl_ack_time = server.unixtime;
562             /* Note: this command does not reply anything! */
563             return;
564         } else if (!strcasecmp(c->argv[j]->ptr,"getack")) {
565             /* REPLCONF GETACK is used in order to request an ACK ASAP
566              * to the slave. */
567             if (server.masterhost && server.master) replicationSendAck();
568             /* Note: this command does not reply anything! */
569         } else {
570             addReplyErrorFormat(c,"Unrecognized REPLCONF option: %s",
571                 (char*)c->argv[j]->ptr);
572             return;
573         }
574     }
575     addReply(c,shared.ok);
576 }
577 
578 void sendBulkToSlave(aeEventLoop *el, int fd, void *privdata, int mask) {
579     redisClient *slave = privdata;
580     REDIS_NOTUSED(el);
581     REDIS_NOTUSED(mask);
582     char buf[REDIS_IOBUF_LEN];
583     ssize_t nwritten, buflen;
584 
585     /* Before sending the RDB file, we send the preamble as configured by the
586      * replication process. Currently the preamble is just the bulk count of
587      * the file in the form "$<length>\r\n". */
588     if (slave->replpreamble) {
589         nwritten = write(fd,slave->replpreamble,sdslen(slave->replpreamble));
590         if (nwritten == -1) {
591             redisLog(REDIS_VERBOSE,"Write error sending RDB preamble to slave: %s",
592                 strerror(errno));
593             freeClient(slave);
594             return;
595         }
596         sdsrange(slave->replpreamble,nwritten,-1);
597         if (sdslen(slave->replpreamble) == 0) {
598             sdsfree(slave->replpreamble);
599             slave->replpreamble = NULL;
600             /* fall through sending data. */
601         } else {
602             return;
603         }
604     }
605 
606     /* If the preamble was already transfered, send the RDB bulk data. */
607     lseek(slave->repldbfd,slave->repldboff,SEEK_SET);
608     buflen = read(slave->repldbfd,buf,REDIS_IOBUF_LEN);
609     if (buflen <= 0) {
610         redisLog(REDIS_WARNING,"Read error sending DB to slave: %s",
611             (buflen == 0) ? "premature EOF" : strerror(errno));
612         freeClient(slave);
613         return;
614     }
615     if ((nwritten = write(fd,buf,buflen)) == -1) {
616         if (errno != EAGAIN) {
617             redisLog(REDIS_WARNING,"Write error sending DB to slave: %s",
618                 strerror(errno));
619             freeClient(slave);
620         }
621         return;
622     }
623     slave->repldboff += nwritten;
624     if (slave->repldboff == slave->repldbsize) {
625         close(slave->repldbfd);
626         slave->repldbfd = -1;
627         aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
628         slave->replstate = REDIS_REPL_ONLINE;
629         slave->repl_ack_time = server.unixtime;
630         if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE,
631             sendReplyToClient, slave) == AE_ERR) {
632             redisLog(REDIS_WARNING,"Unable to register writable event for slave bulk transfer: %s", strerror(errno));
633             freeClient(slave);
634             return;
635         }
636         refreshGoodSlavesCount();
637         redisLog(REDIS_NOTICE,"Synchronization with slave succeeded");
638     }
639 }
640 
641 /* This function is called at the end of every background saving.
642  * The argument bgsaveerr is REDIS_OK if the background saving succeeded
643  * otherwise REDIS_ERR is passed to the function.
644  *
645  * The goal of this function is to handle slaves waiting for a successful
646  * background saving in order to perform non-blocking synchronization. */
647 void updateSlavesWaitingBgsave(int bgsaveerr) {
648     listNode *ln;
649     int startbgsave = 0;
650     listIter li;
651 
652     listRewind(server.slaves,&li);
653     while((ln = listNext(&li))) {
654         redisClient *slave = ln->value;
655 
656         if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) {
657             startbgsave = 1;
658             slave->replstate = REDIS_REPL_WAIT_BGSAVE_END;
659         } else if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) {
660             struct redis_stat buf;
661 
662             if (bgsaveerr != REDIS_OK) {
663                 freeClient(slave);
664                 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE child returned an error");
665                 continue;
666             }
667             if ((slave->repldbfd = open(server.rdb_filename,O_RDONLY)) == -1 ||
668                 redis_fstat(slave->repldbfd,&buf) == -1) {
669                 freeClient(slave);
670                 redisLog(REDIS_WARNING,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno));
671                 continue;
672             }
673             slave->repldboff = 0;
674             slave->repldbsize = buf.st_size;
675             slave->replstate = REDIS_REPL_SEND_BULK;
676             slave->replpreamble = sdscatprintf(sdsempty(),"$%lld\r\n",
677                 (unsigned long long) slave->repldbsize);
678 
679             aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
680             if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE, sendBulkToSlave, slave) == AE_ERR) {
681                 freeClient(slave);
682                 continue;
683             }
684         }
685     }
686     if (startbgsave) {
687         /* Since we are starting a new background save for one or more slaves,
688          * we flush the Replication Script Cache to use EVAL to propagate every
689          * new EVALSHA for the first time, since all the new slaves don't know
690          * about previous scripts. */
691         replicationScriptCacheFlush();
692         if (rdbSaveBackground(server.rdb_filename) != REDIS_OK) {
693             listIter li;
694 
695             listRewind(server.slaves,&li);
696             redisLog(REDIS_WARNING,"SYNC failed. BGSAVE failed");
697             while((ln = listNext(&li))) {
698                 redisClient *slave = ln->value;
699 
700                 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START)
701                     freeClient(slave);
702             }
703         }
704     }
705 }
706 
707 /* ----------------------------------- SLAVE -------------------------------- */
708 
709 /* Abort the async download of the bulk dataset while SYNC-ing with master */
710 void replicationAbortSyncTransfer(void) {
711     redisAssert(server.repl_state == REDIS_REPL_TRANSFER);
712 
713     aeDeleteFileEvent(server.el,server.repl_transfer_s,AE_READABLE);
714     close(server.repl_transfer_s);
715     close(server.repl_transfer_fd);
716     unlink(server.repl_transfer_tmpfile);
717     zfree(server.repl_transfer_tmpfile);
718     server.repl_state = REDIS_REPL_CONNECT;
719 }
720 
721 /* Avoid the master to detect the slave is timing out while loading the
722  * RDB file in initial synchronization. We send a single newline character
723  * that is valid protocol but is guaranteed to either be sent entierly or
724  * not, since the byte is indivisible.
725  *
726  * The function is called in two contexts: while we flush the current
727  * data with emptyDb(), and while we load the new data received as an
728  * RDB file from the master. */
729 void replicationSendNewlineToMaster(void) {
730     static time_t newline_sent;
731     if (time(NULL) != newline_sent) {
732         newline_sent = time(NULL);
733         if (write(server.repl_transfer_s,"\n",1) == -1) {
734             /* Pinging back in this stage is best-effort. */
735         }
736     }
737 }
738 
739 /* Callback used by emptyDb() while flushing away old data to load
740  * the new dataset received by the master. */
741 void replicationEmptyDbCallback(void *privdata) {
742     REDIS_NOTUSED(privdata);
743     replicationSendNewlineToMaster();
744 }
745 
746 /* Asynchronously read the SYNC payload we receive from a master */
747 #define REPL_MAX_WRITTEN_BEFORE_FSYNC (1024*1024*8) /* 8 MB */
748 void readSyncBulkPayload(aeEventLoop *el, int fd, void *privdata, int mask) {
749     char buf[4096];
750     ssize_t nread, readlen;
751     off_t left;
752     REDIS_NOTUSED(el);
753     REDIS_NOTUSED(privdata);
754     REDIS_NOTUSED(mask);
755 
756     /* If repl_transfer_size == -1 we still have to read the bulk length
757      * from the master reply. */
758     if (server.repl_transfer_size == -1) {
759         if (syncReadLine(fd,buf,1024,server.repl_syncio_timeout*1000) == -1) {
760             redisLog(REDIS_WARNING,
761                 "I/O error reading bulk count from MASTER: %s",
762                 strerror(errno));
763             goto error;
764         }
765 
766         if (buf[0] == '-') {
767             redisLog(REDIS_WARNING,
768                 "MASTER aborted replication with an error: %s",
769                 buf+1);
770             goto error;
771         } else if (buf[0] == '\0') {
772             /* At this stage just a newline works as a PING in order to take
773              * the connection live. So we refresh our last interaction
774              * timestamp. */
775             server.repl_transfer_lastio = server.unixtime;
776             return;
777         } else if (buf[0] != '$') {
778             redisLog(REDIS_WARNING,"Bad protocol from MASTER, the first byte is not '$' (we received '%s'), are you sure the host and port are right?", buf);
779             goto error;
780         }
781         server.repl_transfer_size = strtol(buf+1,NULL,10);
782         redisLog(REDIS_NOTICE,
783             "MASTER <-> SLAVE sync: receiving %lld bytes from master",
784             (long long) server.repl_transfer_size);
785         return;
786     }
787 
788     /* Read bulk data */
789     left = server.repl_transfer_size - server.repl_transfer_read;
790     readlen = (left < (signed)sizeof(buf)) ? left : (signed)sizeof(buf);
791     nread = read(fd,buf,readlen);
792     if (nread <= 0) {
793         redisLog(REDIS_WARNING,"I/O error trying to sync with MASTER: %s",
794             (nread == -1) ? strerror(errno) : "connection lost");
795         replicationAbortSyncTransfer();
796         return;
797     }
798     server.repl_transfer_lastio = server.unixtime;
799     if (write(server.repl_transfer_fd,buf,nread) != nread) {
800         redisLog(REDIS_WARNING,"Write error or short write writing to the DB dump file needed for MASTER <-> SLAVE synchronization: %s", strerror(errno));
801         goto error;
802     }
803     server.repl_transfer_read += nread;
804 
805     /* Sync data on disk from time to time, otherwise at the end of the transfer
806      * we may suffer a big delay as the memory buffers are copied into the
807      * actual disk. */
808     if (server.repl_transfer_read >=
809         server.repl_transfer_last_fsync_off + REPL_MAX_WRITTEN_BEFORE_FSYNC)
810     {
811         off_t sync_size = server.repl_transfer_read -
812                           server.repl_transfer_last_fsync_off;
813         rdb_fsync_range(server.repl_transfer_fd,
814             server.repl_transfer_last_fsync_off, sync_size);
815         server.repl_transfer_last_fsync_off += sync_size;
816     }
817 
818     /* Check if the transfer is now complete */
819     if (server.repl_transfer_read == server.repl_transfer_size) {
820         if (rename(server.repl_transfer_tmpfile,server.rdb_filename) == -1) {
821             redisLog(REDIS_WARNING,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno));
822             replicationAbortSyncTransfer();
823             return;
824         }
825         redisLog(REDIS_NOTICE, "MASTER <-> SLAVE sync: Flushing old data");
826         signalFlushedDb(-1);
827         emptyDb(replicationEmptyDbCallback);
828         /* Before loading the DB into memory we need to delete the readable
829          * handler, otherwise it will get called recursively since
830          * rdbLoad() will call the event loop to process events from time to
831          * time for non blocking loading. */
832         aeDeleteFileEvent(server.el,server.repl_transfer_s,AE_READABLE);
833         redisLog(REDIS_NOTICE, "MASTER <-> SLAVE sync: Loading DB in memory");
834         if (rdbLoad(server.rdb_filename) != REDIS_OK) {
835             redisLog(REDIS_WARNING,"Failed trying to load the MASTER synchronization DB from disk");
836             replicationAbortSyncTransfer();
837             return;
838         }
839         /* Final setup of the connected slave <- master link */
840         zfree(server.repl_transfer_tmpfile);
841         close(server.repl_transfer_fd);
842         server.master = createClient(server.repl_transfer_s);
843         server.master->flags |= REDIS_MASTER;
844         server.master->authenticated = 1;
845         server.repl_state = REDIS_REPL_CONNECTED;
846         server.master->reploff = server.repl_master_initial_offset;
847         memcpy(server.master->replrunid, server.repl_master_runid,
848             sizeof(server.repl_master_runid));
849         /* If master offset is set to -1, this master is old and is not
850          * PSYNC capable, so we flag it accordingly. */
851         if (server.master->reploff == -1)
852             server.master->flags |= REDIS_PRE_PSYNC;
853         redisLog(REDIS_NOTICE, "MASTER <-> SLAVE sync: Finished with success");
854         /* Restart the AOF subsystem now that we finished the sync. This
855          * will trigger an AOF rewrite, and when done will start appending
856          * to the new file. */
857         if (server.aof_state != REDIS_AOF_OFF) {
858             int retry = 10;
859 
860             stopAppendOnly();
861             while (retry-- && startAppendOnly() == REDIS_ERR) {
862                 redisLog(REDIS_WARNING,"Failed enabling the AOF after successful master synchronization! Trying it again in one second.");
863                 sleep(1);
864             }
865             if (!retry) {
866                 redisLog(REDIS_WARNING,"FATAL: this slave instance finished the synchronization with its master, but the AOF can't be turned on. Exiting now.");
867                 exit(1);
868             }
869         }
870     }
871 
872     return;
873 
874 error:
875     replicationAbortSyncTransfer();
876     return;
877 }
878 
879 /* Send a synchronous command to the master. Used to send AUTH and
880  * REPLCONF commands before starting the replication with SYNC.
881  *
882  * The command returns an sds string representing the result of the
883  * operation. On error the first byte is a "-".
884  */
885 char *sendSynchronousCommand(int fd, ...) {
886     va_list ap;
887     sds cmd = sdsempty();
888     char *arg, buf[256];
889 
890     /* Create the command to send to the master, we use simple inline
891      * protocol for simplicity as currently we only send simple strings. */
892     va_start(ap,fd);
893     while(1) {
894         arg = va_arg(ap, char*);
895         if (arg == NULL) break;
896 
897         if (sdslen(cmd) != 0) cmd = sdscatlen(cmd," ",1);
898         cmd = sdscat(cmd,arg);
899     }
900     cmd = sdscatlen(cmd,"\r\n",2);
901 
902     /* Transfer command to the server. */
903     if (syncWrite(fd,cmd,sdslen(cmd),server.repl_syncio_timeout*1000) == -1) {
904         sdsfree(cmd);
905         return sdscatprintf(sdsempty(),"-Writing to master: %s",
906                 strerror(errno));
907     }
908     sdsfree(cmd);
909 
910     /* Read the reply from the server. */
911     if (syncReadLine(fd,buf,sizeof(buf),server.repl_syncio_timeout*1000) == -1)
912     {
913         return sdscatprintf(sdsempty(),"-Reading from master: %s",
914                 strerror(errno));
915     }
916     return sdsnew(buf);
917 }
918 
919 /* Try a partial resynchronization with the master if we are about to reconnect.
920  * If there is no cached master structure, at least try to issue a
921  * "PSYNC ? -1" command in order to trigger a full resync using the PSYNC
922  * command in order to obtain the master run id and the master replication
923  * global offset.
924  *
925  * This function is designed to be called from syncWithMaster(), so the
926  * following assumptions are made:
927  *
928  * 1) We pass the function an already connected socket "fd".
929  * 2) This function does not close the file descriptor "fd". However in case
930  *    of successful partial resynchronization, the function will reuse
931  *    'fd' as file descriptor of the server.master client structure.
932  *
933  * The function returns:
934  *
935  * PSYNC_CONTINUE: If the PSYNC command succeded and we can continue.
936  * PSYNC_FULLRESYNC: If PSYNC is supported but a full resync is needed.
937  *                   In this case the master run_id and global replication
938  *                   offset is saved.
939  * PSYNC_NOT_SUPPORTED: If the server does not understand PSYNC at all and
940  *                      the caller should fall back to SYNC.
941  */
942 
943 #define PSYNC_CONTINUE 0
944 #define PSYNC_FULLRESYNC 1
945 #define PSYNC_NOT_SUPPORTED 2
946 int slaveTryPartialResynchronization(int fd) {
947     char *psync_runid;
948     char psync_offset[32];
949     sds reply;
950 
951     /* Initially set repl_master_initial_offset to -1 to mark the current
952      * master run_id and offset as not valid. Later if we'll be able to do
953      * a FULL resync using the PSYNC command we'll set the offset at the
954      * right value, so that this information will be propagated to the
955      * client structure representing the master into server.master. */
956     server.repl_master_initial_offset = -1;
957 
958     if (server.cached_master) {
959         psync_runid = server.cached_master->replrunid;
960         snprintf(psync_offset,sizeof(psync_offset),"%lld", server.cached_master->reploff+1);
961         redisLog(REDIS_NOTICE,"Trying a partial resynchronization (request %s:%s).", psync_runid, psync_offset);
962     } else {
963         redisLog(REDIS_NOTICE,"Partial resynchronization not possible (no cached master)");
964         psync_runid = "?";
965         memcpy(psync_offset,"-1",3);
966     }
967 
968     /* Issue the PSYNC command */
969     reply = sendSynchronousCommand(fd,"PSYNC",psync_runid,psync_offset,NULL);
970 
971     if (!strncmp(reply,"+FULLRESYNC",11)) {
972         char *runid = NULL, *offset = NULL;
973 
974         /* FULL RESYNC, parse the reply in order to extract the run id
975          * and the replication offset. */
976         runid = strchr(reply,' ');
977         if (runid) {
978             runid++;
979             offset = strchr(runid,' ');
980             if (offset) offset++;
981         }
982         if (!runid || !offset || (offset-runid-1) != REDIS_RUN_ID_SIZE) {
983             redisLog(REDIS_WARNING,
984                 "Master replied with wrong +FULLRESYNC syntax.");
985             /* This is an unexpected condition, actually the +FULLRESYNC
986              * reply means that the master supports PSYNC, but the reply
987              * format seems wrong. To stay safe we blank the master
988              * runid to make sure next PSYNCs will fail. */
989             memset(server.repl_master_runid,0,REDIS_RUN_ID_SIZE+1);
990         } else {
991             memcpy(server.repl_master_runid, runid, offset-runid-1);
992             server.repl_master_runid[REDIS_RUN_ID_SIZE] = '\0';
993             server.repl_master_initial_offset = strtoll(offset,NULL,10);
994             redisLog(REDIS_NOTICE,"Full resync from master: %s:%lld",
995                 server.repl_master_runid,
996                 server.repl_master_initial_offset);
997         }
998         /* We are going to full resync, discard the cached master structure. */
999         replicationDiscardCachedMaster();
1000         sdsfree(reply);
1001         return PSYNC_FULLRESYNC;
1002     }
1003 
1004     if (!strncmp(reply,"+CONTINUE",9)) {
1005         /* Partial resync was accepted, set the replication state accordingly */
1006         redisLog(REDIS_NOTICE,
1007             "Successful partial resynchronization with master.");
1008         sdsfree(reply);
1009         replicationResurrectCachedMaster(fd);
1010         return PSYNC_CONTINUE;
1011     }
1012 
1013     /* If we reach this point we receied either an error since the master does
1014      * not understand PSYNC, or an unexpected reply from the master.
1015      * Return PSYNC_NOT_SUPPORTED to the caller in both cases. */
1016 
1017     if (strncmp(reply,"-ERR",4)) {
1018         /* If it's not an error, log the unexpected event. */
1019         redisLog(REDIS_WARNING,
1020             "Unexpected reply to PSYNC from master: %s", reply);
1021     } else {
1022         redisLog(REDIS_NOTICE,
1023             "Master does not support PSYNC or is in "
1024             "error state (reply: %s)", reply);
1025     }
1026     sdsfree(reply);
1027     replicationDiscardCachedMaster();
1028     return PSYNC_NOT_SUPPORTED;
1029 }
1030 
1031 void syncWithMaster(aeEventLoop *el, int fd, void *privdata, int mask) {
1032     char tmpfile[256], *err;
1033     int dfd, maxtries = 5;
1034     int sockerr = 0, psync_result;
1035     socklen_t errlen = sizeof(sockerr);
1036     REDIS_NOTUSED(el);
1037     REDIS_NOTUSED(privdata);
1038     REDIS_NOTUSED(mask);
1039 
1040     /* If this event fired after the user turned the instance into a master
1041      * with SLAVEOF NO ONE we must just return ASAP. */
1042     if (server.repl_state == REDIS_REPL_NONE) {
1043         close(fd);
1044         return;
1045     }
1046 
1047     /* Check for errors in the socket. */
1048     if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &sockerr, &errlen) == -1)
1049         sockerr = errno;
1050     if (sockerr) {
1051         aeDeleteFileEvent(server.el,fd,AE_READABLE|AE_WRITABLE);
1052         redisLog(REDIS_WARNING,"Error condition on socket for SYNC: %s",
1053             strerror(sockerr));
1054         goto error;
1055     }
1056 
1057     /* If we were connecting, it's time to send a non blocking PING, we want to
1058      * make sure the master is able to reply before going into the actual
1059      * replication process where we have long timeouts in the order of
1060      * seconds (in the meantime the slave would block). */
1061     if (server.repl_state == REDIS_REPL_CONNECTING) {
1062         redisLog(REDIS_NOTICE,"Non blocking connect for SYNC fired the event.");
1063         /* Delete the writable event so that the readable event remains
1064          * registered and we can wait for the PONG reply. */
1065         aeDeleteFileEvent(server.el,fd,AE_WRITABLE);
1066         server.repl_state = REDIS_REPL_RECEIVE_PONG;
1067         /* Send the PING, don't check for errors at all, we have the timeout
1068          * that will take care about this. */
1069         syncWrite(fd,"PING\r\n",6,100);
1070         return;
1071     }
1072 
1073     /* Receive the PONG command. */
1074     if (server.repl_state == REDIS_REPL_RECEIVE_PONG) {
1075         char buf[1024];
1076 
1077         /* Delete the readable event, we no longer need it now that there is
1078          * the PING reply to read. */
1079         aeDeleteFileEvent(server.el,fd,AE_READABLE);
1080 
1081         /* Read the reply with explicit timeout. */
1082         buf[0] = '\0';
1083         if (syncReadLine(fd,buf,sizeof(buf),
1084             server.repl_syncio_timeout*1000) == -1)
1085         {
1086             redisLog(REDIS_WARNING,
1087                 "I/O error reading PING reply from master: %s",
1088                 strerror(errno));
1089             goto error;
1090         }
1091 
1092         /* We accept only two replies as valid, a positive +PONG reply
1093          * (we just check for "+") or an authentication error.
1094          * Note that older versions of Redis replied with "operation not
1095          * permitted" instead of using a proper error code, so we test
1096          * both. */
1097         if (buf[0] != '+' &&
1098             strncmp(buf,"-NOAUTH",7) != 0 &&
1099             strncmp(buf,"-ERR operation not permitted",28) != 0)
1100         {
1101             redisLog(REDIS_WARNING,"Error reply to PING from master: '%s'",buf);
1102             goto error;
1103         } else {
1104             redisLog(REDIS_NOTICE,
1105                 "Master replied to PING, replication can continue...");
1106         }
1107     }
1108 
1109     /* AUTH with the master if required. */
1110     if(server.masterauth) {
1111         err = sendSynchronousCommand(fd,"AUTH",server.masterauth,NULL);
1112         if (err[0] == '-') {
1113             redisLog(REDIS_WARNING,"Unable to AUTH to MASTER: %s",err);
1114             sdsfree(err);
1115             goto error;
1116         }
1117         sdsfree(err);
1118     }
1119 
1120     /* Set the slave port, so that Master's INFO command can list the
1121      * slave listening port correctly. */
1122     {
1123         sds port = sdsfromlonglong(server.port);
1124         err = sendSynchronousCommand(fd,"REPLCONF","listening-port",port,
1125                                          NULL);
1126         sdsfree(port);
1127         /* Ignore the error if any, not all the Redis versions support
1128          * REPLCONF listening-port. */
1129         if (err[0] == '-') {
1130             redisLog(REDIS_NOTICE,"(Non critical) Master does not understand REPLCONF listening-port: %s", err);
1131         }
1132         sdsfree(err);
1133     }
1134 
1135     /* Try a partial resynchonization. If we don't have a cached master
1136      * slaveTryPartialResynchronization() will at least try to use PSYNC
1137      * to start a full resynchronization so that we get the master run id
1138      * and the global offset, to try a partial resync at the next
1139      * reconnection attempt. */
1140     psync_result = slaveTryPartialResynchronization(fd);
1141     if (psync_result == PSYNC_CONTINUE) {
1142         redisLog(REDIS_NOTICE, "MASTER <-> SLAVE sync: Master accepted a Partial Resynchronization.");
1143         return;
1144     }
1145 
1146     /* Fall back to SYNC if needed. Otherwise psync_result == PSYNC_FULLRESYNC
1147      * and the server.repl_master_runid and repl_master_initial_offset are
1148      * already populated. */
1149     if (psync_result == PSYNC_NOT_SUPPORTED) {
1150         redisLog(REDIS_NOTICE,"Retrying with SYNC...");
1151         if (syncWrite(fd,"SYNC\r\n",6,server.repl_syncio_timeout*1000) == -1) {
1152             redisLog(REDIS_WARNING,"I/O error writing to MASTER: %s",
1153                 strerror(errno));
1154             goto error;
1155         }
1156     }
1157 
1158     /* Prepare a suitable temp file for bulk transfer */
1159     while(maxtries--) {
1160         snprintf(tmpfile,256,
1161             "temp-%d.%ld.rdb",(int)server.unixtime,(long int)getpid());
1162         dfd = open(tmpfile,O_CREAT|O_WRONLY|O_EXCL,0644);
1163         if (dfd != -1) break;
1164         sleep(1);
1165     }
1166     if (dfd == -1) {
1167         redisLog(REDIS_WARNING,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno));
1168         goto error;
1169     }
1170 
1171     /* Setup the non blocking download of the bulk file. */
1172     if (aeCreateFileEvent(server.el,fd, AE_READABLE,readSyncBulkPayload,NULL)
1173             == AE_ERR)
1174     {
1175         redisLog(REDIS_WARNING,
1176             "Can't create readable event for SYNC: %s (fd=%d)",
1177             strerror(errno),fd);
1178         goto error;
1179     }
1180 
1181     server.repl_state = REDIS_REPL_TRANSFER;
1182     server.repl_transfer_size = -1;
1183     server.repl_transfer_read = 0;
1184     server.repl_transfer_last_fsync_off = 0;
1185     server.repl_transfer_fd = dfd;
1186     server.repl_transfer_lastio = server.unixtime;
1187     server.repl_transfer_tmpfile = zstrdup(tmpfile);
1188     return;
1189 
1190 error:
1191     close(fd);
1192     server.repl_transfer_s = -1;
1193     server.repl_state = REDIS_REPL_CONNECT;
1194     return;
1195 }
1196 
1197 int connectWithMaster(void) {
1198     int fd;
1199 
1200     fd = anetTcpNonBlockConnect(NULL,server.masterhost,server.masterport);
1201     if (fd == -1) {
1202         redisLog(REDIS_WARNING,"Unable to connect to MASTER: %s",
1203             strerror(errno));
1204         return REDIS_ERR;
1205     }
1206 
1207     if (aeCreateFileEvent(server.el,fd,AE_READABLE|AE_WRITABLE,syncWithMaster,NULL) ==
1208             AE_ERR)
1209     {
1210         close(fd);
1211         redisLog(REDIS_WARNING,"Can't create readable event for SYNC");
1212         return REDIS_ERR;
1213     }
1214 
1215     server.repl_transfer_lastio = server.unixtime;
1216     server.repl_transfer_s = fd;
1217     server.repl_state = REDIS_REPL_CONNECTING;
1218     return REDIS_OK;
1219 }
1220 
1221 /* This function can be called when a non blocking connection is currently
1222  * in progress to undo it. */
1223 void undoConnectWithMaster(void) {
1224     int fd = server.repl_transfer_s;
1225 
1226     redisAssert(server.repl_state == REDIS_REPL_CONNECTING ||
1227                 server.repl_state == REDIS_REPL_RECEIVE_PONG);
1228     aeDeleteFileEvent(server.el,fd,AE_READABLE|AE_WRITABLE);
1229     close(fd);
1230     server.repl_transfer_s = -1;
1231     server.repl_state = REDIS_REPL_CONNECT;
1232 }
1233 
1234 /* This function aborts a non blocking replication attempt if there is one
1235  * in progress, by canceling the non-blocking connect attempt or
1236  * the initial bulk transfer.
1237  *
1238  * If there was a replication handshake in progress 1 is returned and
1239  * the replication state (server.repl_state) set to REDIS_REPL_CONNECT.
1240  *
1241  * Otherwise zero is returned and no operation is perforemd at all. */
1242 int cancelReplicationHandshake(void) {
1243     if (server.repl_state == REDIS_REPL_TRANSFER) {
1244         replicationAbortSyncTransfer();
1245     } else if (server.repl_state == REDIS_REPL_CONNECTING ||
1246              server.repl_state == REDIS_REPL_RECEIVE_PONG)
1247     {
1248         undoConnectWithMaster();
1249     } else {
1250         return 0;
1251     }
1252     return 1;
1253 }
1254 
1255 /* Set replication to the specified master address and port. */
1256 void replicationSetMaster(char *ip, int port) {
1257     sdsfree(server.masterhost);
1258     server.masterhost = sdsnew(ip);
1259     server.masterport = port;
1260     if (server.master) freeClient(server.master);
1261     disconnectSlaves(); /* Force our slaves to resync with us as well. */
1262     replicationDiscardCachedMaster(); /* Don't try a PSYNC. */
1263     freeReplicationBacklog(); /* Don't allow our chained slaves to PSYNC. */
1264     cancelReplicationHandshake();
1265     server.repl_state = REDIS_REPL_CONNECT;
1266     server.master_repl_offset = 0;
1267     server.repl_down_since = 0;
1268 }
1269 
1270 /* Cancel replication, setting the instance as a master itself. */
1271 void replicationUnsetMaster(void) {
1272     if (server.masterhost == NULL) return; /* Nothing to do. */
1273     sdsfree(server.masterhost);
1274     server.masterhost = NULL;
1275     if (server.master) {
1276         if (listLength(server.slaves) == 0) {
1277             /* If this instance is turned into a master and there are no
1278              * slaves, it inherits the replication offset from the master.
1279              * Under certain conditions this makes replicas comparable by
1280              * replication offset to understand what is the most updated. */
1281             server.master_repl_offset = server.master->reploff;
1282             freeReplicationBacklog();
1283         }
1284         freeClient(server.master);
1285     }
1286     replicationDiscardCachedMaster();
1287     cancelReplicationHandshake();
1288     server.repl_state = REDIS_REPL_NONE;
1289 }
1290 
1291 void slaveofCommand(redisClient *c) {
1292     /* SLAVEOF is not allowed in cluster mode as replication is automatically
1293      * configured using the current address of the master node. */
1294     if (server.cluster_enabled) {
1295         addReplyError(c,"SLAVEOF not allowed in cluster mode.");
1296         return;
1297     }
1298 
1299     /* The special host/port combination "NO" "ONE" turns the instance
1300      * into a master. Otherwise the new master address is set. */
1301     if (!strcasecmp(c->argv[1]->ptr,"no") &&
1302         !strcasecmp(c->argv[2]->ptr,"one")) {
1303         if (server.masterhost) {
1304             replicationUnsetMaster();
1305             redisLog(REDIS_NOTICE,"MASTER MODE enabled (user request)");
1306         }
1307     } else {
1308         long port;
1309 
1310         if ((getLongFromObjectOrReply(c, c->argv[2], &port, NULL) != REDIS_OK))
1311             return;
1312 
1313         /* Check if we are already attached to the specified slave */
1314         if (server.masterhost && !strcasecmp(server.masterhost,c->argv[1]->ptr)
1315             && server.masterport == port) {
1316             redisLog(REDIS_NOTICE,"SLAVE OF would result into synchronization with the master we are already connected with. No operation performed.");
1317             addReplySds(c,sdsnew("+OK Already connected to specified master\r\n"));
1318             return;
1319         }
1320         /* There was no previous master or the user specified a different one,
1321          * we can continue. */
1322         replicationSetMaster(c->argv[1]->ptr, port);
1323         redisLog(REDIS_NOTICE,"SLAVE OF %s:%d enabled (user request)",
1324             server.masterhost, server.masterport);
1325     }
1326     addReply(c,shared.ok);
1327 }
1328 
1329 /* Send a REPLCONF ACK command to the master to inform it about the current
1330  * processed offset. If we are not connected with a master, the command has
1331  * no effects. */
1332 void replicationSendAck(void) {
1333     redisClient *c = server.master;
1334 
1335     if (c != NULL) {
1336         c->flags |= REDIS_MASTER_FORCE_REPLY;
1337         addReplyMultiBulkLen(c,3);
1338         addReplyBulkCString(c,"REPLCONF");
1339         addReplyBulkCString(c,"ACK");
1340         addReplyBulkLongLong(c,c->reploff);
1341         c->flags &= ~REDIS_MASTER_FORCE_REPLY;
1342     }
1343 }
1344 
1345 /* ---------------------- MASTER CACHING FOR PSYNC -------------------------- */
1346 
1347 /* In order to implement partial synchronization we need to be able to cache
1348  * our master's client structure after a transient disconnection.
1349  * It is cached into server.cached_master and flushed away using the following
1350  * functions. */
1351 
1352 /* This function is called by freeClient() in order to cache the master
1353  * client structure instead of destryoing it. freeClient() will return
1354  * ASAP after this function returns, so every action needed to avoid problems
1355  * with a client that is really "suspended" has to be done by this function.
1356  *
1357  * The other functions that will deal with the cached master are:
1358  *
1359  * replicationDiscardCachedMaster() that will make sure to kill the client
1360  * as for some reason we don't want to use it in the future.
1361  *
1362  * replicationResurrectCachedMaster() that is used after a successful PSYNC
1363  * handshake in order to reactivate the cached master.
1364  */
1365 void replicationCacheMaster(redisClient *c) {
1366     listNode *ln;
1367 
1368     redisAssert(server.master != NULL && server.cached_master == NULL);
1369     redisLog(REDIS_NOTICE,"Caching the disconnected master state.");
1370 
1371     /* Remove from the list of clients, we don't want this client to be
1372      * listed by CLIENT LIST or processed in any way by batch operations. */
1373     ln = listSearchKey(server.clients,c);
1374     redisAssert(ln != NULL);
1375     listDelNode(server.clients,ln);
1376 
1377     /* Save the master. Server.master will be set to null later by
1378      * replicationHandleMasterDisconnection(). */
1379     server.cached_master = server.master;
1380 
1381     /* Remove the event handlers and close the socket. We'll later reuse
1382      * the socket of the new connection with the master during PSYNC. */
1383     aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
1384     aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
1385     close(c->fd);
1386 
1387     /* Set fd to -1 so that we can safely call freeClient(c) later. */
1388     c->fd = -1;
1389 
1390     /* Caching the master happens instead of the actual freeClient() call,
1391      * so make sure to adjust the replication state. This function will
1392      * also set server.master to NULL. */
1393     replicationHandleMasterDisconnection();
1394 }
1395 
1396 /* Free a cached master, called when there are no longer the conditions for
1397  * a partial resync on reconnection. */
1398 void replicationDiscardCachedMaster(void) {
1399     if (server.cached_master == NULL) return;
1400 
1401     redisLog(REDIS_NOTICE,"Discarding previously cached master state.");
1402     server.cached_master->flags &= ~REDIS_MASTER;
1403     freeClient(server.cached_master);
1404     server.cached_master = NULL;
1405 }
1406 
1407 /* Turn the cached master into the current master, using the file descriptor
1408  * passed as argument as the socket for the new master.
1409  *
1410  * This funciton is called when successfully setup a partial resynchronization
1411  * so the stream of data that we'll receive will start from were this
1412  * master left. */
1413 void replicationResurrectCachedMaster(int newfd) {
1414     server.master = server.cached_master;
1415     server.cached_master = NULL;
1416     server.master->fd = newfd;
1417     server.master->flags &= ~(REDIS_CLOSE_AFTER_REPLY|REDIS_CLOSE_ASAP);
1418     server.master->authenticated = 1;
1419     server.master->lastinteraction = server.unixtime;
1420     server.repl_state = REDIS_REPL_CONNECTED;
1421 
1422     /* Re-add to the list of clients. */
1423     listAddNodeTail(server.clients,server.master);
1424     if (aeCreateFileEvent(server.el, newfd, AE_READABLE,
1425                           readQueryFromClient, server.master)) {
1426         redisLog(REDIS_WARNING,"Error resurrecting the cached master, impossible to add the readable handler: %s", strerror(errno));
1427         freeClientAsync(server.master); /* Close ASAP. */
1428     }
1429 
1430     /* We may also need to install the write handler as well if there is
1431      * pending data in the write buffers. */
1432     if (server.master->bufpos || listLength(server.master->reply)) {
1433         if (aeCreateFileEvent(server.el, newfd, AE_WRITABLE,
1434                           sendReplyToClient, server.master)) {
1435             redisLog(REDIS_WARNING,"Error resurrecting the cached master, impossible to add the writable handler: %s", strerror(errno));
1436             freeClientAsync(server.master); /* Close ASAP. */
1437         }
1438     }
1439 }
1440 
1441 /* ------------------------- MIN-SLAVES-TO-WRITE  --------------------------- */
1442 
1443 /* This function counts the number of slaves with lag <= min-slaves-max-lag.
1444  * If the option is active, the server will prevent writes if there are not
1445  * enough connected slaves with the specified lag (or less). */
1446 void refreshGoodSlavesCount(void) {
1447     listIter li;
1448     listNode *ln;
1449     int good = 0;
1450 
1451     if (!server.repl_min_slaves_to_write ||
1452         !server.repl_min_slaves_max_lag) return;
1453 
1454     listRewind(server.slaves,&li);
1455     while((ln = listNext(&li))) {
1456         redisClient *slave = ln->value;
1457         time_t lag = server.unixtime - slave->repl_ack_time;
1458 
1459         if (slave->replstate == REDIS_REPL_ONLINE &&
1460             lag <= server.repl_min_slaves_max_lag) good++;
1461     }
1462     server.repl_good_slaves_count = good;
1463 }
1464 
1465 /* ----------------------- REPLICATION SCRIPT CACHE --------------------------
1466  * The goal of this code is to keep track of scripts already sent to every
1467  * connected slave, in order to be able to replicate EVALSHA as it is without
1468  * translating it to EVAL every time it is possible.
1469  *
1470  * We use a capped collection implemented by a hash table for fast lookup
1471  * of scripts we can send as EVALSHA, plus a linked list that is used for
1472  * eviction of the oldest entry when the max number of items is reached.
1473  *
1474  * We don't care about taking a different cache for every different slave
1475  * since to fill the cache again is not very costly, the goal of this code
1476  * is to avoid that the same big script is trasmitted a big number of times
1477  * per second wasting bandwidth and processor speed, but it is not a problem
1478  * if we need to rebuild the cache from scratch from time to time, every used
1479  * script will need to be transmitted a single time to reappear in the cache.
1480  *
1481  * This is how the system works:
1482  *
1483  * 1) Every time a new slave connects, we flush the whole script cache.
1484  * 2) We only send as EVALSHA what was sent to the master as EVALSHA, without
1485  *    trying to convert EVAL into EVALSHA specifically for slaves.
1486  * 3) Every time we trasmit a script as EVAL to the slaves, we also add the
1487  *    corresponding SHA1 of the script into the cache as we are sure every
1488  *    slave knows about the script starting from now.
1489  * 4) On SCRIPT FLUSH command, we replicate the command to all the slaves
1490  *    and at the same time flush the script cache.
1491  * 5) When the last slave disconnects, flush the cache.
1492  * 6) We handle SCRIPT LOAD as well since that's how scripts are loaded
1493  *    in the master sometimes.
1494  */
1495 
1496 /* Initialize the script cache, only called at startup. */
1497 void replicationScriptCacheInit(void) {
1498     server.repl_scriptcache_size = 10000;
1499     server.repl_scriptcache_dict = dictCreate(&replScriptCacheDictType,NULL);
1500     server.repl_scriptcache_fifo = listCreate();
1501 }
1502 
1503 /* Empty the script cache. Should be called every time we are no longer sure
1504  * that every slave knows about all the scripts in our set, or when the
1505  * current AOF "context" is no longer aware of the script. In general we
1506  * should flush the cache:
1507  *
1508  * 1) Every time a new slave reconnects to this master and performs a
1509  *    full SYNC (PSYNC does not require flushing).
1510  * 2) Every time an AOF rewrite is performed.
1511  * 3) Every time we are left without slaves at all, and AOF is off, in order
1512  *    to reclaim otherwise unused memory.
1513  */
1514 void replicationScriptCacheFlush(void) {
1515     dictEmpty(server.repl_scriptcache_dict,NULL);
1516     listRelease(server.repl_scriptcache_fifo);
1517     server.repl_scriptcache_fifo = listCreate();
1518 }
1519 
1520 /* Add an entry into the script cache, if we reach max number of entries the
1521  * oldest is removed from the list. */
1522 void replicationScriptCacheAdd(sds sha1) {
1523     int retval;
1524     sds key = sdsdup(sha1);
1525 
1526     /* Evict oldest. */
1527     if (listLength(server.repl_scriptcache_fifo) == server.repl_scriptcache_size)
1528     {
1529         listNode *ln = listLast(server.repl_scriptcache_fifo);
1530         sds oldest = listNodeValue(ln);
1531 
1532         retval = dictDelete(server.repl_scriptcache_dict,oldest);
1533         redisAssert(retval == DICT_OK);
1534         listDelNode(server.repl_scriptcache_fifo,ln);
1535     }
1536 
1537     /* Add current. */
1538     retval = dictAdd(server.repl_scriptcache_dict,key,NULL);
1539     listAddNodeHead(server.repl_scriptcache_fifo,key);
1540     redisAssert(retval == DICT_OK);
1541 }
1542 
1543 /* Returns non-zero if the specified entry exists inside the cache, that is,
1544  * if all the slaves are aware of this script SHA1. */
1545 int replicationScriptCacheExists(sds sha1) {
1546     return dictFind(server.repl_scriptcache_dict,sha1) != NULL;
1547 }
1548 
1549 /* ----------------------- SYNCHRONOUS REPLICATION --------------------------
1550  * Redis synchronous replication design can be summarized in points:
1551  *
1552  * - Redis masters have a global replication offset, used by PSYNC.
1553  * - Master increment the offset every time new commands are sent to slaves.
1554  * - Slaves ping back masters with the offset processed so far.
1555  *
1556  * So synchronous replication adds a new WAIT command in the form:
1557  *
1558  *   WAIT <num_replicas> <milliseconds_timeout>
1559  *
1560  * That returns the number of replicas that processed the query when
1561  * we finally have at least num_replicas, or when the timeout was
1562  * reached.
1563  *
1564  * The command is implemented in this way:
1565  *
1566  * - Every time a client processes a command, we remember the replication
1567  *   offset after sending that command to the slaves.
1568  * - When WAIT is called, we ask slaves to send an acknowledgement ASAP.
1569  *   The client is blocked at the same time (see blocked.c).
1570  * - Once we receive enough ACKs for a given offset or when the timeout
1571  *   is reached, the WAIT command is unblocked and the reply sent to the
1572  *   client.
1573  */
1574 
1575 /* This just set a flag so that we broadcast a REPLCONF GETACK command
1576  * to all the slaves in the beforeSleep() function. Note that this way
1577  * we "group" all the clients that want to wait for synchronouns replication
1578  * in a given event loop iteration, and send a single GETACK for them all. */
1579 void replicationRequestAckFromSlaves(void) {
1580     server.get_ack_from_slaves = 1;
1581 }
1582 
1583 /* Return the number of slaves that already acknowledged the specified
1584  * replication offset. */
1585 int replicationCountAcksByOffset(long long offset) {
1586     listIter li;
1587     listNode *ln;
1588     int count = 0;
1589 
1590     listRewind(server.slaves,&li);
1591     while((ln = listNext(&li))) {
1592         redisClient *slave = ln->value;
1593 
1594         if (slave->replstate != REDIS_REPL_ONLINE) continue;
1595         if (slave->repl_ack_off >= offset) count++;
1596     }
1597     return count;
1598 }
1599 
1600 /* WAIT for N replicas to acknowledge the processing of our latest
1601  * write command (and all the previous commands). */
1602 void waitCommand(redisClient *c) {
1603     mstime_t timeout;
1604     long numreplicas, ackreplicas;
1605     long long offset = c->woff;
1606 
1607     /* Argument parsing. */
1608     if (getLongFromObjectOrReply(c,c->argv[1],&numreplicas,NULL) != REDIS_OK)
1609         return;
1610     if (getTimeoutFromObjectOrReply(c,c->argv[2],&timeout,UNIT_MILLISECONDS)
1611         != REDIS_OK) return;
1612 
1613     /* First try without blocking at all. */
1614     ackreplicas = replicationCountAcksByOffset(c->woff);
1615     if (ackreplicas >= numreplicas || c->flags & REDIS_MULTI) {
1616         addReplyLongLong(c,ackreplicas);
1617         return;
1618     }
1619 
1620     /* Otherwise block the client and put it into our list of clients
1621      * waiting for ack from slaves. */
1622     c->bpop.timeout = timeout;
1623     c->bpop.reploffset = offset;
1624     c->bpop.numreplicas = numreplicas;
1625     listAddNodeTail(server.clients_waiting_acks,c);
1626     blockClient(c,REDIS_BLOCKED_WAIT);
1627 
1628     /* Make sure that the server will send an ACK request to all the slaves
1629      * before returning to the event loop. */
1630     replicationRequestAckFromSlaves();
1631 }
1632 
1633 /* This is called by unblockClient() to perform the blocking op type
1634  * specific cleanup. We just remove the client from the list of clients
1635  * waiting for replica acks. Never call it directly, call unblockClient()
1636  * instead. */
1637 void unblockClientWaitingReplicas(redisClient *c) {
1638     listNode *ln = listSearchKey(server.clients_waiting_acks,c);
1639     redisAssert(ln != NULL);
1640     listDelNode(server.clients_waiting_acks,ln);
1641 }
1642 
1643 /* Check if there are clients blocked in WAIT that can be unblocked since
1644  * we received enough ACKs from slaves. */
1645 void processClientsWaitingReplicas(void) {
1646     long long last_offset = 0;
1647     int last_numreplicas = 0;
1648 
1649     listIter li;
1650     listNode *ln;
1651 
1652     listRewind(server.clients_waiting_acks,&li);
1653     while((ln = listNext(&li))) {
1654         redisClient *c = ln->value;
1655 
1656         /* Every time we find a client that is satisfied for a given
1657          * offset and number of replicas, we remember it so the next client
1658          * may be unblocked without calling replicationCountAcksByOffset()
1659          * if the requested offset / replicas were equal or less. */
1660         if (last_offset && last_offset > c->bpop.reploffset &&
1661                            last_numreplicas > c->bpop.numreplicas)
1662         {
1663             unblockClient(c);
1664             addReplyLongLong(c,last_numreplicas);
1665         } else {
1666             int numreplicas = replicationCountAcksByOffset(c->bpop.reploffset);
1667 
1668             if (numreplicas >= c->bpop.numreplicas) {
1669                 last_offset = c->bpop.reploffset;
1670                 last_numreplicas = numreplicas;
1671                 unblockClient(c);
1672                 addReplyLongLong(c,numreplicas);
1673             }
1674         }
1675     }
1676 }
1677 
1678 /* Return the slave replication offset for this instance, that is
1679  * the offset for which we already processed the master replication stream. */
1680 long long replicationGetSlaveOffset(void) {
1681     long long offset = 0;
1682 
1683     if (server.masterhost != NULL) {
1684         if (server.master) {
1685             offset = server.master->reploff;
1686         } else if (server.cached_master) {
1687             offset = server.cached_master->reploff;
1688         }
1689     }
1690     /* offset may be -1 when the master does not support it at all, however
1691      * this function is designed to return an offset that can express the
1692      * amount of data processed by the master, so we return a positive
1693      * integer. */
1694     if (offset < 0) offset = 0;
1695     return offset;
1696 }
1697 
1698 /* --------------------------- REPLICATION CRON  ---------------------------- */
1699 
1700 /* Replication cron funciton, called 1 time per second. */
1701 void replicationCron(void) {
1702     /* Non blocking connection timeout? */
1703     if (server.masterhost &&
1704         (server.repl_state == REDIS_REPL_CONNECTING ||
1705          server.repl_state == REDIS_REPL_RECEIVE_PONG) &&
1706         (time(NULL)-server.repl_transfer_lastio) > server.repl_timeout)
1707     {
1708         redisLog(REDIS_WARNING,"Timeout connecting to the MASTER...");
1709         undoConnectWithMaster();
1710     }
1711 
1712     /* Bulk transfer I/O timeout? */
1713     if (server.masterhost && server.repl_state == REDIS_REPL_TRANSFER &&
1714         (time(NULL)-server.repl_transfer_lastio) > server.repl_timeout)
1715     {
1716         redisLog(REDIS_WARNING,"Timeout receiving bulk data from MASTER... If the problem persists try to set the 'repl-timeout' parameter in redis.conf to a larger value.");
1717         replicationAbortSyncTransfer();
1718     }
1719 
1720     /* Timed out master when we are an already connected slave? */
1721     if (server.masterhost && server.repl_state == REDIS_REPL_CONNECTED &&
1722         (time(NULL)-server.master->lastinteraction) > server.repl_timeout)
1723     {
1724         redisLog(REDIS_WARNING,"MASTER timeout: no data nor PING received...");
1725         freeClient(server.master);
1726     }
1727 
1728     /* Check if we should connect to a MASTER */
1729     if (server.repl_state == REDIS_REPL_CONNECT) {
1730         redisLog(REDIS_NOTICE,"Connecting to MASTER %s:%d",
1731             server.masterhost, server.masterport);
1732         if (connectWithMaster() == REDIS_OK) {
1733             redisLog(REDIS_NOTICE,"MASTER <-> SLAVE sync started");
1734         }
1735     }
1736 
1737     /* Send ACK to master from time to time.
1738      * Note that we do not send periodic acks to masters that don't
1739      * support PSYNC and replication offsets. */
1740     if (server.masterhost && server.master &&
1741         !(server.master->flags & REDIS_PRE_PSYNC))
1742         replicationSendAck();
1743 
1744     /* If we have attached slaves, PING them from time to time.
1745      * So slaves can implement an explicit timeout to masters, and will
1746      * be able to detect a link disconnection even if the TCP connection
1747      * will not actually go down. */
1748     if (!(server.cronloops % (server.repl_ping_slave_period * server.hz))) {
1749         listIter li;
1750         listNode *ln;
1751         robj *ping_argv[1];
1752 
1753         /* First, send PING */
1754         ping_argv[0] = createStringObject("PING",4);
1755         replicationFeedSlaves(server.slaves, server.slaveseldb, ping_argv, 1);
1756         decrRefCount(ping_argv[0]);
1757 
1758         /* Second, send a newline to all the slaves in pre-synchronization
1759          * stage, that is, slaves waiting for the master to create the RDB file.
1760          * The newline will be ignored by the slave but will refresh the
1761          * last-io timer preventing a timeout. */
1762         listRewind(server.slaves,&li);
1763         while((ln = listNext(&li))) {
1764             redisClient *slave = ln->value;
1765 
1766             if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START ||
1767                 slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) {
1768                 if (write(slave->fd, "\n", 1) == -1) {
1769                     /* Don't worry, it's just a ping. */
1770                 }
1771             }
1772         }
1773     }
1774 
1775     /* Disconnect timedout slaves. */
1776     if (listLength(server.slaves)) {
1777         listIter li;
1778         listNode *ln;
1779 
1780         listRewind(server.slaves,&li);
1781         while((ln = listNext(&li))) {
1782             redisClient *slave = ln->value;
1783 
1784             if (slave->replstate != REDIS_REPL_ONLINE) continue;
1785             if (slave->flags & REDIS_PRE_PSYNC) continue;
1786             if ((server.unixtime - slave->repl_ack_time) > server.repl_timeout)
1787             {
1788                 char ip[REDIS_IP_STR_LEN];
1789                 int port;
1790 
1791                 if (anetPeerToString(slave->fd,ip,sizeof(ip),&port) != -1) {
1792                     redisLog(REDIS_WARNING,
1793                         "Disconnecting timedout slave: %s:%d",
1794                         ip, slave->slave_listening_port);
1795                 }
1796                 freeClient(slave);
1797             }
1798         }
1799     }
1800 
1801     /* If we have no attached slaves and there is a replication backlog
1802      * using memory, free it after some (configured) time. */
1803     if (listLength(server.slaves) == 0 && server.repl_backlog_time_limit &&
1804         server.repl_backlog)
1805     {
1806         time_t idle = server.unixtime - server.repl_no_slaves_since;
1807 
1808         if (idle > server.repl_backlog_time_limit) {
1809             freeReplicationBacklog();
1810             redisLog(REDIS_NOTICE,
1811                 "Replication backlog freed after %d seconds "
1812                 "without connected slaves.",
1813                 (int) server.repl_backlog_time_limit);
1814         }
1815     }
1816 
1817     /* If AOF is disabled and we no longer have attached slaves, we can
1818      * free our Replication Script Cache as there is no need to propagate
1819      * EVALSHA at all. */
1820     if (listLength(server.slaves) == 0 &&
1821         server.aof_state == REDIS_AOF_OFF &&
1822         listLength(server.repl_scriptcache_fifo) != 0)
1823     {
1824         replicationScriptCacheFlush();
1825     }
1826 
1827     /* Refresh the number of slaves with lag <= min-slaves-max-lag. */
1828     refreshGoodSlavesCount();
1829 }
1830