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