xref: /redis-3.2.3/src/cluster.c (revision 34882878)
1 /* Redis Cluster 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 #include "server.h"
32 #include "cluster.h"
33 #include "endianconv.h"
34 
35 #include <sys/types.h>
36 #include <sys/socket.h>
37 #include <arpa/inet.h>
38 #include <fcntl.h>
39 #include <unistd.h>
40 #include <sys/socket.h>
41 #include <sys/stat.h>
42 #include <sys/file.h>
43 #include <math.h>
44 
45 /* A global reference to myself is handy to make code more clear.
46  * Myself always points to server.cluster->myself, that is, the clusterNode
47  * that represents this node. */
48 clusterNode *myself = NULL;
49 
50 clusterNode *createClusterNode(char *nodename, int flags);
51 int clusterAddNode(clusterNode *node);
52 void clusterAcceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
53 void clusterReadHandler(aeEventLoop *el, int fd, void *privdata, int mask);
54 void clusterSendPing(clusterLink *link, int type);
55 void clusterSendFail(char *nodename);
56 void clusterSendFailoverAuthIfNeeded(clusterNode *node, clusterMsg *request);
57 void clusterUpdateState(void);
58 int clusterNodeGetSlotBit(clusterNode *n, int slot);
59 sds clusterGenNodesDescription(int filter);
60 clusterNode *clusterLookupNode(char *name);
61 int clusterNodeAddSlave(clusterNode *master, clusterNode *slave);
62 int clusterAddSlot(clusterNode *n, int slot);
63 int clusterDelSlot(int slot);
64 int clusterDelNodeSlots(clusterNode *node);
65 int clusterNodeSetSlotBit(clusterNode *n, int slot);
66 void clusterSetMaster(clusterNode *n);
67 void clusterHandleSlaveFailover(void);
68 void clusterHandleSlaveMigration(int max_slaves);
69 int bitmapTestBit(unsigned char *bitmap, int pos);
70 void clusterDoBeforeSleep(int flags);
71 void clusterSendUpdate(clusterLink *link, clusterNode *node);
72 void resetManualFailover(void);
73 void clusterCloseAllSlots(void);
74 void clusterSetNodeAsMaster(clusterNode *n);
75 void clusterDelNode(clusterNode *delnode);
76 sds representClusterNodeFlags(sds ci, uint16_t flags);
77 uint64_t clusterGetMaxEpoch(void);
78 int clusterBumpConfigEpochWithoutConsensus(void);
79 
80 /* -----------------------------------------------------------------------------
81  * Initialization
82  * -------------------------------------------------------------------------- */
83 
84 /* Load the cluster config from 'filename'.
85  *
86  * If the file does not exist or is zero-length (this may happen because
87  * when we lock the nodes.conf file, we create a zero-length one for the
88  * sake of locking if it does not already exist), C_ERR is returned.
89  * If the configuration was loaded from the file, C_OK is returned. */
90 int clusterLoadConfig(char *filename) {
91     FILE *fp = fopen(filename,"r");
92     struct stat sb;
93     char *line;
94     int maxline, j;
95 
96     if (fp == NULL) {
97         if (errno == ENOENT) {
98             return C_ERR;
99         } else {
100             serverLog(LL_WARNING,
101                 "Loading the cluster node config from %s: %s",
102                 filename, strerror(errno));
103             exit(1);
104         }
105     }
106 
107     /* Check if the file is zero-length: if so return C_ERR to signal
108      * we have to write the config. */
109     if (fstat(fileno(fp),&sb) != -1 && sb.st_size == 0) {
110         fclose(fp);
111         return C_ERR;
112     }
113 
114     /* Parse the file. Note that single lines of the cluster config file can
115      * be really long as they include all the hash slots of the node.
116      * This means in the worst possible case, half of the Redis slots will be
117      * present in a single line, possibly in importing or migrating state, so
118      * together with the node ID of the sender/receiver.
119      *
120      * To simplify we allocate 1024+CLUSTER_SLOTS*128 bytes per line. */
121     maxline = 1024+CLUSTER_SLOTS*128;
122     line = zmalloc(maxline);
123     while(fgets(line,maxline,fp) != NULL) {
124         int argc;
125         sds *argv;
126         clusterNode *n, *master;
127         char *p, *s;
128 
129         /* Skip blank lines, they can be created either by users manually
130          * editing nodes.conf or by the config writing process if stopped
131          * before the truncate() call. */
132         if (line[0] == '\n') continue;
133 
134         /* Split the line into arguments for processing. */
135         argv = sdssplitargs(line,&argc);
136         if (argv == NULL) goto fmterr;
137 
138         /* Handle the special "vars" line. Don't pretend it is the last
139          * line even if it actually is when generated by Redis. */
140         if (strcasecmp(argv[0],"vars") == 0) {
141             for (j = 1; j < argc; j += 2) {
142                 if (strcasecmp(argv[j],"currentEpoch") == 0) {
143                     server.cluster->currentEpoch =
144                             strtoull(argv[j+1],NULL,10);
145                 } else if (strcasecmp(argv[j],"lastVoteEpoch") == 0) {
146                     server.cluster->lastVoteEpoch =
147                             strtoull(argv[j+1],NULL,10);
148                 } else {
149                     serverLog(LL_WARNING,
150                         "Skipping unknown cluster config variable '%s'",
151                         argv[j]);
152                 }
153             }
154             sdsfreesplitres(argv,argc);
155             continue;
156         }
157 
158         /* Regular config lines have at least eight fields */
159         if (argc < 8) goto fmterr;
160 
161         /* Create this node if it does not exist */
162         n = clusterLookupNode(argv[0]);
163         if (!n) {
164             n = createClusterNode(argv[0],0);
165             clusterAddNode(n);
166         }
167         /* Address and port */
168         if ((p = strrchr(argv[1],':')) == NULL) goto fmterr;
169         *p = '\0';
170         memcpy(n->ip,argv[1],strlen(argv[1])+1);
171         n->port = atoi(p+1);
172 
173         /* Parse flags */
174         p = s = argv[2];
175         while(p) {
176             p = strchr(s,',');
177             if (p) *p = '\0';
178             if (!strcasecmp(s,"myself")) {
179                 serverAssert(server.cluster->myself == NULL);
180                 myself = server.cluster->myself = n;
181                 n->flags |= CLUSTER_NODE_MYSELF;
182             } else if (!strcasecmp(s,"master")) {
183                 n->flags |= CLUSTER_NODE_MASTER;
184             } else if (!strcasecmp(s,"slave")) {
185                 n->flags |= CLUSTER_NODE_SLAVE;
186             } else if (!strcasecmp(s,"fail?")) {
187                 n->flags |= CLUSTER_NODE_PFAIL;
188             } else if (!strcasecmp(s,"fail")) {
189                 n->flags |= CLUSTER_NODE_FAIL;
190                 n->fail_time = mstime();
191             } else if (!strcasecmp(s,"handshake")) {
192                 n->flags |= CLUSTER_NODE_HANDSHAKE;
193             } else if (!strcasecmp(s,"noaddr")) {
194                 n->flags |= CLUSTER_NODE_NOADDR;
195             } else if (!strcasecmp(s,"noflags")) {
196                 /* nothing to do */
197             } else {
198                 serverPanic("Unknown flag in redis cluster config file");
199             }
200             if (p) s = p+1;
201         }
202 
203         /* Get master if any. Set the master and populate master's
204          * slave list. */
205         if (argv[3][0] != '-') {
206             master = clusterLookupNode(argv[3]);
207             if (!master) {
208                 master = createClusterNode(argv[3],0);
209                 clusterAddNode(master);
210             }
211             n->slaveof = master;
212             clusterNodeAddSlave(master,n);
213         }
214 
215         /* Set ping sent / pong received timestamps */
216         if (atoi(argv[4])) n->ping_sent = mstime();
217         if (atoi(argv[5])) n->pong_received = mstime();
218 
219         /* Set configEpoch for this node. */
220         n->configEpoch = strtoull(argv[6],NULL,10);
221 
222         /* Populate hash slots served by this instance. */
223         for (j = 8; j < argc; j++) {
224             int start, stop;
225 
226             if (argv[j][0] == '[') {
227                 /* Here we handle migrating / importing slots */
228                 int slot;
229                 char direction;
230                 clusterNode *cn;
231 
232                 p = strchr(argv[j],'-');
233                 serverAssert(p != NULL);
234                 *p = '\0';
235                 direction = p[1]; /* Either '>' or '<' */
236                 slot = atoi(argv[j]+1);
237                 p += 3;
238                 cn = clusterLookupNode(p);
239                 if (!cn) {
240                     cn = createClusterNode(p,0);
241                     clusterAddNode(cn);
242                 }
243                 if (direction == '>') {
244                     server.cluster->migrating_slots_to[slot] = cn;
245                 } else {
246                     server.cluster->importing_slots_from[slot] = cn;
247                 }
248                 continue;
249             } else if ((p = strchr(argv[j],'-')) != NULL) {
250                 *p = '\0';
251                 start = atoi(argv[j]);
252                 stop = atoi(p+1);
253             } else {
254                 start = stop = atoi(argv[j]);
255             }
256             while(start <= stop) clusterAddSlot(n, start++);
257         }
258 
259         sdsfreesplitres(argv,argc);
260     }
261     /* Config sanity check */
262     if (server.cluster->myself == NULL) goto fmterr;
263 
264     zfree(line);
265     fclose(fp);
266 
267     serverLog(LL_NOTICE,"Node configuration loaded, I'm %.40s", myself->name);
268 
269     /* Something that should never happen: currentEpoch smaller than
270      * the max epoch found in the nodes configuration. However we handle this
271      * as some form of protection against manual editing of critical files. */
272     if (clusterGetMaxEpoch() > server.cluster->currentEpoch) {
273         server.cluster->currentEpoch = clusterGetMaxEpoch();
274     }
275     return C_OK;
276 
277 fmterr:
278     serverLog(LL_WARNING,
279         "Unrecoverable error: corrupted cluster config file.");
280     zfree(line);
281     if (fp) fclose(fp);
282     exit(1);
283 }
284 
285 /* Cluster node configuration is exactly the same as CLUSTER NODES output.
286  *
287  * This function writes the node config and returns 0, on error -1
288  * is returned.
289  *
290  * Note: we need to write the file in an atomic way from the point of view
291  * of the POSIX filesystem semantics, so that if the server is stopped
292  * or crashes during the write, we'll end with either the old file or the
293  * new one. Since we have the full payload to write available we can use
294  * a single write to write the whole file. If the pre-existing file was
295  * bigger we pad our payload with newlines that are anyway ignored and truncate
296  * the file afterward. */
297 int clusterSaveConfig(int do_fsync) {
298     sds ci;
299     size_t content_size;
300     struct stat sb;
301     int fd;
302 
303     server.cluster->todo_before_sleep &= ~CLUSTER_TODO_SAVE_CONFIG;
304 
305     /* Get the nodes description and concatenate our "vars" directive to
306      * save currentEpoch and lastVoteEpoch. */
307     ci = clusterGenNodesDescription(CLUSTER_NODE_HANDSHAKE);
308     ci = sdscatprintf(ci,"vars currentEpoch %llu lastVoteEpoch %llu\n",
309         (unsigned long long) server.cluster->currentEpoch,
310         (unsigned long long) server.cluster->lastVoteEpoch);
311     content_size = sdslen(ci);
312 
313     if ((fd = open(server.cluster_configfile,O_WRONLY|O_CREAT,0644))
314         == -1) goto err;
315 
316     /* Pad the new payload if the existing file length is greater. */
317     if (fstat(fd,&sb) != -1) {
318         if (sb.st_size > (off_t)content_size) {
319             ci = sdsgrowzero(ci,sb.st_size);
320             memset(ci+content_size,'\n',sb.st_size-content_size);
321         }
322     }
323     if (write(fd,ci,sdslen(ci)) != (ssize_t)sdslen(ci)) goto err;
324     if (do_fsync) {
325         server.cluster->todo_before_sleep &= ~CLUSTER_TODO_FSYNC_CONFIG;
326         fsync(fd);
327     }
328 
329     /* Truncate the file if needed to remove the final \n padding that
330      * is just garbage. */
331     if (content_size != sdslen(ci) && ftruncate(fd,content_size) == -1) {
332         /* ftruncate() failing is not a critical error. */
333     }
334     close(fd);
335     sdsfree(ci);
336     return 0;
337 
338 err:
339     if (fd != -1) close(fd);
340     sdsfree(ci);
341     return -1;
342 }
343 
344 void clusterSaveConfigOrDie(int do_fsync) {
345     if (clusterSaveConfig(do_fsync) == -1) {
346         serverLog(LL_WARNING,"Fatal: can't update cluster config file.");
347         exit(1);
348     }
349 }
350 
351 /* Lock the cluster config using flock(), and leaks the file descritor used to
352  * acquire the lock so that the file will be locked forever.
353  *
354  * This works because we always update nodes.conf with a new version
355  * in-place, reopening the file, and writing to it in place (later adjusting
356  * the length with ftruncate()).
357  *
358  * On success C_OK is returned, otherwise an error is logged and
359  * the function returns C_ERR to signal a lock was not acquired. */
360 int clusterLockConfig(char *filename) {
361 /* flock() does not exist on Solaris
362  * and a fcntl-based solution won't help, as we constantly re-open that file,
363  * which will release _all_ locks anyway
364  */
365 #if !defined(__sun)
366     /* To lock it, we need to open the file in a way it is created if
367      * it does not exist, otherwise there is a race condition with other
368      * processes. */
369     int fd = open(filename,O_WRONLY|O_CREAT,0644);
370     if (fd == -1) {
371         serverLog(LL_WARNING,
372             "Can't open %s in order to acquire a lock: %s",
373             filename, strerror(errno));
374         return C_ERR;
375     }
376 
377     if (flock(fd,LOCK_EX|LOCK_NB) == -1) {
378         if (errno == EWOULDBLOCK) {
379             serverLog(LL_WARNING,
380                  "Sorry, the cluster configuration file %s is already used "
381                  "by a different Redis Cluster node. Please make sure that "
382                  "different nodes use different cluster configuration "
383                  "files.", filename);
384         } else {
385             serverLog(LL_WARNING,
386                 "Impossible to lock %s: %s", filename, strerror(errno));
387         }
388         close(fd);
389         return C_ERR;
390     }
391     /* Lock acquired: leak the 'fd' by not closing it, so that we'll retain the
392      * lock to the file as long as the process exists. */
393 #endif /* __sun */
394 
395     return C_OK;
396 }
397 
398 void clusterInit(void) {
399     int saveconf = 0;
400 
401     server.cluster = zmalloc(sizeof(clusterState));
402     server.cluster->myself = NULL;
403     server.cluster->currentEpoch = 0;
404     server.cluster->state = CLUSTER_FAIL;
405     server.cluster->size = 1;
406     server.cluster->todo_before_sleep = 0;
407     server.cluster->nodes = dictCreate(&clusterNodesDictType,NULL);
408     server.cluster->nodes_black_list =
409         dictCreate(&clusterNodesBlackListDictType,NULL);
410     server.cluster->failover_auth_time = 0;
411     server.cluster->failover_auth_count = 0;
412     server.cluster->failover_auth_rank = 0;
413     server.cluster->failover_auth_epoch = 0;
414     server.cluster->cant_failover_reason = CLUSTER_CANT_FAILOVER_NONE;
415     server.cluster->lastVoteEpoch = 0;
416     server.cluster->stats_bus_messages_sent = 0;
417     server.cluster->stats_bus_messages_received = 0;
418     memset(server.cluster->slots,0, sizeof(server.cluster->slots));
419     clusterCloseAllSlots();
420 
421     /* Lock the cluster config file to make sure every node uses
422      * its own nodes.conf. */
423     if (clusterLockConfig(server.cluster_configfile) == C_ERR)
424         exit(1);
425 
426     /* Load or create a new nodes configuration. */
427     if (clusterLoadConfig(server.cluster_configfile) == C_ERR) {
428         /* No configuration found. We will just use the random name provided
429          * by the createClusterNode() function. */
430         myself = server.cluster->myself =
431             createClusterNode(NULL,CLUSTER_NODE_MYSELF|CLUSTER_NODE_MASTER);
432         serverLog(LL_NOTICE,"No cluster configuration found, I'm %.40s",
433             myself->name);
434         clusterAddNode(myself);
435         saveconf = 1;
436     }
437     if (saveconf) clusterSaveConfigOrDie(1);
438 
439     /* We need a listening TCP port for our cluster messaging needs. */
440     server.cfd_count = 0;
441 
442     /* Port sanity check II
443      * The other handshake port check is triggered too late to stop
444      * us from trying to use a too-high cluster port number. */
445     if (server.port > (65535-CLUSTER_PORT_INCR)) {
446         serverLog(LL_WARNING, "Redis port number too high. "
447                    "Cluster communication port is 10,000 port "
448                    "numbers higher than your Redis port. "
449                    "Your Redis port number must be "
450                    "lower than 55535.");
451         exit(1);
452     }
453 
454     if (listenToPort(server.port+CLUSTER_PORT_INCR,
455         server.cfd,&server.cfd_count) == C_ERR)
456     {
457         exit(1);
458     } else {
459         int j;
460 
461         for (j = 0; j < server.cfd_count; j++) {
462             if (aeCreateFileEvent(server.el, server.cfd[j], AE_READABLE,
463                 clusterAcceptHandler, NULL) == AE_ERR)
464                     serverPanic("Unrecoverable error creating Redis Cluster "
465                                 "file event.");
466         }
467     }
468 
469     /* The slots -> keys map is a sorted set. Init it. */
470     server.cluster->slots_to_keys = zslCreate();
471 
472     /* Set myself->port to my listening port, we'll just need to discover
473      * the IP address via MEET messages. */
474     myself->port = server.port;
475 
476     server.cluster->mf_end = 0;
477     resetManualFailover();
478 }
479 
480 /* Reset a node performing a soft or hard reset:
481  *
482  * 1) All other nodes are forget.
483  * 2) All the assigned / open slots are released.
484  * 3) If the node is a slave, it turns into a master.
485  * 5) Only for hard reset: a new Node ID is generated.
486  * 6) Only for hard reset: currentEpoch and configEpoch are set to 0.
487  * 7) The new configuration is saved and the cluster state updated.
488  * 8) If the node was a slave, the whole data set is flushed away. */
489 void clusterReset(int hard) {
490     dictIterator *di;
491     dictEntry *de;
492     int j;
493 
494     /* Turn into master. */
495     if (nodeIsSlave(myself)) {
496         clusterSetNodeAsMaster(myself);
497         replicationUnsetMaster();
498         emptyDb(NULL);
499     }
500 
501     /* Close slots, reset manual failover state. */
502     clusterCloseAllSlots();
503     resetManualFailover();
504 
505     /* Unassign all the slots. */
506     for (j = 0; j < CLUSTER_SLOTS; j++) clusterDelSlot(j);
507 
508     /* Forget all the nodes, but myself. */
509     di = dictGetSafeIterator(server.cluster->nodes);
510     while((de = dictNext(di)) != NULL) {
511         clusterNode *node = dictGetVal(de);
512 
513         if (node == myself) continue;
514         clusterDelNode(node);
515     }
516     dictReleaseIterator(di);
517 
518     /* Hard reset only: set epochs to 0, change node ID. */
519     if (hard) {
520         sds oldname;
521 
522         server.cluster->currentEpoch = 0;
523         server.cluster->lastVoteEpoch = 0;
524         myself->configEpoch = 0;
525         serverLog(LL_WARNING, "configEpoch set to 0 via CLUSTER RESET HARD");
526 
527         /* To change the Node ID we need to remove the old name from the
528          * nodes table, change the ID, and re-add back with new name. */
529         oldname = sdsnewlen(myself->name, CLUSTER_NAMELEN);
530         dictDelete(server.cluster->nodes,oldname);
531         sdsfree(oldname);
532         getRandomHexChars(myself->name, CLUSTER_NAMELEN);
533         clusterAddNode(myself);
534     }
535 
536     /* Make sure to persist the new config and update the state. */
537     clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
538                          CLUSTER_TODO_UPDATE_STATE|
539                          CLUSTER_TODO_FSYNC_CONFIG);
540 }
541 
542 /* -----------------------------------------------------------------------------
543  * CLUSTER communication link
544  * -------------------------------------------------------------------------- */
545 
546 clusterLink *createClusterLink(clusterNode *node) {
547     clusterLink *link = zmalloc(sizeof(*link));
548     link->ctime = mstime();
549     link->sndbuf = sdsempty();
550     link->rcvbuf = sdsempty();
551     link->node = node;
552     link->fd = -1;
553     return link;
554 }
555 
556 /* Free a cluster link, but does not free the associated node of course.
557  * This function will just make sure that the original node associated
558  * with this link will have the 'link' field set to NULL. */
559 void freeClusterLink(clusterLink *link) {
560     if (link->fd != -1) {
561         aeDeleteFileEvent(server.el, link->fd, AE_WRITABLE);
562         aeDeleteFileEvent(server.el, link->fd, AE_READABLE);
563     }
564     sdsfree(link->sndbuf);
565     sdsfree(link->rcvbuf);
566     if (link->node)
567         link->node->link = NULL;
568     close(link->fd);
569     zfree(link);
570 }
571 
572 #define MAX_CLUSTER_ACCEPTS_PER_CALL 1000
573 void clusterAcceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
574     int cport, cfd;
575     int max = MAX_CLUSTER_ACCEPTS_PER_CALL;
576     char cip[NET_IP_STR_LEN];
577     clusterLink *link;
578     UNUSED(el);
579     UNUSED(mask);
580     UNUSED(privdata);
581 
582     /* If the server is starting up, don't accept cluster connections:
583      * UPDATE messages may interact with the database content. */
584     if (server.masterhost == NULL && server.loading) return;
585 
586     while(max--) {
587         cfd = anetTcpAccept(server.neterr, fd, cip, sizeof(cip), &cport);
588         if (cfd == ANET_ERR) {
589             if (errno != EWOULDBLOCK)
590                 serverLog(LL_VERBOSE,
591                     "Error accepting cluster node: %s", server.neterr);
592             return;
593         }
594         anetNonBlock(NULL,cfd);
595         anetEnableTcpNoDelay(NULL,cfd);
596 
597         /* Use non-blocking I/O for cluster messages. */
598         serverLog(LL_VERBOSE,"Accepted cluster node %s:%d", cip, cport);
599         /* Create a link object we use to handle the connection.
600          * It gets passed to the readable handler when data is available.
601          * Initiallly the link->node pointer is set to NULL as we don't know
602          * which node is, but the right node is references once we know the
603          * node identity. */
604         link = createClusterLink(NULL);
605         link->fd = cfd;
606         aeCreateFileEvent(server.el,cfd,AE_READABLE,clusterReadHandler,link);
607     }
608 }
609 
610 /* -----------------------------------------------------------------------------
611  * Key space handling
612  * -------------------------------------------------------------------------- */
613 
614 /* We have 16384 hash slots. The hash slot of a given key is obtained
615  * as the least significant 14 bits of the crc16 of the key.
616  *
617  * However if the key contains the {...} pattern, only the part between
618  * { and } is hashed. This may be useful in the future to force certain
619  * keys to be in the same node (assuming no resharding is in progress). */
620 unsigned int keyHashSlot(char *key, int keylen) {
621     int s, e; /* start-end indexes of { and } */
622 
623     for (s = 0; s < keylen; s++)
624         if (key[s] == '{') break;
625 
626     /* No '{' ? Hash the whole key. This is the base case. */
627     if (s == keylen) return crc16(key,keylen) & 0x3FFF;
628 
629     /* '{' found? Check if we have the corresponding '}'. */
630     for (e = s+1; e < keylen; e++)
631         if (key[e] == '}') break;
632 
633     /* No '}' or nothing betweeen {} ? Hash the whole key. */
634     if (e == keylen || e == s+1) return crc16(key,keylen) & 0x3FFF;
635 
636     /* If we are here there is both a { and a } on its right. Hash
637      * what is in the middle between { and }. */
638     return crc16(key+s+1,e-s-1) & 0x3FFF;
639 }
640 
641 /* -----------------------------------------------------------------------------
642  * CLUSTER node API
643  * -------------------------------------------------------------------------- */
644 
645 /* Create a new cluster node, with the specified flags.
646  * If "nodename" is NULL this is considered a first handshake and a random
647  * node name is assigned to this node (it will be fixed later when we'll
648  * receive the first pong).
649  *
650  * The node is created and returned to the user, but it is not automatically
651  * added to the nodes hash table. */
652 clusterNode *createClusterNode(char *nodename, int flags) {
653     clusterNode *node = zmalloc(sizeof(*node));
654 
655     if (nodename)
656         memcpy(node->name, nodename, CLUSTER_NAMELEN);
657     else
658         getRandomHexChars(node->name, CLUSTER_NAMELEN);
659     node->ctime = mstime();
660     node->configEpoch = 0;
661     node->flags = flags;
662     memset(node->slots,0,sizeof(node->slots));
663     node->numslots = 0;
664     node->numslaves = 0;
665     node->slaves = NULL;
666     node->slaveof = NULL;
667     node->ping_sent = node->pong_received = 0;
668     node->fail_time = 0;
669     node->link = NULL;
670     memset(node->ip,0,sizeof(node->ip));
671     node->port = 0;
672     node->fail_reports = listCreate();
673     node->voted_time = 0;
674     node->repl_offset_time = 0;
675     node->repl_offset = 0;
676     listSetFreeMethod(node->fail_reports,zfree);
677     return node;
678 }
679 
680 /* This function is called every time we get a failure report from a node.
681  * The side effect is to populate the fail_reports list (or to update
682  * the timestamp of an existing report).
683  *
684  * 'failing' is the node that is in failure state according to the
685  * 'sender' node.
686  *
687  * The function returns 0 if it just updates a timestamp of an existing
688  * failure report from the same sender. 1 is returned if a new failure
689  * report is created. */
690 int clusterNodeAddFailureReport(clusterNode *failing, clusterNode *sender) {
691     list *l = failing->fail_reports;
692     listNode *ln;
693     listIter li;
694     clusterNodeFailReport *fr;
695 
696     /* If a failure report from the same sender already exists, just update
697      * the timestamp. */
698     listRewind(l,&li);
699     while ((ln = listNext(&li)) != NULL) {
700         fr = ln->value;
701         if (fr->node == sender) {
702             fr->time = mstime();
703             return 0;
704         }
705     }
706 
707     /* Otherwise create a new report. */
708     fr = zmalloc(sizeof(*fr));
709     fr->node = sender;
710     fr->time = mstime();
711     listAddNodeTail(l,fr);
712     return 1;
713 }
714 
715 /* Remove failure reports that are too old, where too old means reasonably
716  * older than the global node timeout. Note that anyway for a node to be
717  * flagged as FAIL we need to have a local PFAIL state that is at least
718  * older than the global node timeout, so we don't just trust the number
719  * of failure reports from other nodes. */
720 void clusterNodeCleanupFailureReports(clusterNode *node) {
721     list *l = node->fail_reports;
722     listNode *ln;
723     listIter li;
724     clusterNodeFailReport *fr;
725     mstime_t maxtime = server.cluster_node_timeout *
726                      CLUSTER_FAIL_REPORT_VALIDITY_MULT;
727     mstime_t now = mstime();
728 
729     listRewind(l,&li);
730     while ((ln = listNext(&li)) != NULL) {
731         fr = ln->value;
732         if (now - fr->time > maxtime) listDelNode(l,ln);
733     }
734 }
735 
736 /* Remove the failing report for 'node' if it was previously considered
737  * failing by 'sender'. This function is called when a node informs us via
738  * gossip that a node is OK from its point of view (no FAIL or PFAIL flags).
739  *
740  * Note that this function is called relatively often as it gets called even
741  * when there are no nodes failing, and is O(N), however when the cluster is
742  * fine the failure reports list is empty so the function runs in constant
743  * time.
744  *
745  * The function returns 1 if the failure report was found and removed.
746  * Otherwise 0 is returned. */
747 int clusterNodeDelFailureReport(clusterNode *node, clusterNode *sender) {
748     list *l = node->fail_reports;
749     listNode *ln;
750     listIter li;
751     clusterNodeFailReport *fr;
752 
753     /* Search for a failure report from this sender. */
754     listRewind(l,&li);
755     while ((ln = listNext(&li)) != NULL) {
756         fr = ln->value;
757         if (fr->node == sender) break;
758     }
759     if (!ln) return 0; /* No failure report from this sender. */
760 
761     /* Remove the failure report. */
762     listDelNode(l,ln);
763     clusterNodeCleanupFailureReports(node);
764     return 1;
765 }
766 
767 /* Return the number of external nodes that believe 'node' is failing,
768  * not including this node, that may have a PFAIL or FAIL state for this
769  * node as well. */
770 int clusterNodeFailureReportsCount(clusterNode *node) {
771     clusterNodeCleanupFailureReports(node);
772     return listLength(node->fail_reports);
773 }
774 
775 int clusterNodeRemoveSlave(clusterNode *master, clusterNode *slave) {
776     int j;
777 
778     for (j = 0; j < master->numslaves; j++) {
779         if (master->slaves[j] == slave) {
780             if ((j+1) < master->numslaves) {
781                 int remaining_slaves = (master->numslaves - j) - 1;
782                 memmove(master->slaves+j,master->slaves+(j+1),
783                         (sizeof(*master->slaves) * remaining_slaves));
784             }
785             master->numslaves--;
786             if (master->numslaves == 0)
787                 master->flags &= ~CLUSTER_NODE_MIGRATE_TO;
788             return C_OK;
789         }
790     }
791     return C_ERR;
792 }
793 
794 int clusterNodeAddSlave(clusterNode *master, clusterNode *slave) {
795     int j;
796 
797     /* If it's already a slave, don't add it again. */
798     for (j = 0; j < master->numslaves; j++)
799         if (master->slaves[j] == slave) return C_ERR;
800     master->slaves = zrealloc(master->slaves,
801         sizeof(clusterNode*)*(master->numslaves+1));
802     master->slaves[master->numslaves] = slave;
803     master->numslaves++;
804     master->flags |= CLUSTER_NODE_MIGRATE_TO;
805     return C_OK;
806 }
807 
808 void clusterNodeResetSlaves(clusterNode *n) {
809     zfree(n->slaves);
810     n->numslaves = 0;
811     n->slaves = NULL;
812 }
813 
814 int clusterCountNonFailingSlaves(clusterNode *n) {
815     int j, okslaves = 0;
816 
817     for (j = 0; j < n->numslaves; j++)
818         if (!nodeFailed(n->slaves[j])) okslaves++;
819     return okslaves;
820 }
821 
822 /* Low level cleanup of the node structure. Only called by clusterDelNode(). */
823 void freeClusterNode(clusterNode *n) {
824     sds nodename;
825     int j;
826 
827     /* If the node is a master with associated slaves, we have to set
828      * all the slaves->slaveof fields to NULL (unknown). */
829     if (nodeIsMaster(n)) {
830         for (j = 0; j < n->numslaves; j++)
831             n->slaves[j]->slaveof = NULL;
832     }
833 
834     /* Remove this node from the list of slaves of its master. */
835     if (nodeIsSlave(n) && n->slaveof) clusterNodeRemoveSlave(n->slaveof,n);
836 
837     /* Unlink from the set of nodes. */
838     nodename = sdsnewlen(n->name, CLUSTER_NAMELEN);
839     serverAssert(dictDelete(server.cluster->nodes,nodename) == DICT_OK);
840     sdsfree(nodename);
841 
842     /* Release link and associated data structures. */
843     if (n->link) freeClusterLink(n->link);
844     listRelease(n->fail_reports);
845     zfree(n->slaves);
846     zfree(n);
847 }
848 
849 /* Add a node to the nodes hash table */
850 int clusterAddNode(clusterNode *node) {
851     int retval;
852 
853     retval = dictAdd(server.cluster->nodes,
854             sdsnewlen(node->name,CLUSTER_NAMELEN), node);
855     return (retval == DICT_OK) ? C_OK : C_ERR;
856 }
857 
858 /* Remove a node from the cluster. The functio performs the high level
859  * cleanup, calling freeClusterNode() for the low level cleanup.
860  * Here we do the following:
861  *
862  * 1) Mark all the slots handled by it as unassigned.
863  * 2) Remove all the failure reports sent by this node and referenced by
864  *    other nodes.
865  * 3) Free the node with freeClusterNode() that will in turn remove it
866  *    from the hash table and from the list of slaves of its master, if
867  *    it is a slave node.
868  */
869 void clusterDelNode(clusterNode *delnode) {
870     int j;
871     dictIterator *di;
872     dictEntry *de;
873 
874     /* 1) Mark slots as unassigned. */
875     for (j = 0; j < CLUSTER_SLOTS; j++) {
876         if (server.cluster->importing_slots_from[j] == delnode)
877             server.cluster->importing_slots_from[j] = NULL;
878         if (server.cluster->migrating_slots_to[j] == delnode)
879             server.cluster->migrating_slots_to[j] = NULL;
880         if (server.cluster->slots[j] == delnode)
881             clusterDelSlot(j);
882     }
883 
884     /* 2) Remove failure reports. */
885     di = dictGetSafeIterator(server.cluster->nodes);
886     while((de = dictNext(di)) != NULL) {
887         clusterNode *node = dictGetVal(de);
888 
889         if (node == delnode) continue;
890         clusterNodeDelFailureReport(node,delnode);
891     }
892     dictReleaseIterator(di);
893 
894     /* 3) Free the node, unlinking it from the cluster. */
895     freeClusterNode(delnode);
896 }
897 
898 /* Node lookup by name */
899 clusterNode *clusterLookupNode(char *name) {
900     sds s = sdsnewlen(name, CLUSTER_NAMELEN);
901     dictEntry *de;
902 
903     de = dictFind(server.cluster->nodes,s);
904     sdsfree(s);
905     if (de == NULL) return NULL;
906     return dictGetVal(de);
907 }
908 
909 /* This is only used after the handshake. When we connect a given IP/PORT
910  * as a result of CLUSTER MEET we don't have the node name yet, so we
911  * pick a random one, and will fix it when we receive the PONG request using
912  * this function. */
913 void clusterRenameNode(clusterNode *node, char *newname) {
914     int retval;
915     sds s = sdsnewlen(node->name, CLUSTER_NAMELEN);
916 
917     serverLog(LL_DEBUG,"Renaming node %.40s into %.40s",
918         node->name, newname);
919     retval = dictDelete(server.cluster->nodes, s);
920     sdsfree(s);
921     serverAssert(retval == DICT_OK);
922     memcpy(node->name, newname, CLUSTER_NAMELEN);
923     clusterAddNode(node);
924 }
925 
926 /* -----------------------------------------------------------------------------
927  * CLUSTER config epoch handling
928  * -------------------------------------------------------------------------- */
929 
930 /* Return the greatest configEpoch found in the cluster, or the current
931  * epoch if greater than any node configEpoch. */
932 uint64_t clusterGetMaxEpoch(void) {
933     uint64_t max = 0;
934     dictIterator *di;
935     dictEntry *de;
936 
937     di = dictGetSafeIterator(server.cluster->nodes);
938     while((de = dictNext(di)) != NULL) {
939         clusterNode *node = dictGetVal(de);
940         if (node->configEpoch > max) max = node->configEpoch;
941     }
942     dictReleaseIterator(di);
943     if (max < server.cluster->currentEpoch) max = server.cluster->currentEpoch;
944     return max;
945 }
946 
947 /* If this node epoch is zero or is not already the greatest across the
948  * cluster (from the POV of the local configuration), this function will:
949  *
950  * 1) Generate a new config epoch increment the current epoch.
951  * 2) Assign the new epoch to this node, WITHOUT any consensus.
952  * 3) Persist the configuration on disk before sending packets with the
953  *    new configuration.
954  *
955  * If the new config epoch is generated and assigend, C_OK is returned,
956  * otherwise C_ERR is returned (since the node has already the greatest
957  * configuration around) and no operation is performed.
958  *
959  * Important note: this function violates the principle that config epochs
960  * should be generated with consensus and should be unique across the cluster.
961  * However Redis Cluster uses this auto-generated new config epochs in two
962  * cases:
963  *
964  * 1) When slots are closed after importing. Otherwise resharding would be
965  *    too exansive.
966  * 2) When CLUSTER FAILOVER is called with options that force a slave to
967  *    failover its master even if there is not master majority able to
968  *    create a new configuration epoch.
969  *
970  * Redis Cluster does not explode using this function, even in the case of
971  * a collision between this node and another node, generating the same
972  * configuration epoch unilaterally, because the config epoch conflict
973  * resolution algorithm will eventually move colliding nodes to different
974  * config epochs. However usign this function may violate the "last failover
975  * wins" rule, so should only be used with care. */
976 int clusterBumpConfigEpochWithoutConsensus(void) {
977     uint64_t maxEpoch = clusterGetMaxEpoch();
978 
979     if (myself->configEpoch == 0 ||
980         myself->configEpoch != maxEpoch)
981     {
982         server.cluster->currentEpoch++;
983         myself->configEpoch = server.cluster->currentEpoch;
984         clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
985                              CLUSTER_TODO_FSYNC_CONFIG);
986         serverLog(LL_WARNING,
987             "New configEpoch set to %llu",
988             (unsigned long long) myself->configEpoch);
989         return C_OK;
990     } else {
991         return C_ERR;
992     }
993 }
994 
995 /* This function is called when this node is a master, and we receive from
996  * another master a configuration epoch that is equal to our configuration
997  * epoch.
998  *
999  * BACKGROUND
1000  *
1001  * It is not possible that different slaves get the same config
1002  * epoch during a failover election, because the slaves need to get voted
1003  * by a majority. However when we perform a manual resharding of the cluster
1004  * the node will assign a configuration epoch to itself without to ask
1005  * for agreement. Usually resharding happens when the cluster is working well
1006  * and is supervised by the sysadmin, however it is possible for a failover
1007  * to happen exactly while the node we are resharding a slot to assigns itself
1008  * a new configuration epoch, but before it is able to propagate it.
1009  *
1010  * So technically it is possible in this condition that two nodes end with
1011  * the same configuration epoch.
1012  *
1013  * Another possibility is that there are bugs in the implementation causing
1014  * this to happen.
1015  *
1016  * Moreover when a new cluster is created, all the nodes start with the same
1017  * configEpoch. This collision resolution code allows nodes to automatically
1018  * end with a different configEpoch at startup automatically.
1019  *
1020  * In all the cases, we want a mechanism that resolves this issue automatically
1021  * as a safeguard. The same configuration epoch for masters serving different
1022  * set of slots is not harmful, but it is if the nodes end serving the same
1023  * slots for some reason (manual errors or software bugs) without a proper
1024  * failover procedure.
1025  *
1026  * In general we want a system that eventually always ends with different
1027  * masters having different configuration epochs whatever happened, since
1028  * nothign is worse than a split-brain condition in a distributed system.
1029  *
1030  * BEHAVIOR
1031  *
1032  * When this function gets called, what happens is that if this node
1033  * has the lexicographically smaller Node ID compared to the other node
1034  * with the conflicting epoch (the 'sender' node), it will assign itself
1035  * the greatest configuration epoch currently detected among nodes plus 1.
1036  *
1037  * This means that even if there are multiple nodes colliding, the node
1038  * with the greatest Node ID never moves forward, so eventually all the nodes
1039  * end with a different configuration epoch.
1040  */
1041 void clusterHandleConfigEpochCollision(clusterNode *sender) {
1042     /* Prerequisites: nodes have the same configEpoch and are both masters. */
1043     if (sender->configEpoch != myself->configEpoch ||
1044         !nodeIsMaster(sender) || !nodeIsMaster(myself)) return;
1045     /* Don't act if the colliding node has a smaller Node ID. */
1046     if (memcmp(sender->name,myself->name,CLUSTER_NAMELEN) <= 0) return;
1047     /* Get the next ID available at the best of this node knowledge. */
1048     server.cluster->currentEpoch++;
1049     myself->configEpoch = server.cluster->currentEpoch;
1050     clusterSaveConfigOrDie(1);
1051     serverLog(LL_VERBOSE,
1052         "WARNING: configEpoch collision with node %.40s."
1053         " configEpoch set to %llu",
1054         sender->name,
1055         (unsigned long long) myself->configEpoch);
1056 }
1057 
1058 /* -----------------------------------------------------------------------------
1059  * CLUSTER nodes blacklist
1060  *
1061  * The nodes blacklist is just a way to ensure that a given node with a given
1062  * Node ID is not readded before some time elapsed (this time is specified
1063  * in seconds in CLUSTER_BLACKLIST_TTL).
1064  *
1065  * This is useful when we want to remove a node from the cluster completely:
1066  * when CLUSTER FORGET is called, it also puts the node into the blacklist so
1067  * that even if we receive gossip messages from other nodes that still remember
1068  * about the node we want to remove, we don't re-add it before some time.
1069  *
1070  * Currently the CLUSTER_BLACKLIST_TTL is set to 1 minute, this means
1071  * that redis-trib has 60 seconds to send CLUSTER FORGET messages to nodes
1072  * in the cluster without dealing with the problem of other nodes re-adding
1073  * back the node to nodes we already sent the FORGET command to.
1074  *
1075  * The data structure used is a hash table with an sds string representing
1076  * the node ID as key, and the time when it is ok to re-add the node as
1077  * value.
1078  * -------------------------------------------------------------------------- */
1079 
1080 #define CLUSTER_BLACKLIST_TTL 60      /* 1 minute. */
1081 
1082 
1083 /* Before of the addNode() or Exists() operations we always remove expired
1084  * entries from the black list. This is an O(N) operation but it is not a
1085  * problem since add / exists operations are called very infrequently and
1086  * the hash table is supposed to contain very little elements at max.
1087  * However without the cleanup during long uptimes and with some automated
1088  * node add/removal procedures, entries could accumulate. */
1089 void clusterBlacklistCleanup(void) {
1090     dictIterator *di;
1091     dictEntry *de;
1092 
1093     di = dictGetSafeIterator(server.cluster->nodes_black_list);
1094     while((de = dictNext(di)) != NULL) {
1095         int64_t expire = dictGetUnsignedIntegerVal(de);
1096 
1097         if (expire < server.unixtime)
1098             dictDelete(server.cluster->nodes_black_list,dictGetKey(de));
1099     }
1100     dictReleaseIterator(di);
1101 }
1102 
1103 /* Cleanup the blacklist and add a new node ID to the black list. */
1104 void clusterBlacklistAddNode(clusterNode *node) {
1105     dictEntry *de;
1106     sds id = sdsnewlen(node->name,CLUSTER_NAMELEN);
1107 
1108     clusterBlacklistCleanup();
1109     if (dictAdd(server.cluster->nodes_black_list,id,NULL) == DICT_OK) {
1110         /* If the key was added, duplicate the sds string representation of
1111          * the key for the next lookup. We'll free it at the end. */
1112         id = sdsdup(id);
1113     }
1114     de = dictFind(server.cluster->nodes_black_list,id);
1115     dictSetUnsignedIntegerVal(de,time(NULL)+CLUSTER_BLACKLIST_TTL);
1116     sdsfree(id);
1117 }
1118 
1119 /* Return non-zero if the specified node ID exists in the blacklist.
1120  * You don't need to pass an sds string here, any pointer to 40 bytes
1121  * will work. */
1122 int clusterBlacklistExists(char *nodeid) {
1123     sds id = sdsnewlen(nodeid,CLUSTER_NAMELEN);
1124     int retval;
1125 
1126     clusterBlacklistCleanup();
1127     retval = dictFind(server.cluster->nodes_black_list,id) != NULL;
1128     sdsfree(id);
1129     return retval;
1130 }
1131 
1132 /* -----------------------------------------------------------------------------
1133  * CLUSTER messages exchange - PING/PONG and gossip
1134  * -------------------------------------------------------------------------- */
1135 
1136 /* This function checks if a given node should be marked as FAIL.
1137  * It happens if the following conditions are met:
1138  *
1139  * 1) We received enough failure reports from other master nodes via gossip.
1140  *    Enough means that the majority of the masters signaled the node is
1141  *    down recently.
1142  * 2) We believe this node is in PFAIL state.
1143  *
1144  * If a failure is detected we also inform the whole cluster about this
1145  * event trying to force every other node to set the FAIL flag for the node.
1146  *
1147  * Note that the form of agreement used here is weak, as we collect the majority
1148  * of masters state during some time, and even if we force agreement by
1149  * propagating the FAIL message, because of partitions we may not reach every
1150  * node. However:
1151  *
1152  * 1) Either we reach the majority and eventually the FAIL state will propagate
1153  *    to all the cluster.
1154  * 2) Or there is no majority so no slave promotion will be authorized and the
1155  *    FAIL flag will be cleared after some time.
1156  */
1157 void markNodeAsFailingIfNeeded(clusterNode *node) {
1158     int failures;
1159     int needed_quorum = (server.cluster->size / 2) + 1;
1160 
1161     if (!nodeTimedOut(node)) return; /* We can reach it. */
1162     if (nodeFailed(node)) return; /* Already FAILing. */
1163 
1164     failures = clusterNodeFailureReportsCount(node);
1165     /* Also count myself as a voter if I'm a master. */
1166     if (nodeIsMaster(myself)) failures++;
1167     if (failures < needed_quorum) return; /* No weak agreement from masters. */
1168 
1169     serverLog(LL_NOTICE,
1170         "Marking node %.40s as failing (quorum reached).", node->name);
1171 
1172     /* Mark the node as failing. */
1173     node->flags &= ~CLUSTER_NODE_PFAIL;
1174     node->flags |= CLUSTER_NODE_FAIL;
1175     node->fail_time = mstime();
1176 
1177     /* Broadcast the failing node name to everybody, forcing all the other
1178      * reachable nodes to flag the node as FAIL. */
1179     if (nodeIsMaster(myself)) clusterSendFail(node->name);
1180     clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
1181 }
1182 
1183 /* This function is called only if a node is marked as FAIL, but we are able
1184  * to reach it again. It checks if there are the conditions to undo the FAIL
1185  * state. */
1186 void clearNodeFailureIfNeeded(clusterNode *node) {
1187     mstime_t now = mstime();
1188 
1189     serverAssert(nodeFailed(node));
1190 
1191     /* For slaves we always clear the FAIL flag if we can contact the
1192      * node again. */
1193     if (nodeIsSlave(node) || node->numslots == 0) {
1194         serverLog(LL_NOTICE,
1195             "Clear FAIL state for node %.40s: %s is reachable again.",
1196                 node->name,
1197                 nodeIsSlave(node) ? "slave" : "master without slots");
1198         node->flags &= ~CLUSTER_NODE_FAIL;
1199         clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
1200     }
1201 
1202     /* If it is a master and...
1203      * 1) The FAIL state is old enough.
1204      * 2) It is yet serving slots from our point of view (not failed over).
1205      * Apparently no one is going to fix these slots, clear the FAIL flag. */
1206     if (nodeIsMaster(node) && node->numslots > 0 &&
1207         (now - node->fail_time) >
1208         (server.cluster_node_timeout * CLUSTER_FAIL_UNDO_TIME_MULT))
1209     {
1210         serverLog(LL_NOTICE,
1211             "Clear FAIL state for node %.40s: is reachable again and nobody is serving its slots after some time.",
1212                 node->name);
1213         node->flags &= ~CLUSTER_NODE_FAIL;
1214         clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
1215     }
1216 }
1217 
1218 /* Return true if we already have a node in HANDSHAKE state matching the
1219  * specified ip address and port number. This function is used in order to
1220  * avoid adding a new handshake node for the same address multiple times. */
1221 int clusterHandshakeInProgress(char *ip, int port) {
1222     dictIterator *di;
1223     dictEntry *de;
1224 
1225     di = dictGetSafeIterator(server.cluster->nodes);
1226     while((de = dictNext(di)) != NULL) {
1227         clusterNode *node = dictGetVal(de);
1228 
1229         if (!nodeInHandshake(node)) continue;
1230         if (!strcasecmp(node->ip,ip) && node->port == port) break;
1231     }
1232     dictReleaseIterator(di);
1233     return de != NULL;
1234 }
1235 
1236 /* Start an handshake with the specified address if there is not one
1237  * already in progress. Returns non-zero if the handshake was actually
1238  * started. On error zero is returned and errno is set to one of the
1239  * following values:
1240  *
1241  * EAGAIN - There is already an handshake in progress for this address.
1242  * EINVAL - IP or port are not valid. */
1243 int clusterStartHandshake(char *ip, int port) {
1244     clusterNode *n;
1245     char norm_ip[NET_IP_STR_LEN];
1246     struct sockaddr_storage sa;
1247 
1248     /* IP sanity check */
1249     if (inet_pton(AF_INET,ip,
1250             &(((struct sockaddr_in *)&sa)->sin_addr)))
1251     {
1252         sa.ss_family = AF_INET;
1253     } else if (inet_pton(AF_INET6,ip,
1254             &(((struct sockaddr_in6 *)&sa)->sin6_addr)))
1255     {
1256         sa.ss_family = AF_INET6;
1257     } else {
1258         errno = EINVAL;
1259         return 0;
1260     }
1261 
1262     /* Port sanity check */
1263     if (port <= 0 || port > (65535-CLUSTER_PORT_INCR)) {
1264         errno = EINVAL;
1265         return 0;
1266     }
1267 
1268     /* Set norm_ip as the normalized string representation of the node
1269      * IP address. */
1270     memset(norm_ip,0,NET_IP_STR_LEN);
1271     if (sa.ss_family == AF_INET)
1272         inet_ntop(AF_INET,
1273             (void*)&(((struct sockaddr_in *)&sa)->sin_addr),
1274             norm_ip,NET_IP_STR_LEN);
1275     else
1276         inet_ntop(AF_INET6,
1277             (void*)&(((struct sockaddr_in6 *)&sa)->sin6_addr),
1278             norm_ip,NET_IP_STR_LEN);
1279 
1280     if (clusterHandshakeInProgress(norm_ip,port)) {
1281         errno = EAGAIN;
1282         return 0;
1283     }
1284 
1285     /* Add the node with a random address (NULL as first argument to
1286      * createClusterNode()). Everything will be fixed during the
1287      * handshake. */
1288     n = createClusterNode(NULL,CLUSTER_NODE_HANDSHAKE|CLUSTER_NODE_MEET);
1289     memcpy(n->ip,norm_ip,sizeof(n->ip));
1290     n->port = port;
1291     clusterAddNode(n);
1292     return 1;
1293 }
1294 
1295 /* Process the gossip section of PING or PONG packets.
1296  * Note that this function assumes that the packet is already sanity-checked
1297  * by the caller, not in the content of the gossip section, but in the
1298  * length. */
1299 void clusterProcessGossipSection(clusterMsg *hdr, clusterLink *link) {
1300     uint16_t count = ntohs(hdr->count);
1301     clusterMsgDataGossip *g = (clusterMsgDataGossip*) hdr->data.ping.gossip;
1302     clusterNode *sender = link->node ? link->node : clusterLookupNode(hdr->sender);
1303 
1304     while(count--) {
1305         uint16_t flags = ntohs(g->flags);
1306         clusterNode *node;
1307         sds ci;
1308 
1309         ci = representClusterNodeFlags(sdsempty(), flags);
1310         serverLog(LL_DEBUG,"GOSSIP %.40s %s:%d %s",
1311             g->nodename,
1312             g->ip,
1313             ntohs(g->port),
1314             ci);
1315         sdsfree(ci);
1316 
1317         /* Update our state accordingly to the gossip sections */
1318         node = clusterLookupNode(g->nodename);
1319         if (node) {
1320             /* We already know this node.
1321                Handle failure reports, only when the sender is a master. */
1322             if (sender && nodeIsMaster(sender) && node != myself) {
1323                 if (flags & (CLUSTER_NODE_FAIL|CLUSTER_NODE_PFAIL)) {
1324                     if (clusterNodeAddFailureReport(node,sender)) {
1325                         serverLog(LL_VERBOSE,
1326                             "Node %.40s reported node %.40s as not reachable.",
1327                             sender->name, node->name);
1328                     }
1329                     markNodeAsFailingIfNeeded(node);
1330                 } else {
1331                     if (clusterNodeDelFailureReport(node,sender)) {
1332                         serverLog(LL_VERBOSE,
1333                             "Node %.40s reported node %.40s is back online.",
1334                             sender->name, node->name);
1335                     }
1336                 }
1337             }
1338 
1339             /* If we already know this node, but it is not reachable, and
1340              * we see a different address in the gossip section, start an
1341              * handshake with the (possibly) new address: this will result
1342              * into a node address update if the handshake will be
1343              * successful. */
1344             if (node->flags & (CLUSTER_NODE_FAIL|CLUSTER_NODE_PFAIL) &&
1345                 (strcasecmp(node->ip,g->ip) || node->port != ntohs(g->port)))
1346             {
1347                 clusterStartHandshake(g->ip,ntohs(g->port));
1348             }
1349         } else {
1350             /* If it's not in NOADDR state and we don't have it, we
1351              * start a handshake process against this IP/PORT pairs.
1352              *
1353              * Note that we require that the sender of this gossip message
1354              * is a well known node in our cluster, otherwise we risk
1355              * joining another cluster. */
1356             if (sender &&
1357                 !(flags & CLUSTER_NODE_NOADDR) &&
1358                 !clusterBlacklistExists(g->nodename))
1359             {
1360                 clusterStartHandshake(g->ip,ntohs(g->port));
1361             }
1362         }
1363 
1364         /* Next node */
1365         g++;
1366     }
1367 }
1368 
1369 /* IP -> string conversion. 'buf' is supposed to at least be 46 bytes. */
1370 void nodeIp2String(char *buf, clusterLink *link) {
1371     anetPeerToString(link->fd, buf, NET_IP_STR_LEN, NULL);
1372 }
1373 
1374 /* Update the node address to the IP address that can be extracted
1375  * from link->fd, and at the specified port.
1376  * Also disconnect the node link so that we'll connect again to the new
1377  * address.
1378  *
1379  * If the ip/port pair are already correct no operation is performed at
1380  * all.
1381  *
1382  * The function returns 0 if the node address is still the same,
1383  * otherwise 1 is returned. */
1384 int nodeUpdateAddressIfNeeded(clusterNode *node, clusterLink *link, int port) {
1385     char ip[NET_IP_STR_LEN] = {0};
1386 
1387     /* We don't proceed if the link is the same as the sender link, as this
1388      * function is designed to see if the node link is consistent with the
1389      * symmetric link that is used to receive PINGs from the node.
1390      *
1391      * As a side effect this function never frees the passed 'link', so
1392      * it is safe to call during packet processing. */
1393     if (link == node->link) return 0;
1394 
1395     nodeIp2String(ip,link);
1396     if (node->port == port && strcmp(ip,node->ip) == 0) return 0;
1397 
1398     /* IP / port is different, update it. */
1399     memcpy(node->ip,ip,sizeof(ip));
1400     node->port = port;
1401     if (node->link) freeClusterLink(node->link);
1402     node->flags &= ~CLUSTER_NODE_NOADDR;
1403     serverLog(LL_WARNING,"Address updated for node %.40s, now %s:%d",
1404         node->name, node->ip, node->port);
1405 
1406     /* Check if this is our master and we have to change the
1407      * replication target as well. */
1408     if (nodeIsSlave(myself) && myself->slaveof == node)
1409         replicationSetMaster(node->ip, node->port);
1410     return 1;
1411 }
1412 
1413 /* Reconfigure the specified node 'n' as a master. This function is called when
1414  * a node that we believed to be a slave is now acting as master in order to
1415  * update the state of the node. */
1416 void clusterSetNodeAsMaster(clusterNode *n) {
1417     if (nodeIsMaster(n)) return;
1418 
1419     if (n->slaveof) {
1420         clusterNodeRemoveSlave(n->slaveof,n);
1421         if (n != myself) n->flags |= CLUSTER_NODE_MIGRATE_TO;
1422     }
1423     n->flags &= ~CLUSTER_NODE_SLAVE;
1424     n->flags |= CLUSTER_NODE_MASTER;
1425     n->slaveof = NULL;
1426 
1427     /* Update config and state. */
1428     clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
1429                          CLUSTER_TODO_UPDATE_STATE);
1430 }
1431 
1432 /* This function is called when we receive a master configuration via a
1433  * PING, PONG or UPDATE packet. What we receive is a node, a configEpoch of the
1434  * node, and the set of slots claimed under this configEpoch.
1435  *
1436  * What we do is to rebind the slots with newer configuration compared to our
1437  * local configuration, and if needed, we turn ourself into a replica of the
1438  * node (see the function comments for more info).
1439  *
1440  * The 'sender' is the node for which we received a configuration update.
1441  * Sometimes it is not actually the "Sender" of the information, like in the
1442  * case we receive the info via an UPDATE packet. */
1443 void clusterUpdateSlotsConfigWith(clusterNode *sender, uint64_t senderConfigEpoch, unsigned char *slots) {
1444     int j;
1445     clusterNode *curmaster, *newmaster = NULL;
1446     /* The dirty slots list is a list of slots for which we lose the ownership
1447      * while having still keys inside. This usually happens after a failover
1448      * or after a manual cluster reconfiguration operated by the admin.
1449      *
1450      * If the update message is not able to demote a master to slave (in this
1451      * case we'll resync with the master updating the whole key space), we
1452      * need to delete all the keys in the slots we lost ownership. */
1453     uint16_t dirty_slots[CLUSTER_SLOTS];
1454     int dirty_slots_count = 0;
1455 
1456     /* Here we set curmaster to this node or the node this node
1457      * replicates to if it's a slave. In the for loop we are
1458      * interested to check if slots are taken away from curmaster. */
1459     curmaster = nodeIsMaster(myself) ? myself : myself->slaveof;
1460 
1461     if (sender == myself) {
1462         serverLog(LL_WARNING,"Discarding UPDATE message about myself.");
1463         return;
1464     }
1465 
1466     for (j = 0; j < CLUSTER_SLOTS; j++) {
1467         if (bitmapTestBit(slots,j)) {
1468             /* The slot is already bound to the sender of this message. */
1469             if (server.cluster->slots[j] == sender) continue;
1470 
1471             /* The slot is in importing state, it should be modified only
1472              * manually via redis-trib (example: a resharding is in progress
1473              * and the migrating side slot was already closed and is advertising
1474              * a new config. We still want the slot to be closed manually). */
1475             if (server.cluster->importing_slots_from[j]) continue;
1476 
1477             /* We rebind the slot to the new node claiming it if:
1478              * 1) The slot was unassigned or the new node claims it with a
1479              *    greater configEpoch.
1480              * 2) We are not currently importing the slot. */
1481             if (server.cluster->slots[j] == NULL ||
1482                 server.cluster->slots[j]->configEpoch < senderConfigEpoch)
1483             {
1484                 /* Was this slot mine, and still contains keys? Mark it as
1485                  * a dirty slot. */
1486                 if (server.cluster->slots[j] == myself &&
1487                     countKeysInSlot(j) &&
1488                     sender != myself)
1489                 {
1490                     dirty_slots[dirty_slots_count] = j;
1491                     dirty_slots_count++;
1492                 }
1493 
1494                 if (server.cluster->slots[j] == curmaster)
1495                     newmaster = sender;
1496                 clusterDelSlot(j);
1497                 clusterAddSlot(sender,j);
1498                 clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
1499                                      CLUSTER_TODO_UPDATE_STATE|
1500                                      CLUSTER_TODO_FSYNC_CONFIG);
1501             }
1502         }
1503     }
1504 
1505     /* If at least one slot was reassigned from a node to another node
1506      * with a greater configEpoch, it is possible that:
1507      * 1) We are a master left without slots. This means that we were
1508      *    failed over and we should turn into a replica of the new
1509      *    master.
1510      * 2) We are a slave and our master is left without slots. We need
1511      *    to replicate to the new slots owner. */
1512     if (newmaster && curmaster->numslots == 0) {
1513         serverLog(LL_WARNING,
1514             "Configuration change detected. Reconfiguring myself "
1515             "as a replica of %.40s", sender->name);
1516         clusterSetMaster(sender);
1517         clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
1518                              CLUSTER_TODO_UPDATE_STATE|
1519                              CLUSTER_TODO_FSYNC_CONFIG);
1520     } else if (dirty_slots_count) {
1521         /* If we are here, we received an update message which removed
1522          * ownership for certain slots we still have keys about, but still
1523          * we are serving some slots, so this master node was not demoted to
1524          * a slave.
1525          *
1526          * In order to maintain a consistent state between keys and slots
1527          * we need to remove all the keys from the slots we lost. */
1528         for (j = 0; j < dirty_slots_count; j++)
1529             delKeysInSlot(dirty_slots[j]);
1530     }
1531 }
1532 
1533 /* When this function is called, there is a packet to process starting
1534  * at node->rcvbuf. Releasing the buffer is up to the caller, so this
1535  * function should just handle the higher level stuff of processing the
1536  * packet, modifying the cluster state if needed.
1537  *
1538  * The function returns 1 if the link is still valid after the packet
1539  * was processed, otherwise 0 if the link was freed since the packet
1540  * processing lead to some inconsistency error (for instance a PONG
1541  * received from the wrong sender ID). */
1542 int clusterProcessPacket(clusterLink *link) {
1543     clusterMsg *hdr = (clusterMsg*) link->rcvbuf;
1544     uint32_t totlen = ntohl(hdr->totlen);
1545     uint16_t type = ntohs(hdr->type);
1546     uint16_t flags = ntohs(hdr->flags);
1547     uint64_t senderCurrentEpoch = 0, senderConfigEpoch = 0;
1548     clusterNode *sender;
1549 
1550     server.cluster->stats_bus_messages_received++;
1551     serverLog(LL_DEBUG,"--- Processing packet of type %d, %lu bytes",
1552         type, (unsigned long) totlen);
1553 
1554     /* Perform sanity checks */
1555     if (totlen < 16) return 1; /* At least signature, version, totlen, count. */
1556     if (ntohs(hdr->ver) != CLUSTER_PROTO_VER)
1557         return 1; /* Can't handle versions other than the current one.*/
1558     if (totlen > sdslen(link->rcvbuf)) return 1;
1559     if (type == CLUSTERMSG_TYPE_PING || type == CLUSTERMSG_TYPE_PONG ||
1560         type == CLUSTERMSG_TYPE_MEET)
1561     {
1562         uint16_t count = ntohs(hdr->count);
1563         uint32_t explen; /* expected length of this packet */
1564 
1565         explen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
1566         explen += (sizeof(clusterMsgDataGossip)*count);
1567         if (totlen != explen) return 1;
1568     } else if (type == CLUSTERMSG_TYPE_FAIL) {
1569         uint32_t explen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
1570 
1571         explen += sizeof(clusterMsgDataFail);
1572         if (totlen != explen) return 1;
1573     } else if (type == CLUSTERMSG_TYPE_PUBLISH) {
1574         uint32_t explen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
1575 
1576         explen += sizeof(clusterMsgDataPublish) -
1577                 8 +
1578                 ntohl(hdr->data.publish.msg.channel_len) +
1579                 ntohl(hdr->data.publish.msg.message_len);
1580         if (totlen != explen) return 1;
1581     } else if (type == CLUSTERMSG_TYPE_FAILOVER_AUTH_REQUEST ||
1582                type == CLUSTERMSG_TYPE_FAILOVER_AUTH_ACK ||
1583                type == CLUSTERMSG_TYPE_MFSTART)
1584     {
1585         uint32_t explen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
1586 
1587         if (totlen != explen) return 1;
1588     } else if (type == CLUSTERMSG_TYPE_UPDATE) {
1589         uint32_t explen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
1590 
1591         explen += sizeof(clusterMsgDataUpdate);
1592         if (totlen != explen) return 1;
1593     }
1594 
1595     /* Check if the sender is a known node. */
1596     sender = clusterLookupNode(hdr->sender);
1597     if (sender && !nodeInHandshake(sender)) {
1598         /* Update our curretEpoch if we see a newer epoch in the cluster. */
1599         senderCurrentEpoch = ntohu64(hdr->currentEpoch);
1600         senderConfigEpoch = ntohu64(hdr->configEpoch);
1601         if (senderCurrentEpoch > server.cluster->currentEpoch)
1602             server.cluster->currentEpoch = senderCurrentEpoch;
1603         /* Update the sender configEpoch if it is publishing a newer one. */
1604         if (senderConfigEpoch > sender->configEpoch) {
1605             sender->configEpoch = senderConfigEpoch;
1606             clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
1607                                  CLUSTER_TODO_FSYNC_CONFIG);
1608         }
1609         /* Update the replication offset info for this node. */
1610         sender->repl_offset = ntohu64(hdr->offset);
1611         sender->repl_offset_time = mstime();
1612         /* If we are a slave performing a manual failover and our master
1613          * sent its offset while already paused, populate the MF state. */
1614         if (server.cluster->mf_end &&
1615             nodeIsSlave(myself) &&
1616             myself->slaveof == sender &&
1617             hdr->mflags[0] & CLUSTERMSG_FLAG0_PAUSED &&
1618             server.cluster->mf_master_offset == 0)
1619         {
1620             server.cluster->mf_master_offset = sender->repl_offset;
1621             serverLog(LL_WARNING,
1622                 "Received replication offset for paused "
1623                 "master manual failover: %lld",
1624                 server.cluster->mf_master_offset);
1625         }
1626     }
1627 
1628     /* Initial processing of PING and MEET requests replying with a PONG. */
1629     if (type == CLUSTERMSG_TYPE_PING || type == CLUSTERMSG_TYPE_MEET) {
1630         serverLog(LL_DEBUG,"Ping packet received: %p", (void*)link->node);
1631 
1632         /* We use incoming MEET messages in order to set the address
1633          * for 'myself', since only other cluster nodes will send us
1634          * MEET messagses on handshakes, when the cluster joins, or
1635          * later if we changed address, and those nodes will use our
1636          * official address to connect to us. So by obtaining this address
1637          * from the socket is a simple way to discover / update our own
1638          * address in the cluster without it being hardcoded in the config.
1639          *
1640          * However if we don't have an address at all, we update the address
1641          * even with a normal PING packet. If it's wrong it will be fixed
1642          * by MEET later. */
1643         if (type == CLUSTERMSG_TYPE_MEET || myself->ip[0] == '\0') {
1644             char ip[NET_IP_STR_LEN];
1645 
1646             if (anetSockName(link->fd,ip,sizeof(ip),NULL) != -1 &&
1647                 strcmp(ip,myself->ip))
1648             {
1649                 memcpy(myself->ip,ip,NET_IP_STR_LEN);
1650                 serverLog(LL_WARNING,"IP address for this node updated to %s",
1651                     myself->ip);
1652                 clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG);
1653             }
1654         }
1655 
1656         /* Add this node if it is new for us and the msg type is MEET.
1657          * In this stage we don't try to add the node with the right
1658          * flags, slaveof pointer, and so forth, as this details will be
1659          * resolved when we'll receive PONGs from the node. */
1660         if (!sender && type == CLUSTERMSG_TYPE_MEET) {
1661             clusterNode *node;
1662 
1663             node = createClusterNode(NULL,CLUSTER_NODE_HANDSHAKE);
1664             nodeIp2String(node->ip,link);
1665             node->port = ntohs(hdr->port);
1666             clusterAddNode(node);
1667             clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG);
1668         }
1669 
1670         /* If this is a MEET packet from an unknown node, we still process
1671          * the gossip section here since we have to trust the sender because
1672          * of the message type. */
1673         if (!sender && type == CLUSTERMSG_TYPE_MEET)
1674             clusterProcessGossipSection(hdr,link);
1675 
1676         /* Anyway reply with a PONG */
1677         clusterSendPing(link,CLUSTERMSG_TYPE_PONG);
1678     }
1679 
1680     /* PING, PONG, MEET: process config information. */
1681     if (type == CLUSTERMSG_TYPE_PING || type == CLUSTERMSG_TYPE_PONG ||
1682         type == CLUSTERMSG_TYPE_MEET)
1683     {
1684         serverLog(LL_DEBUG,"%s packet received: %p",
1685             type == CLUSTERMSG_TYPE_PING ? "ping" : "pong",
1686             (void*)link->node);
1687         if (link->node) {
1688             if (nodeInHandshake(link->node)) {
1689                 /* If we already have this node, try to change the
1690                  * IP/port of the node with the new one. */
1691                 if (sender) {
1692                     serverLog(LL_VERBOSE,
1693                         "Handshake: we already know node %.40s, "
1694                         "updating the address if needed.", sender->name);
1695                     if (nodeUpdateAddressIfNeeded(sender,link,ntohs(hdr->port)))
1696                     {
1697                         clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
1698                                              CLUSTER_TODO_UPDATE_STATE);
1699                     }
1700                     /* Free this node as we already have it. This will
1701                      * cause the link to be freed as well. */
1702                     clusterDelNode(link->node);
1703                     return 0;
1704                 }
1705 
1706                 /* First thing to do is replacing the random name with the
1707                  * right node name if this was a handshake stage. */
1708                 clusterRenameNode(link->node, hdr->sender);
1709                 serverLog(LL_DEBUG,"Handshake with node %.40s completed.",
1710                     link->node->name);
1711                 link->node->flags &= ~CLUSTER_NODE_HANDSHAKE;
1712                 link->node->flags |= flags&(CLUSTER_NODE_MASTER|CLUSTER_NODE_SLAVE);
1713                 clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG);
1714             } else if (memcmp(link->node->name,hdr->sender,
1715                         CLUSTER_NAMELEN) != 0)
1716             {
1717                 /* If the reply has a non matching node ID we
1718                  * disconnect this node and set it as not having an associated
1719                  * address. */
1720                 serverLog(LL_DEBUG,"PONG contains mismatching sender ID");
1721                 link->node->flags |= CLUSTER_NODE_NOADDR;
1722                 link->node->ip[0] = '\0';
1723                 link->node->port = 0;
1724                 freeClusterLink(link);
1725                 clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG);
1726                 return 0;
1727             }
1728         }
1729 
1730         /* Update the node address if it changed. */
1731         if (sender && type == CLUSTERMSG_TYPE_PING &&
1732             !nodeInHandshake(sender) &&
1733             nodeUpdateAddressIfNeeded(sender,link,ntohs(hdr->port)))
1734         {
1735             clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
1736                                  CLUSTER_TODO_UPDATE_STATE);
1737         }
1738 
1739         /* Update our info about the node */
1740         if (link->node && type == CLUSTERMSG_TYPE_PONG) {
1741             link->node->pong_received = mstime();
1742             link->node->ping_sent = 0;
1743 
1744             /* The PFAIL condition can be reversed without external
1745              * help if it is momentary (that is, if it does not
1746              * turn into a FAIL state).
1747              *
1748              * The FAIL condition is also reversible under specific
1749              * conditions detected by clearNodeFailureIfNeeded(). */
1750             if (nodeTimedOut(link->node)) {
1751                 link->node->flags &= ~CLUSTER_NODE_PFAIL;
1752                 clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
1753                                      CLUSTER_TODO_UPDATE_STATE);
1754             } else if (nodeFailed(link->node)) {
1755                 clearNodeFailureIfNeeded(link->node);
1756             }
1757         }
1758 
1759         /* Check for role switch: slave -> master or master -> slave. */
1760         if (sender) {
1761             if (!memcmp(hdr->slaveof,CLUSTER_NODE_NULL_NAME,
1762                 sizeof(hdr->slaveof)))
1763             {
1764                 /* Node is a master. */
1765                 clusterSetNodeAsMaster(sender);
1766             } else {
1767                 /* Node is a slave. */
1768                 clusterNode *master = clusterLookupNode(hdr->slaveof);
1769 
1770                 if (nodeIsMaster(sender)) {
1771                     /* Master turned into a slave! Reconfigure the node. */
1772                     clusterDelNodeSlots(sender);
1773                     sender->flags &= ~(CLUSTER_NODE_MASTER|
1774                                        CLUSTER_NODE_MIGRATE_TO);
1775                     sender->flags |= CLUSTER_NODE_SLAVE;
1776 
1777                     /* Remove the list of slaves from the node. */
1778                     if (sender->numslaves) clusterNodeResetSlaves(sender);
1779 
1780                     /* Update config and state. */
1781                     clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
1782                                          CLUSTER_TODO_UPDATE_STATE);
1783                 }
1784 
1785                 /* Master node changed for this slave? */
1786                 if (master && sender->slaveof != master) {
1787                     if (sender->slaveof)
1788                         clusterNodeRemoveSlave(sender->slaveof,sender);
1789                     clusterNodeAddSlave(master,sender);
1790                     sender->slaveof = master;
1791 
1792                     /* Update config. */
1793                     clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG);
1794                 }
1795             }
1796         }
1797 
1798         /* Update our info about served slots.
1799          *
1800          * Note: this MUST happen after we update the master/slave state
1801          * so that CLUSTER_NODE_MASTER flag will be set. */
1802 
1803         /* Many checks are only needed if the set of served slots this
1804          * instance claims is different compared to the set of slots we have
1805          * for it. Check this ASAP to avoid other computational expansive
1806          * checks later. */
1807         clusterNode *sender_master = NULL; /* Sender or its master if slave. */
1808         int dirty_slots = 0; /* Sender claimed slots don't match my view? */
1809 
1810         if (sender) {
1811             sender_master = nodeIsMaster(sender) ? sender : sender->slaveof;
1812             if (sender_master) {
1813                 dirty_slots = memcmp(sender_master->slots,
1814                         hdr->myslots,sizeof(hdr->myslots)) != 0;
1815             }
1816         }
1817 
1818         /* 1) If the sender of the message is a master, and we detected that
1819          *    the set of slots it claims changed, scan the slots to see if we
1820          *    need to update our configuration. */
1821         if (sender && nodeIsMaster(sender) && dirty_slots)
1822             clusterUpdateSlotsConfigWith(sender,senderConfigEpoch,hdr->myslots);
1823 
1824         /* 2) We also check for the reverse condition, that is, the sender
1825          *    claims to serve slots we know are served by a master with a
1826          *    greater configEpoch. If this happens we inform the sender.
1827          *
1828          * This is useful because sometimes after a partition heals, a
1829          * reappearing master may be the last one to claim a given set of
1830          * hash slots, but with a configuration that other instances know to
1831          * be deprecated. Example:
1832          *
1833          * A and B are master and slave for slots 1,2,3.
1834          * A is partitioned away, B gets promoted.
1835          * B is partitioned away, and A returns available.
1836          *
1837          * Usually B would PING A publishing its set of served slots and its
1838          * configEpoch, but because of the partition B can't inform A of the
1839          * new configuration, so other nodes that have an updated table must
1840          * do it. In this way A will stop to act as a master (or can try to
1841          * failover if there are the conditions to win the election). */
1842         if (sender && dirty_slots) {
1843             int j;
1844 
1845             for (j = 0; j < CLUSTER_SLOTS; j++) {
1846                 if (bitmapTestBit(hdr->myslots,j)) {
1847                     if (server.cluster->slots[j] == sender ||
1848                         server.cluster->slots[j] == NULL) continue;
1849                     if (server.cluster->slots[j]->configEpoch >
1850                         senderConfigEpoch)
1851                     {
1852                         serverLog(LL_VERBOSE,
1853                             "Node %.40s has old slots configuration, sending "
1854                             "an UPDATE message about %.40s",
1855                                 sender->name, server.cluster->slots[j]->name);
1856                         clusterSendUpdate(sender->link,
1857                             server.cluster->slots[j]);
1858 
1859                         /* TODO: instead of exiting the loop send every other
1860                          * UPDATE packet for other nodes that are the new owner
1861                          * of sender's slots. */
1862                         break;
1863                     }
1864                 }
1865             }
1866         }
1867 
1868         /* If our config epoch collides with the sender's try to fix
1869          * the problem. */
1870         if (sender &&
1871             nodeIsMaster(myself) && nodeIsMaster(sender) &&
1872             senderConfigEpoch == myself->configEpoch)
1873         {
1874             clusterHandleConfigEpochCollision(sender);
1875         }
1876 
1877         /* Get info from the gossip section */
1878         if (sender) clusterProcessGossipSection(hdr,link);
1879     } else if (type == CLUSTERMSG_TYPE_FAIL) {
1880         clusterNode *failing;
1881 
1882         if (sender) {
1883             failing = clusterLookupNode(hdr->data.fail.about.nodename);
1884             if (failing &&
1885                 !(failing->flags & (CLUSTER_NODE_FAIL|CLUSTER_NODE_MYSELF)))
1886             {
1887                 serverLog(LL_NOTICE,
1888                     "FAIL message received from %.40s about %.40s",
1889                     hdr->sender, hdr->data.fail.about.nodename);
1890                 failing->flags |= CLUSTER_NODE_FAIL;
1891                 failing->fail_time = mstime();
1892                 failing->flags &= ~CLUSTER_NODE_PFAIL;
1893                 clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
1894                                      CLUSTER_TODO_UPDATE_STATE);
1895             }
1896         } else {
1897             serverLog(LL_NOTICE,
1898                 "Ignoring FAIL message from unknown node %.40s about %.40s",
1899                 hdr->sender, hdr->data.fail.about.nodename);
1900         }
1901     } else if (type == CLUSTERMSG_TYPE_PUBLISH) {
1902         robj *channel, *message;
1903         uint32_t channel_len, message_len;
1904 
1905         /* Don't bother creating useless objects if there are no
1906          * Pub/Sub subscribers. */
1907         if (dictSize(server.pubsub_channels) ||
1908            listLength(server.pubsub_patterns))
1909         {
1910             channel_len = ntohl(hdr->data.publish.msg.channel_len);
1911             message_len = ntohl(hdr->data.publish.msg.message_len);
1912             channel = createStringObject(
1913                         (char*)hdr->data.publish.msg.bulk_data,channel_len);
1914             message = createStringObject(
1915                         (char*)hdr->data.publish.msg.bulk_data+channel_len,
1916                         message_len);
1917             pubsubPublishMessage(channel,message);
1918             decrRefCount(channel);
1919             decrRefCount(message);
1920         }
1921     } else if (type == CLUSTERMSG_TYPE_FAILOVER_AUTH_REQUEST) {
1922         if (!sender) return 1;  /* We don't know that node. */
1923         clusterSendFailoverAuthIfNeeded(sender,hdr);
1924     } else if (type == CLUSTERMSG_TYPE_FAILOVER_AUTH_ACK) {
1925         if (!sender) return 1;  /* We don't know that node. */
1926         /* We consider this vote only if the sender is a master serving
1927          * a non zero number of slots, and its currentEpoch is greater or
1928          * equal to epoch where this node started the election. */
1929         if (nodeIsMaster(sender) && sender->numslots > 0 &&
1930             senderCurrentEpoch >= server.cluster->failover_auth_epoch)
1931         {
1932             server.cluster->failover_auth_count++;
1933             /* Maybe we reached a quorum here, set a flag to make sure
1934              * we check ASAP. */
1935             clusterDoBeforeSleep(CLUSTER_TODO_HANDLE_FAILOVER);
1936         }
1937     } else if (type == CLUSTERMSG_TYPE_MFSTART) {
1938         /* This message is acceptable only if I'm a master and the sender
1939          * is one of my slaves. */
1940         if (!sender || sender->slaveof != myself) return 1;
1941         /* Manual failover requested from slaves. Initialize the state
1942          * accordingly. */
1943         resetManualFailover();
1944         server.cluster->mf_end = mstime() + CLUSTER_MF_TIMEOUT;
1945         server.cluster->mf_slave = sender;
1946         pauseClients(mstime()+(CLUSTER_MF_TIMEOUT*2));
1947         serverLog(LL_WARNING,"Manual failover requested by slave %.40s.",
1948             sender->name);
1949     } else if (type == CLUSTERMSG_TYPE_UPDATE) {
1950         clusterNode *n; /* The node the update is about. */
1951         uint64_t reportedConfigEpoch =
1952                     ntohu64(hdr->data.update.nodecfg.configEpoch);
1953 
1954         if (!sender) return 1;  /* We don't know the sender. */
1955         n = clusterLookupNode(hdr->data.update.nodecfg.nodename);
1956         if (!n) return 1;   /* We don't know the reported node. */
1957         if (n->configEpoch >= reportedConfigEpoch) return 1; /* Nothing new. */
1958 
1959         /* If in our current config the node is a slave, set it as a master. */
1960         if (nodeIsSlave(n)) clusterSetNodeAsMaster(n);
1961 
1962         /* Update the node's configEpoch. */
1963         n->configEpoch = reportedConfigEpoch;
1964         clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
1965                              CLUSTER_TODO_FSYNC_CONFIG);
1966 
1967         /* Check the bitmap of served slots and update our
1968          * config accordingly. */
1969         clusterUpdateSlotsConfigWith(n,reportedConfigEpoch,
1970             hdr->data.update.nodecfg.slots);
1971     } else {
1972         serverLog(LL_WARNING,"Received unknown packet type: %d", type);
1973     }
1974     return 1;
1975 }
1976 
1977 /* This function is called when we detect the link with this node is lost.
1978    We set the node as no longer connected. The Cluster Cron will detect
1979    this connection and will try to get it connected again.
1980 
1981    Instead if the node is a temporary node used to accept a query, we
1982    completely free the node on error. */
1983 void handleLinkIOError(clusterLink *link) {
1984     freeClusterLink(link);
1985 }
1986 
1987 /* Send data. This is handled using a trivial send buffer that gets
1988  * consumed by write(). We don't try to optimize this for speed too much
1989  * as this is a very low traffic channel. */
1990 void clusterWriteHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
1991     clusterLink *link = (clusterLink*) privdata;
1992     ssize_t nwritten;
1993     UNUSED(el);
1994     UNUSED(mask);
1995 
1996     nwritten = write(fd, link->sndbuf, sdslen(link->sndbuf));
1997     if (nwritten <= 0) {
1998         serverLog(LL_DEBUG,"I/O error writing to node link: %s",
1999             strerror(errno));
2000         handleLinkIOError(link);
2001         return;
2002     }
2003     sdsrange(link->sndbuf,nwritten,-1);
2004     if (sdslen(link->sndbuf) == 0)
2005         aeDeleteFileEvent(server.el, link->fd, AE_WRITABLE);
2006 }
2007 
2008 /* Read data. Try to read the first field of the header first to check the
2009  * full length of the packet. When a whole packet is in memory this function
2010  * will call the function to process the packet. And so forth. */
2011 void clusterReadHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
2012     char buf[sizeof(clusterMsg)];
2013     ssize_t nread;
2014     clusterMsg *hdr;
2015     clusterLink *link = (clusterLink*) privdata;
2016     unsigned int readlen, rcvbuflen;
2017     UNUSED(el);
2018     UNUSED(mask);
2019 
2020     while(1) { /* Read as long as there is data to read. */
2021         rcvbuflen = sdslen(link->rcvbuf);
2022         if (rcvbuflen < 8) {
2023             /* First, obtain the first 8 bytes to get the full message
2024              * length. */
2025             readlen = 8 - rcvbuflen;
2026         } else {
2027             /* Finally read the full message. */
2028             hdr = (clusterMsg*) link->rcvbuf;
2029             if (rcvbuflen == 8) {
2030                 /* Perform some sanity check on the message signature
2031                  * and length. */
2032                 if (memcmp(hdr->sig,"RCmb",4) != 0 ||
2033                     ntohl(hdr->totlen) < CLUSTERMSG_MIN_LEN)
2034                 {
2035                     serverLog(LL_WARNING,
2036                         "Bad message length or signature received "
2037                         "from Cluster bus.");
2038                     handleLinkIOError(link);
2039                     return;
2040                 }
2041             }
2042             readlen = ntohl(hdr->totlen) - rcvbuflen;
2043             if (readlen > sizeof(buf)) readlen = sizeof(buf);
2044         }
2045 
2046         nread = read(fd,buf,readlen);
2047         if (nread == -1 && errno == EAGAIN) return; /* No more data ready. */
2048 
2049         if (nread <= 0) {
2050             /* I/O error... */
2051             serverLog(LL_DEBUG,"I/O error reading from node link: %s",
2052                 (nread == 0) ? "connection closed" : strerror(errno));
2053             handleLinkIOError(link);
2054             return;
2055         } else {
2056             /* Read data and recast the pointer to the new buffer. */
2057             link->rcvbuf = sdscatlen(link->rcvbuf,buf,nread);
2058             hdr = (clusterMsg*) link->rcvbuf;
2059             rcvbuflen += nread;
2060         }
2061 
2062         /* Total length obtained? Process this packet. */
2063         if (rcvbuflen >= 8 && rcvbuflen == ntohl(hdr->totlen)) {
2064             if (clusterProcessPacket(link)) {
2065                 sdsfree(link->rcvbuf);
2066                 link->rcvbuf = sdsempty();
2067             } else {
2068                 return; /* Link no longer valid. */
2069             }
2070         }
2071     }
2072 }
2073 
2074 /* Put stuff into the send buffer.
2075  *
2076  * It is guaranteed that this function will never have as a side effect
2077  * the link to be invalidated, so it is safe to call this function
2078  * from event handlers that will do stuff with the same link later. */
2079 void clusterSendMessage(clusterLink *link, unsigned char *msg, size_t msglen) {
2080     if (sdslen(link->sndbuf) == 0 && msglen != 0)
2081         aeCreateFileEvent(server.el,link->fd,AE_WRITABLE,
2082                     clusterWriteHandler,link);
2083 
2084     link->sndbuf = sdscatlen(link->sndbuf, msg, msglen);
2085     server.cluster->stats_bus_messages_sent++;
2086 }
2087 
2088 /* Send a message to all the nodes that are part of the cluster having
2089  * a connected link.
2090  *
2091  * It is guaranteed that this function will never have as a side effect
2092  * some node->link to be invalidated, so it is safe to call this function
2093  * from event handlers that will do stuff with node links later. */
2094 void clusterBroadcastMessage(void *buf, size_t len) {
2095     dictIterator *di;
2096     dictEntry *de;
2097 
2098     di = dictGetSafeIterator(server.cluster->nodes);
2099     while((de = dictNext(di)) != NULL) {
2100         clusterNode *node = dictGetVal(de);
2101 
2102         if (!node->link) continue;
2103         if (node->flags & (CLUSTER_NODE_MYSELF|CLUSTER_NODE_HANDSHAKE))
2104             continue;
2105         clusterSendMessage(node->link,buf,len);
2106     }
2107     dictReleaseIterator(di);
2108 }
2109 
2110 /* Build the message header. hdr must point to a buffer at least
2111  * sizeof(clusterMsg) in bytes. */
2112 void clusterBuildMessageHdr(clusterMsg *hdr, int type) {
2113     int totlen = 0;
2114     uint64_t offset;
2115     clusterNode *master;
2116 
2117     /* If this node is a master, we send its slots bitmap and configEpoch.
2118      * If this node is a slave we send the master's information instead (the
2119      * node is flagged as slave so the receiver knows that it is NOT really
2120      * in charge for this slots. */
2121     master = (nodeIsSlave(myself) && myself->slaveof) ?
2122               myself->slaveof : myself;
2123 
2124     memset(hdr,0,sizeof(*hdr));
2125     hdr->ver = htons(CLUSTER_PROTO_VER);
2126     hdr->sig[0] = 'R';
2127     hdr->sig[1] = 'C';
2128     hdr->sig[2] = 'm';
2129     hdr->sig[3] = 'b';
2130     hdr->type = htons(type);
2131     memcpy(hdr->sender,myself->name,CLUSTER_NAMELEN);
2132 
2133     memcpy(hdr->myslots,master->slots,sizeof(hdr->myslots));
2134     memset(hdr->slaveof,0,CLUSTER_NAMELEN);
2135     if (myself->slaveof != NULL)
2136         memcpy(hdr->slaveof,myself->slaveof->name, CLUSTER_NAMELEN);
2137     hdr->port = htons(server.port);
2138     hdr->flags = htons(myself->flags);
2139     hdr->state = server.cluster->state;
2140 
2141     /* Set the currentEpoch and configEpochs. */
2142     hdr->currentEpoch = htonu64(server.cluster->currentEpoch);
2143     hdr->configEpoch = htonu64(master->configEpoch);
2144 
2145     /* Set the replication offset. */
2146     if (nodeIsSlave(myself))
2147         offset = replicationGetSlaveOffset();
2148     else
2149         offset = server.master_repl_offset;
2150     hdr->offset = htonu64(offset);
2151 
2152     /* Set the message flags. */
2153     if (nodeIsMaster(myself) && server.cluster->mf_end)
2154         hdr->mflags[0] |= CLUSTERMSG_FLAG0_PAUSED;
2155 
2156     /* Compute the message length for certain messages. For other messages
2157      * this is up to the caller. */
2158     if (type == CLUSTERMSG_TYPE_FAIL) {
2159         totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
2160         totlen += sizeof(clusterMsgDataFail);
2161     } else if (type == CLUSTERMSG_TYPE_UPDATE) {
2162         totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
2163         totlen += sizeof(clusterMsgDataUpdate);
2164     }
2165     hdr->totlen = htonl(totlen);
2166     /* For PING, PONG, and MEET, fixing the totlen field is up to the caller. */
2167 }
2168 
2169 /* Send a PING or PONG packet to the specified node, making sure to add enough
2170  * gossip informations. */
2171 void clusterSendPing(clusterLink *link, int type) {
2172     unsigned char *buf;
2173     clusterMsg *hdr;
2174     int gossipcount = 0; /* Number of gossip sections added so far. */
2175     int wanted; /* Number of gossip sections we want to append if possible. */
2176     int totlen; /* Total packet length. */
2177     /* freshnodes is the max number of nodes we can hope to append at all:
2178      * nodes available minus two (ourself and the node we are sending the
2179      * message to). However practically there may be less valid nodes since
2180      * nodes in handshake state, disconnected, are not considered. */
2181     int freshnodes = dictSize(server.cluster->nodes)-2;
2182 
2183     /* How many gossip sections we want to add? 1/10 of the number of nodes
2184      * and anyway at least 3. Why 1/10?
2185      *
2186      * If we have N masters, with N/10 entries, and we consider that in
2187      * node_timeout we exchange with each other node at least 4 packets
2188      * (we ping in the worst case in node_timeout/2 time, and we also
2189      * receive two pings from the host), we have a total of 8 packets
2190      * in the node_timeout*2 falure reports validity time. So we have
2191      * that, for a single PFAIL node, we can expect to receive the following
2192      * number of failure reports (in the specified window of time):
2193      *
2194      * PROB * GOSSIP_ENTRIES_PER_PACKET * TOTAL_PACKETS:
2195      *
2196      * PROB = probability of being featured in a single gossip entry,
2197      *        which is 1 / NUM_OF_NODES.
2198      * ENTRIES = 10.
2199      * TOTAL_PACKETS = 2 * 4 * NUM_OF_MASTERS.
2200      *
2201      * If we assume we have just masters (so num of nodes and num of masters
2202      * is the same), with 1/10 we always get over the majority, and specifically
2203      * 80% of the number of nodes, to account for many masters failing at the
2204      * same time.
2205      *
2206      * Since we have non-voting slaves that lower the probability of an entry
2207      * to feature our node, we set the number of entires per packet as
2208      * 10% of the total nodes we have. */
2209     wanted = floor(dictSize(server.cluster->nodes)/10);
2210     if (wanted < 3) wanted = 3;
2211     if (wanted > freshnodes) wanted = freshnodes;
2212 
2213     /* Compute the maxium totlen to allocate our buffer. We'll fix the totlen
2214      * later according to the number of gossip sections we really were able
2215      * to put inside the packet. */
2216     totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
2217     totlen += (sizeof(clusterMsgDataGossip)*wanted);
2218     /* Note: clusterBuildMessageHdr() expects the buffer to be always at least
2219      * sizeof(clusterMsg) or more. */
2220     if (totlen < (int)sizeof(clusterMsg)) totlen = sizeof(clusterMsg);
2221     buf = zcalloc(totlen);
2222     hdr = (clusterMsg*) buf;
2223 
2224     /* Populate the header. */
2225     if (link->node && type == CLUSTERMSG_TYPE_PING)
2226         link->node->ping_sent = mstime();
2227     clusterBuildMessageHdr(hdr,type);
2228 
2229     /* Populate the gossip fields */
2230     int maxiterations = wanted*3;
2231     while(freshnodes > 0 && gossipcount < wanted && maxiterations--) {
2232         dictEntry *de = dictGetRandomKey(server.cluster->nodes);
2233         clusterNode *this = dictGetVal(de);
2234         clusterMsgDataGossip *gossip;
2235         int j;
2236 
2237         /* Don't include this node: the whole packet header is about us
2238          * already, so we just gossip about other nodes. */
2239         if (this == myself) continue;
2240 
2241         /* Give a bias to FAIL/PFAIL nodes. */
2242         if (maxiterations > wanted*2 &&
2243             !(this->flags & (CLUSTER_NODE_PFAIL|CLUSTER_NODE_FAIL)))
2244             continue;
2245 
2246         /* In the gossip section don't include:
2247          * 1) Nodes in HANDSHAKE state.
2248          * 3) Nodes with the NOADDR flag set.
2249          * 4) Disconnected nodes if they don't have configured slots.
2250          */
2251         if (this->flags & (CLUSTER_NODE_HANDSHAKE|CLUSTER_NODE_NOADDR) ||
2252             (this->link == NULL && this->numslots == 0))
2253         {
2254             freshnodes--; /* Tecnically not correct, but saves CPU. */
2255             continue;
2256         }
2257 
2258         /* Check if we already added this node */
2259         for (j = 0; j < gossipcount; j++) {
2260             if (memcmp(hdr->data.ping.gossip[j].nodename,this->name,
2261                     CLUSTER_NAMELEN) == 0) break;
2262         }
2263         if (j != gossipcount) continue;
2264 
2265         /* Add it */
2266         freshnodes--;
2267         gossip = &(hdr->data.ping.gossip[gossipcount]);
2268         memcpy(gossip->nodename,this->name,CLUSTER_NAMELEN);
2269         gossip->ping_sent = htonl(this->ping_sent);
2270         gossip->pong_received = htonl(this->pong_received);
2271         memcpy(gossip->ip,this->ip,sizeof(this->ip));
2272         gossip->port = htons(this->port);
2273         gossip->flags = htons(this->flags);
2274         gossip->notused1 = 0;
2275         gossip->notused2 = 0;
2276         gossipcount++;
2277     }
2278 
2279     /* Ready to send... fix the totlen fiend and queue the message in the
2280      * output buffer. */
2281     totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
2282     totlen += (sizeof(clusterMsgDataGossip)*gossipcount);
2283     hdr->count = htons(gossipcount);
2284     hdr->totlen = htonl(totlen);
2285     clusterSendMessage(link,buf,totlen);
2286     zfree(buf);
2287 }
2288 
2289 /* Send a PONG packet to every connected node that's not in handshake state
2290  * and for which we have a valid link.
2291  *
2292  * In Redis Cluster pongs are not used just for failure detection, but also
2293  * to carry important configuration information. So broadcasting a pong is
2294  * useful when something changes in the configuration and we want to make
2295  * the cluster aware ASAP (for instance after a slave promotion).
2296  *
2297  * The 'target' argument specifies the receiving instances using the
2298  * defines below:
2299  *
2300  * CLUSTER_BROADCAST_ALL -> All known instances.
2301  * CLUSTER_BROADCAST_LOCAL_SLAVES -> All slaves in my master-slaves ring.
2302  */
2303 #define CLUSTER_BROADCAST_ALL 0
2304 #define CLUSTER_BROADCAST_LOCAL_SLAVES 1
2305 void clusterBroadcastPong(int target) {
2306     dictIterator *di;
2307     dictEntry *de;
2308 
2309     di = dictGetSafeIterator(server.cluster->nodes);
2310     while((de = dictNext(di)) != NULL) {
2311         clusterNode *node = dictGetVal(de);
2312 
2313         if (!node->link) continue;
2314         if (node == myself || nodeInHandshake(node)) continue;
2315         if (target == CLUSTER_BROADCAST_LOCAL_SLAVES) {
2316             int local_slave =
2317                 nodeIsSlave(node) && node->slaveof &&
2318                 (node->slaveof == myself || node->slaveof == myself->slaveof);
2319             if (!local_slave) continue;
2320         }
2321         clusterSendPing(node->link,CLUSTERMSG_TYPE_PONG);
2322     }
2323     dictReleaseIterator(di);
2324 }
2325 
2326 /* Send a PUBLISH message.
2327  *
2328  * If link is NULL, then the message is broadcasted to the whole cluster. */
2329 void clusterSendPublish(clusterLink *link, robj *channel, robj *message) {
2330     unsigned char buf[sizeof(clusterMsg)], *payload;
2331     clusterMsg *hdr = (clusterMsg*) buf;
2332     uint32_t totlen;
2333     uint32_t channel_len, message_len;
2334 
2335     channel = getDecodedObject(channel);
2336     message = getDecodedObject(message);
2337     channel_len = sdslen(channel->ptr);
2338     message_len = sdslen(message->ptr);
2339 
2340     clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_PUBLISH);
2341     totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
2342     totlen += sizeof(clusterMsgDataPublish) - 8 + channel_len + message_len;
2343 
2344     hdr->data.publish.msg.channel_len = htonl(channel_len);
2345     hdr->data.publish.msg.message_len = htonl(message_len);
2346     hdr->totlen = htonl(totlen);
2347 
2348     /* Try to use the local buffer if possible */
2349     if (totlen < sizeof(buf)) {
2350         payload = buf;
2351     } else {
2352         payload = zmalloc(totlen);
2353         memcpy(payload,hdr,sizeof(*hdr));
2354         hdr = (clusterMsg*) payload;
2355     }
2356     memcpy(hdr->data.publish.msg.bulk_data,channel->ptr,sdslen(channel->ptr));
2357     memcpy(hdr->data.publish.msg.bulk_data+sdslen(channel->ptr),
2358         message->ptr,sdslen(message->ptr));
2359 
2360     if (link)
2361         clusterSendMessage(link,payload,totlen);
2362     else
2363         clusterBroadcastMessage(payload,totlen);
2364 
2365     decrRefCount(channel);
2366     decrRefCount(message);
2367     if (payload != buf) zfree(payload);
2368 }
2369 
2370 /* Send a FAIL message to all the nodes we are able to contact.
2371  * The FAIL message is sent when we detect that a node is failing
2372  * (CLUSTER_NODE_PFAIL) and we also receive a gossip confirmation of this:
2373  * we switch the node state to CLUSTER_NODE_FAIL and ask all the other
2374  * nodes to do the same ASAP. */
2375 void clusterSendFail(char *nodename) {
2376     unsigned char buf[sizeof(clusterMsg)];
2377     clusterMsg *hdr = (clusterMsg*) buf;
2378 
2379     clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_FAIL);
2380     memcpy(hdr->data.fail.about.nodename,nodename,CLUSTER_NAMELEN);
2381     clusterBroadcastMessage(buf,ntohl(hdr->totlen));
2382 }
2383 
2384 /* Send an UPDATE message to the specified link carrying the specified 'node'
2385  * slots configuration. The node name, slots bitmap, and configEpoch info
2386  * are included. */
2387 void clusterSendUpdate(clusterLink *link, clusterNode *node) {
2388     unsigned char buf[sizeof(clusterMsg)];
2389     clusterMsg *hdr = (clusterMsg*) buf;
2390 
2391     if (link == NULL) return;
2392     clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_UPDATE);
2393     memcpy(hdr->data.update.nodecfg.nodename,node->name,CLUSTER_NAMELEN);
2394     hdr->data.update.nodecfg.configEpoch = htonu64(node->configEpoch);
2395     memcpy(hdr->data.update.nodecfg.slots,node->slots,sizeof(node->slots));
2396     clusterSendMessage(link,buf,ntohl(hdr->totlen));
2397 }
2398 
2399 /* -----------------------------------------------------------------------------
2400  * CLUSTER Pub/Sub support
2401  *
2402  * For now we do very little, just propagating PUBLISH messages across the whole
2403  * cluster. In the future we'll try to get smarter and avoiding propagating those
2404  * messages to hosts without receives for a given channel.
2405  * -------------------------------------------------------------------------- */
2406 void clusterPropagatePublish(robj *channel, robj *message) {
2407     clusterSendPublish(NULL, channel, message);
2408 }
2409 
2410 /* -----------------------------------------------------------------------------
2411  * SLAVE node specific functions
2412  * -------------------------------------------------------------------------- */
2413 
2414 /* This function sends a FAILOVE_AUTH_REQUEST message to every node in order to
2415  * see if there is the quorum for this slave instance to failover its failing
2416  * master.
2417  *
2418  * Note that we send the failover request to everybody, master and slave nodes,
2419  * but only the masters are supposed to reply to our query. */
2420 void clusterRequestFailoverAuth(void) {
2421     unsigned char buf[sizeof(clusterMsg)];
2422     clusterMsg *hdr = (clusterMsg*) buf;
2423     uint32_t totlen;
2424 
2425     clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_FAILOVER_AUTH_REQUEST);
2426     /* If this is a manual failover, set the CLUSTERMSG_FLAG0_FORCEACK bit
2427      * in the header to communicate the nodes receiving the message that
2428      * they should authorized the failover even if the master is working. */
2429     if (server.cluster->mf_end) hdr->mflags[0] |= CLUSTERMSG_FLAG0_FORCEACK;
2430     totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
2431     hdr->totlen = htonl(totlen);
2432     clusterBroadcastMessage(buf,totlen);
2433 }
2434 
2435 /* Send a FAILOVER_AUTH_ACK message to the specified node. */
2436 void clusterSendFailoverAuth(clusterNode *node) {
2437     unsigned char buf[sizeof(clusterMsg)];
2438     clusterMsg *hdr = (clusterMsg*) buf;
2439     uint32_t totlen;
2440 
2441     if (!node->link) return;
2442     clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_FAILOVER_AUTH_ACK);
2443     totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
2444     hdr->totlen = htonl(totlen);
2445     clusterSendMessage(node->link,buf,totlen);
2446 }
2447 
2448 /* Send a MFSTART message to the specified node. */
2449 void clusterSendMFStart(clusterNode *node) {
2450     unsigned char buf[sizeof(clusterMsg)];
2451     clusterMsg *hdr = (clusterMsg*) buf;
2452     uint32_t totlen;
2453 
2454     if (!node->link) return;
2455     clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_MFSTART);
2456     totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
2457     hdr->totlen = htonl(totlen);
2458     clusterSendMessage(node->link,buf,totlen);
2459 }
2460 
2461 /* Vote for the node asking for our vote if there are the conditions. */
2462 void clusterSendFailoverAuthIfNeeded(clusterNode *node, clusterMsg *request) {
2463     clusterNode *master = node->slaveof;
2464     uint64_t requestCurrentEpoch = ntohu64(request->currentEpoch);
2465     uint64_t requestConfigEpoch = ntohu64(request->configEpoch);
2466     unsigned char *claimed_slots = request->myslots;
2467     int force_ack = request->mflags[0] & CLUSTERMSG_FLAG0_FORCEACK;
2468     int j;
2469 
2470     /* IF we are not a master serving at least 1 slot, we don't have the
2471      * right to vote, as the cluster size in Redis Cluster is the number
2472      * of masters serving at least one slot, and quorum is the cluster
2473      * size + 1 */
2474     if (nodeIsSlave(myself) || myself->numslots == 0) return;
2475 
2476     /* Request epoch must be >= our currentEpoch.
2477      * Note that it is impossible for it to actually be greater since
2478      * our currentEpoch was updated as a side effect of receiving this
2479      * request, if the request epoch was greater. */
2480     if (requestCurrentEpoch < server.cluster->currentEpoch) {
2481         serverLog(LL_WARNING,
2482             "Failover auth denied to %.40s: reqEpoch (%llu) < curEpoch(%llu)",
2483             node->name,
2484             (unsigned long long) requestCurrentEpoch,
2485             (unsigned long long) server.cluster->currentEpoch);
2486         return;
2487     }
2488 
2489     /* I already voted for this epoch? Return ASAP. */
2490     if (server.cluster->lastVoteEpoch == server.cluster->currentEpoch) {
2491         serverLog(LL_WARNING,
2492                 "Failover auth denied to %.40s: already voted for epoch %llu",
2493                 node->name,
2494                 (unsigned long long) server.cluster->currentEpoch);
2495         return;
2496     }
2497 
2498     /* Node must be a slave and its master down.
2499      * The master can be non failing if the request is flagged
2500      * with CLUSTERMSG_FLAG0_FORCEACK (manual failover). */
2501     if (nodeIsMaster(node) || master == NULL ||
2502         (!nodeFailed(master) && !force_ack))
2503     {
2504         if (nodeIsMaster(node)) {
2505             serverLog(LL_WARNING,
2506                     "Failover auth denied to %.40s: it is a master node",
2507                     node->name);
2508         } else if (master == NULL) {
2509             serverLog(LL_WARNING,
2510                     "Failover auth denied to %.40s: I don't know its master",
2511                     node->name);
2512         } else if (!nodeFailed(master)) {
2513             serverLog(LL_WARNING,
2514                     "Failover auth denied to %.40s: its master is up",
2515                     node->name);
2516         }
2517         return;
2518     }
2519 
2520     /* We did not voted for a slave about this master for two
2521      * times the node timeout. This is not strictly needed for correctness
2522      * of the algorithm but makes the base case more linear. */
2523     if (mstime() - node->slaveof->voted_time < server.cluster_node_timeout * 2)
2524     {
2525         serverLog(LL_WARNING,
2526                 "Failover auth denied to %.40s: "
2527                 "can't vote about this master before %lld milliseconds",
2528                 node->name,
2529                 (long long) ((server.cluster_node_timeout*2)-
2530                              (mstime() - node->slaveof->voted_time)));
2531         return;
2532     }
2533 
2534     /* The slave requesting the vote must have a configEpoch for the claimed
2535      * slots that is >= the one of the masters currently serving the same
2536      * slots in the current configuration. */
2537     for (j = 0; j < CLUSTER_SLOTS; j++) {
2538         if (bitmapTestBit(claimed_slots, j) == 0) continue;
2539         if (server.cluster->slots[j] == NULL ||
2540             server.cluster->slots[j]->configEpoch <= requestConfigEpoch)
2541         {
2542             continue;
2543         }
2544         /* If we reached this point we found a slot that in our current slots
2545          * is served by a master with a greater configEpoch than the one claimed
2546          * by the slave requesting our vote. Refuse to vote for this slave. */
2547         serverLog(LL_WARNING,
2548                 "Failover auth denied to %.40s: "
2549                 "slot %d epoch (%llu) > reqEpoch (%llu)",
2550                 node->name, j,
2551                 (unsigned long long) server.cluster->slots[j]->configEpoch,
2552                 (unsigned long long) requestConfigEpoch);
2553         return;
2554     }
2555 
2556     /* We can vote for this slave. */
2557     clusterSendFailoverAuth(node);
2558     server.cluster->lastVoteEpoch = server.cluster->currentEpoch;
2559     node->slaveof->voted_time = mstime();
2560     serverLog(LL_WARNING, "Failover auth granted to %.40s for epoch %llu",
2561         node->name, (unsigned long long) server.cluster->currentEpoch);
2562 }
2563 
2564 /* This function returns the "rank" of this instance, a slave, in the context
2565  * of its master-slaves ring. The rank of the slave is given by the number of
2566  * other slaves for the same master that have a better replication offset
2567  * compared to the local one (better means, greater, so they claim more data).
2568  *
2569  * A slave with rank 0 is the one with the greatest (most up to date)
2570  * replication offset, and so forth. Note that because how the rank is computed
2571  * multiple slaves may have the same rank, in case they have the same offset.
2572  *
2573  * The slave rank is used to add a delay to start an election in order to
2574  * get voted and replace a failing master. Slaves with better replication
2575  * offsets are more likely to win. */
2576 int clusterGetSlaveRank(void) {
2577     long long myoffset;
2578     int j, rank = 0;
2579     clusterNode *master;
2580 
2581     serverAssert(nodeIsSlave(myself));
2582     master = myself->slaveof;
2583     if (master == NULL) return 0; /* Never called by slaves without master. */
2584 
2585     myoffset = replicationGetSlaveOffset();
2586     for (j = 0; j < master->numslaves; j++)
2587         if (master->slaves[j] != myself &&
2588             master->slaves[j]->repl_offset > myoffset) rank++;
2589     return rank;
2590 }
2591 
2592 /* This function is called by clusterHandleSlaveFailover() in order to
2593  * let the slave log why it is not able to failover. Sometimes there are
2594  * not the conditions, but since the failover function is called again and
2595  * again, we can't log the same things continuously.
2596  *
2597  * This function works by logging only if a given set of conditions are
2598  * true:
2599  *
2600  * 1) The reason for which the failover can't be initiated changed.
2601  *    The reasons also include a NONE reason we reset the state to
2602  *    when the slave finds that its master is fine (no FAIL flag).
2603  * 2) Also, the log is emitted again if the master is still down and
2604  *    the reason for not failing over is still the same, but more than
2605  *    CLUSTER_CANT_FAILOVER_RELOG_PERIOD seconds elapsed.
2606  * 3) Finally, the function only logs if the slave is down for more than
2607  *    five seconds + NODE_TIMEOUT. This way nothing is logged when a
2608  *    failover starts in a reasonable time.
2609  *
2610  * The function is called with the reason why the slave can't failover
2611  * which is one of the integer macros CLUSTER_CANT_FAILOVER_*.
2612  *
2613  * The function is guaranteed to be called only if 'myself' is a slave. */
2614 void clusterLogCantFailover(int reason) {
2615     char *msg;
2616     static time_t lastlog_time = 0;
2617     mstime_t nolog_fail_time = server.cluster_node_timeout + 5000;
2618 
2619     /* Don't log if we have the same reason for some time. */
2620     if (reason == server.cluster->cant_failover_reason &&
2621         time(NULL)-lastlog_time < CLUSTER_CANT_FAILOVER_RELOG_PERIOD)
2622         return;
2623 
2624     server.cluster->cant_failover_reason = reason;
2625 
2626     /* We also don't emit any log if the master failed no long ago, the
2627      * goal of this function is to log slaves in a stalled condition for
2628      * a long time. */
2629     if (myself->slaveof &&
2630         nodeFailed(myself->slaveof) &&
2631         (mstime() - myself->slaveof->fail_time) < nolog_fail_time) return;
2632 
2633     switch(reason) {
2634     case CLUSTER_CANT_FAILOVER_DATA_AGE:
2635         msg = "Disconnected from master for longer than allowed. "
2636               "Please check the 'cluster-slave-validity-factor' configuration "
2637               "option.";
2638         break;
2639     case CLUSTER_CANT_FAILOVER_WAITING_DELAY:
2640         msg = "Waiting the delay before I can start a new failover.";
2641         break;
2642     case CLUSTER_CANT_FAILOVER_EXPIRED:
2643         msg = "Failover attempt expired.";
2644         break;
2645     case CLUSTER_CANT_FAILOVER_WAITING_VOTES:
2646         msg = "Waiting for votes, but majority still not reached.";
2647         break;
2648     default:
2649         msg = "Unknown reason code.";
2650         break;
2651     }
2652     lastlog_time = time(NULL);
2653     serverLog(LL_WARNING,"Currently unable to failover: %s", msg);
2654 }
2655 
2656 /* This function implements the final part of automatic and manual failovers,
2657  * where the slave grabs its master's hash slots, and propagates the new
2658  * configuration.
2659  *
2660  * Note that it's up to the caller to be sure that the node got a new
2661  * configuration epoch already. */
2662 void clusterFailoverReplaceYourMaster(void) {
2663     int j;
2664     clusterNode *oldmaster = myself->slaveof;
2665 
2666     if (nodeIsMaster(myself) || oldmaster == NULL) return;
2667 
2668     /* 1) Turn this node into a master. */
2669     clusterSetNodeAsMaster(myself);
2670     replicationUnsetMaster();
2671 
2672     /* 2) Claim all the slots assigned to our master. */
2673     for (j = 0; j < CLUSTER_SLOTS; j++) {
2674         if (clusterNodeGetSlotBit(oldmaster,j)) {
2675             clusterDelSlot(j);
2676             clusterAddSlot(myself,j);
2677         }
2678     }
2679 
2680     /* 3) Update state and save config. */
2681     clusterUpdateState();
2682     clusterSaveConfigOrDie(1);
2683 
2684     /* 4) Pong all the other nodes so that they can update the state
2685      *    accordingly and detect that we switched to master role. */
2686     clusterBroadcastPong(CLUSTER_BROADCAST_ALL);
2687 
2688     /* 5) If there was a manual failover in progress, clear the state. */
2689     resetManualFailover();
2690 }
2691 
2692 /* This function is called if we are a slave node and our master serving
2693  * a non-zero amount of hash slots is in FAIL state.
2694  *
2695  * The gaol of this function is:
2696  * 1) To check if we are able to perform a failover, is our data updated?
2697  * 2) Try to get elected by masters.
2698  * 3) Perform the failover informing all the other nodes.
2699  */
2700 void clusterHandleSlaveFailover(void) {
2701     mstime_t data_age;
2702     mstime_t auth_age = mstime() - server.cluster->failover_auth_time;
2703     int needed_quorum = (server.cluster->size / 2) + 1;
2704     int manual_failover = server.cluster->mf_end != 0 &&
2705                           server.cluster->mf_can_start;
2706     mstime_t auth_timeout, auth_retry_time;
2707 
2708     server.cluster->todo_before_sleep &= ~CLUSTER_TODO_HANDLE_FAILOVER;
2709 
2710     /* Compute the failover timeout (the max time we have to send votes
2711      * and wait for replies), and the failover retry time (the time to wait
2712      * before trying to get voted again).
2713      *
2714      * Timeout is MIN(NODE_TIMEOUT*2,2000) milliseconds.
2715      * Retry is two times the Timeout.
2716      */
2717     auth_timeout = server.cluster_node_timeout*2;
2718     if (auth_timeout < 2000) auth_timeout = 2000;
2719     auth_retry_time = auth_timeout*2;
2720 
2721     /* Pre conditions to run the function, that must be met both in case
2722      * of an automatic or manual failover:
2723      * 1) We are a slave.
2724      * 2) Our master is flagged as FAIL, or this is a manual failover.
2725      * 3) It is serving slots. */
2726     if (nodeIsMaster(myself) ||
2727         myself->slaveof == NULL ||
2728         (!nodeFailed(myself->slaveof) && !manual_failover) ||
2729         myself->slaveof->numslots == 0)
2730     {
2731         /* There are no reasons to failover, so we set the reason why we
2732          * are returning without failing over to NONE. */
2733         server.cluster->cant_failover_reason = CLUSTER_CANT_FAILOVER_NONE;
2734         return;
2735     }
2736 
2737     /* Set data_age to the number of seconds we are disconnected from
2738      * the master. */
2739     if (server.repl_state == REPL_STATE_CONNECTED) {
2740         data_age = (mstime_t)(server.unixtime - server.master->lastinteraction)
2741                    * 1000;
2742     } else {
2743         data_age = (mstime_t)(server.unixtime - server.repl_down_since) * 1000;
2744     }
2745 
2746     /* Remove the node timeout from the data age as it is fine that we are
2747      * disconnected from our master at least for the time it was down to be
2748      * flagged as FAIL, that's the baseline. */
2749     if (data_age > server.cluster_node_timeout)
2750         data_age -= server.cluster_node_timeout;
2751 
2752     /* Check if our data is recent enough according to the slave validity
2753      * factor configured by the user.
2754      *
2755      * Check bypassed for manual failovers. */
2756     if (server.cluster_slave_validity_factor &&
2757         data_age >
2758         (((mstime_t)server.repl_ping_slave_period * 1000) +
2759          (server.cluster_node_timeout * server.cluster_slave_validity_factor)))
2760     {
2761         if (!manual_failover) {
2762             clusterLogCantFailover(CLUSTER_CANT_FAILOVER_DATA_AGE);
2763             return;
2764         }
2765     }
2766 
2767     /* If the previous failover attempt timedout and the retry time has
2768      * elapsed, we can setup a new one. */
2769     if (auth_age > auth_retry_time) {
2770         server.cluster->failover_auth_time = mstime() +
2771             500 + /* Fixed delay of 500 milliseconds, let FAIL msg propagate. */
2772             random() % 500; /* Random delay between 0 and 500 milliseconds. */
2773         server.cluster->failover_auth_count = 0;
2774         server.cluster->failover_auth_sent = 0;
2775         server.cluster->failover_auth_rank = clusterGetSlaveRank();
2776         /* We add another delay that is proportional to the slave rank.
2777          * Specifically 1 second * rank. This way slaves that have a probably
2778          * less updated replication offset, are penalized. */
2779         server.cluster->failover_auth_time +=
2780             server.cluster->failover_auth_rank * 1000;
2781         /* However if this is a manual failover, no delay is needed. */
2782         if (server.cluster->mf_end) {
2783             server.cluster->failover_auth_time = mstime();
2784             server.cluster->failover_auth_rank = 0;
2785         }
2786         serverLog(LL_WARNING,
2787             "Start of election delayed for %lld milliseconds "
2788             "(rank #%d, offset %lld).",
2789             server.cluster->failover_auth_time - mstime(),
2790             server.cluster->failover_auth_rank,
2791             replicationGetSlaveOffset());
2792         /* Now that we have a scheduled election, broadcast our offset
2793          * to all the other slaves so that they'll updated their offsets
2794          * if our offset is better. */
2795         clusterBroadcastPong(CLUSTER_BROADCAST_LOCAL_SLAVES);
2796         return;
2797     }
2798 
2799     /* It is possible that we received more updated offsets from other
2800      * slaves for the same master since we computed our election delay.
2801      * Update the delay if our rank changed.
2802      *
2803      * Not performed if this is a manual failover. */
2804     if (server.cluster->failover_auth_sent == 0 &&
2805         server.cluster->mf_end == 0)
2806     {
2807         int newrank = clusterGetSlaveRank();
2808         if (newrank > server.cluster->failover_auth_rank) {
2809             long long added_delay =
2810                 (newrank - server.cluster->failover_auth_rank) * 1000;
2811             server.cluster->failover_auth_time += added_delay;
2812             server.cluster->failover_auth_rank = newrank;
2813             serverLog(LL_WARNING,
2814                 "Slave rank updated to #%d, added %lld milliseconds of delay.",
2815                 newrank, added_delay);
2816         }
2817     }
2818 
2819     /* Return ASAP if we can't still start the election. */
2820     if (mstime() < server.cluster->failover_auth_time) {
2821         clusterLogCantFailover(CLUSTER_CANT_FAILOVER_WAITING_DELAY);
2822         return;
2823     }
2824 
2825     /* Return ASAP if the election is too old to be valid. */
2826     if (auth_age > auth_timeout) {
2827         clusterLogCantFailover(CLUSTER_CANT_FAILOVER_EXPIRED);
2828         return;
2829     }
2830 
2831     /* Ask for votes if needed. */
2832     if (server.cluster->failover_auth_sent == 0) {
2833         server.cluster->currentEpoch++;
2834         server.cluster->failover_auth_epoch = server.cluster->currentEpoch;
2835         serverLog(LL_WARNING,"Starting a failover election for epoch %llu.",
2836             (unsigned long long) server.cluster->currentEpoch);
2837         clusterRequestFailoverAuth();
2838         server.cluster->failover_auth_sent = 1;
2839         clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
2840                              CLUSTER_TODO_UPDATE_STATE|
2841                              CLUSTER_TODO_FSYNC_CONFIG);
2842         return; /* Wait for replies. */
2843     }
2844 
2845     /* Check if we reached the quorum. */
2846     if (server.cluster->failover_auth_count >= needed_quorum) {
2847         /* We have the quorum, we can finally failover the master. */
2848 
2849         serverLog(LL_WARNING,
2850             "Failover election won: I'm the new master.");
2851 
2852         /* Update my configEpoch to the epoch of the election. */
2853         if (myself->configEpoch < server.cluster->failover_auth_epoch) {
2854             myself->configEpoch = server.cluster->failover_auth_epoch;
2855             serverLog(LL_WARNING,
2856                 "configEpoch set to %llu after successful failover",
2857                 (unsigned long long) myself->configEpoch);
2858         }
2859 
2860         /* Take responsability for the cluster slots. */
2861         clusterFailoverReplaceYourMaster();
2862     } else {
2863         clusterLogCantFailover(CLUSTER_CANT_FAILOVER_WAITING_VOTES);
2864     }
2865 }
2866 
2867 /* -----------------------------------------------------------------------------
2868  * CLUSTER slave migration
2869  *
2870  * Slave migration is the process that allows a slave of a master that is
2871  * already covered by at least another slave, to "migrate" to a master that
2872  * is orpaned, that is, left with no working slaves.
2873  * ------------------------------------------------------------------------- */
2874 
2875 /* This function is responsible to decide if this replica should be migrated
2876  * to a different (orphaned) master. It is called by the clusterCron() function
2877  * only if:
2878  *
2879  * 1) We are a slave node.
2880  * 2) It was detected that there is at least one orphaned master in
2881  *    the cluster.
2882  * 3) We are a slave of one of the masters with the greatest number of
2883  *    slaves.
2884  *
2885  * This checks are performed by the caller since it requires to iterate
2886  * the nodes anyway, so we spend time into clusterHandleSlaveMigration()
2887  * if definitely needed.
2888  *
2889  * The fuction is called with a pre-computed max_slaves, that is the max
2890  * number of working (not in FAIL state) slaves for a single master.
2891  *
2892  * Additional conditions for migration are examined inside the function.
2893  */
2894 void clusterHandleSlaveMigration(int max_slaves) {
2895     int j, okslaves = 0;
2896     clusterNode *mymaster = myself->slaveof, *target = NULL, *candidate = NULL;
2897     dictIterator *di;
2898     dictEntry *de;
2899 
2900     /* Step 1: Don't migrate if the cluster state is not ok. */
2901     if (server.cluster->state != CLUSTER_OK) return;
2902 
2903     /* Step 2: Don't migrate if my master will not be left with at least
2904      *         'migration-barrier' slaves after my migration. */
2905     if (mymaster == NULL) return;
2906     for (j = 0; j < mymaster->numslaves; j++)
2907         if (!nodeFailed(mymaster->slaves[j]) &&
2908             !nodeTimedOut(mymaster->slaves[j])) okslaves++;
2909     if (okslaves <= server.cluster_migration_barrier) return;
2910 
2911     /* Step 3: Idenitfy a candidate for migration, and check if among the
2912      * masters with the greatest number of ok slaves, I'm the one with the
2913      * smaller node ID.
2914      *
2915      * Note that this means that eventually a replica migration will occurr
2916      * since slaves that are reachable again always have their FAIL flag
2917      * cleared. At the same time this does not mean that there are no
2918      * race conditions possible (two slaves migrating at the same time), but
2919      * this is extremely unlikely to happen, and harmless. */
2920     candidate = myself;
2921     di = dictGetSafeIterator(server.cluster->nodes);
2922     while((de = dictNext(di)) != NULL) {
2923         clusterNode *node = dictGetVal(de);
2924         int okslaves;
2925 
2926         /* Only iterate over working masters. */
2927         if (nodeIsSlave(node) || nodeFailed(node)) continue;
2928         /* We want to migrate only if this master used to have slaves or
2929          * if failed over a master that had slaves. This way we only migrate
2930          * to instances that were supposed to have replicas. */
2931         if (!(node->flags & CLUSTER_NODE_MIGRATE_TO)) continue;
2932         okslaves = clusterCountNonFailingSlaves(node);
2933 
2934         if (okslaves == 0 && target == NULL && node->numslots > 0)
2935             target = node;
2936 
2937         if (okslaves == max_slaves) {
2938             for (j = 0; j < node->numslaves; j++) {
2939                 if (memcmp(node->slaves[j]->name,
2940                            candidate->name,
2941                            CLUSTER_NAMELEN) < 0)
2942                 {
2943                     candidate = node->slaves[j];
2944                 }
2945             }
2946         }
2947     }
2948     dictReleaseIterator(di);
2949 
2950     /* Step 4: perform the migration if there is a target, and if I'm the
2951      * candidate. */
2952     if (target && candidate == myself) {
2953         serverLog(LL_WARNING,"Migrating to orphaned master %.40s",
2954             target->name);
2955         clusterSetMaster(target);
2956     }
2957 }
2958 
2959 /* -----------------------------------------------------------------------------
2960  * CLUSTER manual failover
2961  *
2962  * This are the important steps performed by slaves during a manual failover:
2963  * 1) User send CLUSTER FAILOVER command. The failover state is initialized
2964  *    setting mf_end to the millisecond unix time at which we'll abort the
2965  *    attempt.
2966  * 2) Slave sends a MFSTART message to the master requesting to pause clients
2967  *    for two times the manual failover timeout CLUSTER_MF_TIMEOUT.
2968  *    When master is paused for manual failover, it also starts to flag
2969  *    packets with CLUSTERMSG_FLAG0_PAUSED.
2970  * 3) Slave waits for master to send its replication offset flagged as PAUSED.
2971  * 4) If slave received the offset from the master, and its offset matches,
2972  *    mf_can_start is set to 1, and clusterHandleSlaveFailover() will perform
2973  *    the failover as usually, with the difference that the vote request
2974  *    will be modified to force masters to vote for a slave that has a
2975  *    working master.
2976  *
2977  * From the point of view of the master things are simpler: when a
2978  * PAUSE_CLIENTS packet is received the master sets mf_end as well and
2979  * the sender in mf_slave. During the time limit for the manual failover
2980  * the master will just send PINGs more often to this slave, flagged with
2981  * the PAUSED flag, so that the slave will set mf_master_offset when receiving
2982  * a packet from the master with this flag set.
2983  *
2984  * The gaol of the manual failover is to perform a fast failover without
2985  * data loss due to the asynchronous master-slave replication.
2986  * -------------------------------------------------------------------------- */
2987 
2988 /* Reset the manual failover state. This works for both masters and slavesa
2989  * as all the state about manual failover is cleared.
2990  *
2991  * The function can be used both to initialize the manual failover state at
2992  * startup or to abort a manual failover in progress. */
2993 void resetManualFailover(void) {
2994     if (server.cluster->mf_end && clientsArePaused()) {
2995         server.clients_pause_end_time = 0;
2996         clientsArePaused(); /* Just use the side effect of the function. */
2997     }
2998     server.cluster->mf_end = 0; /* No manual failover in progress. */
2999     server.cluster->mf_can_start = 0;
3000     server.cluster->mf_slave = NULL;
3001     server.cluster->mf_master_offset = 0;
3002 }
3003 
3004 /* If a manual failover timed out, abort it. */
3005 void manualFailoverCheckTimeout(void) {
3006     if (server.cluster->mf_end && server.cluster->mf_end < mstime()) {
3007         serverLog(LL_WARNING,"Manual failover timed out.");
3008         resetManualFailover();
3009     }
3010 }
3011 
3012 /* This function is called from the cluster cron function in order to go
3013  * forward with a manual failover state machine. */
3014 void clusterHandleManualFailover(void) {
3015     /* Return ASAP if no manual failover is in progress. */
3016     if (server.cluster->mf_end == 0) return;
3017 
3018     /* If mf_can_start is non-zero, the failover was already triggered so the
3019      * next steps are performed by clusterHandleSlaveFailover(). */
3020     if (server.cluster->mf_can_start) return;
3021 
3022     if (server.cluster->mf_master_offset == 0) return; /* Wait for offset... */
3023 
3024     if (server.cluster->mf_master_offset == replicationGetSlaveOffset()) {
3025         /* Our replication offset matches the master replication offset
3026          * announced after clients were paused. We can start the failover. */
3027         server.cluster->mf_can_start = 1;
3028         serverLog(LL_WARNING,
3029             "All master replication stream processed, "
3030             "manual failover can start.");
3031     }
3032 }
3033 
3034 /* -----------------------------------------------------------------------------
3035  * CLUSTER cron job
3036  * -------------------------------------------------------------------------- */
3037 
3038 /* This is executed 10 times every second */
3039 void clusterCron(void) {
3040     dictIterator *di;
3041     dictEntry *de;
3042     int update_state = 0;
3043     int orphaned_masters; /* How many masters there are without ok slaves. */
3044     int max_slaves; /* Max number of ok slaves for a single master. */
3045     int this_slaves; /* Number of ok slaves for our master (if we are slave). */
3046     mstime_t min_pong = 0, now = mstime();
3047     clusterNode *min_pong_node = NULL;
3048     static unsigned long long iteration = 0;
3049     mstime_t handshake_timeout;
3050 
3051     iteration++; /* Number of times this function was called so far. */
3052 
3053     /* The handshake timeout is the time after which a handshake node that was
3054      * not turned into a normal node is removed from the nodes. Usually it is
3055      * just the NODE_TIMEOUT value, but when NODE_TIMEOUT is too small we use
3056      * the value of 1 second. */
3057     handshake_timeout = server.cluster_node_timeout;
3058     if (handshake_timeout < 1000) handshake_timeout = 1000;
3059 
3060     /* Check if we have disconnected nodes and re-establish the connection. */
3061     di = dictGetSafeIterator(server.cluster->nodes);
3062     while((de = dictNext(di)) != NULL) {
3063         clusterNode *node = dictGetVal(de);
3064 
3065         if (node->flags & (CLUSTER_NODE_MYSELF|CLUSTER_NODE_NOADDR)) continue;
3066 
3067         /* A Node in HANDSHAKE state has a limited lifespan equal to the
3068          * configured node timeout. */
3069         if (nodeInHandshake(node) && now - node->ctime > handshake_timeout) {
3070             clusterDelNode(node);
3071             continue;
3072         }
3073 
3074         if (node->link == NULL) {
3075             int fd;
3076             mstime_t old_ping_sent;
3077             clusterLink *link;
3078 
3079             fd = anetTcpNonBlockBindConnect(server.neterr, node->ip,
3080                 node->port+CLUSTER_PORT_INCR, NET_FIRST_BIND_ADDR);
3081             if (fd == -1) {
3082                 /* We got a synchronous error from connect before
3083                  * clusterSendPing() had a chance to be called.
3084                  * If node->ping_sent is zero, failure detection can't work,
3085                  * so we claim we actually sent a ping now (that will
3086                  * be really sent as soon as the link is obtained). */
3087                 if (node->ping_sent == 0) node->ping_sent = mstime();
3088                 serverLog(LL_DEBUG, "Unable to connect to "
3089                     "Cluster Node [%s]:%d -> %s", node->ip,
3090                     node->port+CLUSTER_PORT_INCR,
3091                     server.neterr);
3092                 continue;
3093             }
3094             link = createClusterLink(node);
3095             link->fd = fd;
3096             node->link = link;
3097             aeCreateFileEvent(server.el,link->fd,AE_READABLE,
3098                     clusterReadHandler,link);
3099             /* Queue a PING in the new connection ASAP: this is crucial
3100              * to avoid false positives in failure detection.
3101              *
3102              * If the node is flagged as MEET, we send a MEET message instead
3103              * of a PING one, to force the receiver to add us in its node
3104              * table. */
3105             old_ping_sent = node->ping_sent;
3106             clusterSendPing(link, node->flags & CLUSTER_NODE_MEET ?
3107                     CLUSTERMSG_TYPE_MEET : CLUSTERMSG_TYPE_PING);
3108             if (old_ping_sent) {
3109                 /* If there was an active ping before the link was
3110                  * disconnected, we want to restore the ping time, otherwise
3111                  * replaced by the clusterSendPing() call. */
3112                 node->ping_sent = old_ping_sent;
3113             }
3114             /* We can clear the flag after the first packet is sent.
3115              * If we'll never receive a PONG, we'll never send new packets
3116              * to this node. Instead after the PONG is received and we
3117              * are no longer in meet/handshake status, we want to send
3118              * normal PING packets. */
3119             node->flags &= ~CLUSTER_NODE_MEET;
3120 
3121             serverLog(LL_DEBUG,"Connecting with Node %.40s at %s:%d",
3122                     node->name, node->ip, node->port+CLUSTER_PORT_INCR);
3123         }
3124     }
3125     dictReleaseIterator(di);
3126 
3127     /* Ping some random node 1 time every 10 iterations, so that we usually ping
3128      * one random node every second. */
3129     if (!(iteration % 10)) {
3130         int j;
3131 
3132         /* Check a few random nodes and ping the one with the oldest
3133          * pong_received time. */
3134         for (j = 0; j < 5; j++) {
3135             de = dictGetRandomKey(server.cluster->nodes);
3136             clusterNode *this = dictGetVal(de);
3137 
3138             /* Don't ping nodes disconnected or with a ping currently active. */
3139             if (this->link == NULL || this->ping_sent != 0) continue;
3140             if (this->flags & (CLUSTER_NODE_MYSELF|CLUSTER_NODE_HANDSHAKE))
3141                 continue;
3142             if (min_pong_node == NULL || min_pong > this->pong_received) {
3143                 min_pong_node = this;
3144                 min_pong = this->pong_received;
3145             }
3146         }
3147         if (min_pong_node) {
3148             serverLog(LL_DEBUG,"Pinging node %.40s", min_pong_node->name);
3149             clusterSendPing(min_pong_node->link, CLUSTERMSG_TYPE_PING);
3150         }
3151     }
3152 
3153     /* Iterate nodes to check if we need to flag something as failing.
3154      * This loop is also responsible to:
3155      * 1) Check if there are orphaned masters (masters without non failing
3156      *    slaves).
3157      * 2) Count the max number of non failing slaves for a single master.
3158      * 3) Count the number of slaves for our master, if we are a slave. */
3159     orphaned_masters = 0;
3160     max_slaves = 0;
3161     this_slaves = 0;
3162     di = dictGetSafeIterator(server.cluster->nodes);
3163     while((de = dictNext(di)) != NULL) {
3164         clusterNode *node = dictGetVal(de);
3165         now = mstime(); /* Use an updated time at every iteration. */
3166         mstime_t delay;
3167 
3168         if (node->flags &
3169             (CLUSTER_NODE_MYSELF|CLUSTER_NODE_NOADDR|CLUSTER_NODE_HANDSHAKE))
3170                 continue;
3171 
3172         /* Orphaned master check, useful only if the current instance
3173          * is a slave that may migrate to another master. */
3174         if (nodeIsSlave(myself) && nodeIsMaster(node) && !nodeFailed(node)) {
3175             int okslaves = clusterCountNonFailingSlaves(node);
3176 
3177             /* A master is orphaned if it is serving a non-zero number of
3178              * slots, have no working slaves, but used to have at least one
3179              * slave, or failed over a master that used to have slaves. */
3180             if (okslaves == 0 && node->numslots > 0 &&
3181                 node->flags & CLUSTER_NODE_MIGRATE_TO)
3182             {
3183                 orphaned_masters++;
3184             }
3185             if (okslaves > max_slaves) max_slaves = okslaves;
3186             if (nodeIsSlave(myself) && myself->slaveof == node)
3187                 this_slaves = okslaves;
3188         }
3189 
3190         /* If we are waiting for the PONG more than half the cluster
3191          * timeout, reconnect the link: maybe there is a connection
3192          * issue even if the node is alive. */
3193         if (node->link && /* is connected */
3194             now - node->link->ctime >
3195             server.cluster_node_timeout && /* was not already reconnected */
3196             node->ping_sent && /* we already sent a ping */
3197             node->pong_received < node->ping_sent && /* still waiting pong */
3198             /* and we are waiting for the pong more than timeout/2 */
3199             now - node->ping_sent > server.cluster_node_timeout/2)
3200         {
3201             /* Disconnect the link, it will be reconnected automatically. */
3202             freeClusterLink(node->link);
3203         }
3204 
3205         /* If we have currently no active ping in this instance, and the
3206          * received PONG is older than half the cluster timeout, send
3207          * a new ping now, to ensure all the nodes are pinged without
3208          * a too big delay. */
3209         if (node->link &&
3210             node->ping_sent == 0 &&
3211             (now - node->pong_received) > server.cluster_node_timeout/2)
3212         {
3213             clusterSendPing(node->link, CLUSTERMSG_TYPE_PING);
3214             continue;
3215         }
3216 
3217         /* If we are a master and one of the slaves requested a manual
3218          * failover, ping it continuously. */
3219         if (server.cluster->mf_end &&
3220             nodeIsMaster(myself) &&
3221             server.cluster->mf_slave == node &&
3222             node->link)
3223         {
3224             clusterSendPing(node->link, CLUSTERMSG_TYPE_PING);
3225             continue;
3226         }
3227 
3228         /* Check only if we have an active ping for this instance. */
3229         if (node->ping_sent == 0) continue;
3230 
3231         /* Compute the delay of the PONG. Note that if we already received
3232          * the PONG, then node->ping_sent is zero, so can't reach this
3233          * code at all. */
3234         delay = now - node->ping_sent;
3235 
3236         if (delay > server.cluster_node_timeout) {
3237             /* Timeout reached. Set the node as possibly failing if it is
3238              * not already in this state. */
3239             if (!(node->flags & (CLUSTER_NODE_PFAIL|CLUSTER_NODE_FAIL))) {
3240                 serverLog(LL_DEBUG,"*** NODE %.40s possibly failing",
3241                     node->name);
3242                 node->flags |= CLUSTER_NODE_PFAIL;
3243                 update_state = 1;
3244             }
3245         }
3246     }
3247     dictReleaseIterator(di);
3248 
3249     /* If we are a slave node but the replication is still turned off,
3250      * enable it if we know the address of our master and it appears to
3251      * be up. */
3252     if (nodeIsSlave(myself) &&
3253         server.masterhost == NULL &&
3254         myself->slaveof &&
3255         nodeHasAddr(myself->slaveof))
3256     {
3257         replicationSetMaster(myself->slaveof->ip, myself->slaveof->port);
3258     }
3259 
3260     /* Abourt a manual failover if the timeout is reached. */
3261     manualFailoverCheckTimeout();
3262 
3263     if (nodeIsSlave(myself)) {
3264         clusterHandleManualFailover();
3265         clusterHandleSlaveFailover();
3266         /* If there are orphaned slaves, and we are a slave among the masters
3267          * with the max number of non-failing slaves, consider migrating to
3268          * the orphaned masters. Note that it does not make sense to try
3269          * a migration if there is no master with at least *two* working
3270          * slaves. */
3271         if (orphaned_masters && max_slaves >= 2 && this_slaves == max_slaves)
3272             clusterHandleSlaveMigration(max_slaves);
3273     }
3274 
3275     if (update_state || server.cluster->state == CLUSTER_FAIL)
3276         clusterUpdateState();
3277 }
3278 
3279 /* This function is called before the event handler returns to sleep for
3280  * events. It is useful to perform operations that must be done ASAP in
3281  * reaction to events fired but that are not safe to perform inside event
3282  * handlers, or to perform potentially expansive tasks that we need to do
3283  * a single time before replying to clients. */
3284 void clusterBeforeSleep(void) {
3285     /* Handle failover, this is needed when it is likely that there is already
3286      * the quorum from masters in order to react fast. */
3287     if (server.cluster->todo_before_sleep & CLUSTER_TODO_HANDLE_FAILOVER)
3288         clusterHandleSlaveFailover();
3289 
3290     /* Update the cluster state. */
3291     if (server.cluster->todo_before_sleep & CLUSTER_TODO_UPDATE_STATE)
3292         clusterUpdateState();
3293 
3294     /* Save the config, possibly using fsync. */
3295     if (server.cluster->todo_before_sleep & CLUSTER_TODO_SAVE_CONFIG) {
3296         int fsync = server.cluster->todo_before_sleep &
3297                     CLUSTER_TODO_FSYNC_CONFIG;
3298         clusterSaveConfigOrDie(fsync);
3299     }
3300 
3301     /* Reset our flags (not strictly needed since every single function
3302      * called for flags set should be able to clear its flag). */
3303     server.cluster->todo_before_sleep = 0;
3304 }
3305 
3306 void clusterDoBeforeSleep(int flags) {
3307     server.cluster->todo_before_sleep |= flags;
3308 }
3309 
3310 /* -----------------------------------------------------------------------------
3311  * Slots management
3312  * -------------------------------------------------------------------------- */
3313 
3314 /* Test bit 'pos' in a generic bitmap. Return 1 if the bit is set,
3315  * otherwise 0. */
3316 int bitmapTestBit(unsigned char *bitmap, int pos) {
3317     off_t byte = pos/8;
3318     int bit = pos&7;
3319     return (bitmap[byte] & (1<<bit)) != 0;
3320 }
3321 
3322 /* Set the bit at position 'pos' in a bitmap. */
3323 void bitmapSetBit(unsigned char *bitmap, int pos) {
3324     off_t byte = pos/8;
3325     int bit = pos&7;
3326     bitmap[byte] |= 1<<bit;
3327 }
3328 
3329 /* Clear the bit at position 'pos' in a bitmap. */
3330 void bitmapClearBit(unsigned char *bitmap, int pos) {
3331     off_t byte = pos/8;
3332     int bit = pos&7;
3333     bitmap[byte] &= ~(1<<bit);
3334 }
3335 
3336 /* Set the slot bit and return the old value. */
3337 int clusterNodeSetSlotBit(clusterNode *n, int slot) {
3338     int old = bitmapTestBit(n->slots,slot);
3339     bitmapSetBit(n->slots,slot);
3340     if (!old) n->numslots++;
3341     return old;
3342 }
3343 
3344 /* Clear the slot bit and return the old value. */
3345 int clusterNodeClearSlotBit(clusterNode *n, int slot) {
3346     int old = bitmapTestBit(n->slots,slot);
3347     bitmapClearBit(n->slots,slot);
3348     if (old) n->numslots--;
3349     return old;
3350 }
3351 
3352 /* Return the slot bit from the cluster node structure. */
3353 int clusterNodeGetSlotBit(clusterNode *n, int slot) {
3354     return bitmapTestBit(n->slots,slot);
3355 }
3356 
3357 /* Add the specified slot to the list of slots that node 'n' will
3358  * serve. Return C_OK if the operation ended with success.
3359  * If the slot is already assigned to another instance this is considered
3360  * an error and C_ERR is returned. */
3361 int clusterAddSlot(clusterNode *n, int slot) {
3362     if (server.cluster->slots[slot]) return C_ERR;
3363     clusterNodeSetSlotBit(n,slot);
3364     server.cluster->slots[slot] = n;
3365     return C_OK;
3366 }
3367 
3368 /* Delete the specified slot marking it as unassigned.
3369  * Returns C_OK if the slot was assigned, otherwise if the slot was
3370  * already unassigned C_ERR is returned. */
3371 int clusterDelSlot(int slot) {
3372     clusterNode *n = server.cluster->slots[slot];
3373 
3374     if (!n) return C_ERR;
3375     serverAssert(clusterNodeClearSlotBit(n,slot) == 1);
3376     server.cluster->slots[slot] = NULL;
3377     return C_OK;
3378 }
3379 
3380 /* Delete all the slots associated with the specified node.
3381  * The number of deleted slots is returned. */
3382 int clusterDelNodeSlots(clusterNode *node) {
3383     int deleted = 0, j;
3384 
3385     for (j = 0; j < CLUSTER_SLOTS; j++) {
3386         if (clusterNodeGetSlotBit(node,j)) clusterDelSlot(j);
3387         deleted++;
3388     }
3389     return deleted;
3390 }
3391 
3392 /* Clear the migrating / importing state for all the slots.
3393  * This is useful at initialization and when turning a master into slave. */
3394 void clusterCloseAllSlots(void) {
3395     memset(server.cluster->migrating_slots_to,0,
3396         sizeof(server.cluster->migrating_slots_to));
3397     memset(server.cluster->importing_slots_from,0,
3398         sizeof(server.cluster->importing_slots_from));
3399 }
3400 
3401 /* -----------------------------------------------------------------------------
3402  * Cluster state evaluation function
3403  * -------------------------------------------------------------------------- */
3404 
3405 /* The following are defines that are only used in the evaluation function
3406  * and are based on heuristics. Actaully the main point about the rejoin and
3407  * writable delay is that they should be a few orders of magnitude larger
3408  * than the network latency. */
3409 #define CLUSTER_MAX_REJOIN_DELAY 5000
3410 #define CLUSTER_MIN_REJOIN_DELAY 500
3411 #define CLUSTER_WRITABLE_DELAY 2000
3412 
3413 void clusterUpdateState(void) {
3414     int j, new_state;
3415     int reachable_masters = 0;
3416     static mstime_t among_minority_time;
3417     static mstime_t first_call_time = 0;
3418 
3419     server.cluster->todo_before_sleep &= ~CLUSTER_TODO_UPDATE_STATE;
3420 
3421     /* If this is a master node, wait some time before turning the state
3422      * into OK, since it is not a good idea to rejoin the cluster as a writable
3423      * master, after a reboot, without giving the cluster a chance to
3424      * reconfigure this node. Note that the delay is calculated starting from
3425      * the first call to this function and not since the server start, in order
3426      * to don't count the DB loading time. */
3427     if (first_call_time == 0) first_call_time = mstime();
3428     if (nodeIsMaster(myself) &&
3429         server.cluster->state == CLUSTER_FAIL &&
3430         mstime() - first_call_time < CLUSTER_WRITABLE_DELAY) return;
3431 
3432     /* Start assuming the state is OK. We'll turn it into FAIL if there
3433      * are the right conditions. */
3434     new_state = CLUSTER_OK;
3435 
3436     /* Check if all the slots are covered. */
3437     if (server.cluster_require_full_coverage) {
3438         for (j = 0; j < CLUSTER_SLOTS; j++) {
3439             if (server.cluster->slots[j] == NULL ||
3440                 server.cluster->slots[j]->flags & (CLUSTER_NODE_FAIL))
3441             {
3442                 new_state = CLUSTER_FAIL;
3443                 break;
3444             }
3445         }
3446     }
3447 
3448     /* Compute the cluster size, that is the number of master nodes
3449      * serving at least a single slot.
3450      *
3451      * At the same time count the number of reachable masters having
3452      * at least one slot. */
3453     {
3454         dictIterator *di;
3455         dictEntry *de;
3456 
3457         server.cluster->size = 0;
3458         di = dictGetSafeIterator(server.cluster->nodes);
3459         while((de = dictNext(di)) != NULL) {
3460             clusterNode *node = dictGetVal(de);
3461 
3462             if (nodeIsMaster(node) && node->numslots) {
3463                 server.cluster->size++;
3464                 if ((node->flags & (CLUSTER_NODE_FAIL|CLUSTER_NODE_PFAIL)) == 0)
3465                     reachable_masters++;
3466             }
3467         }
3468         dictReleaseIterator(di);
3469     }
3470 
3471     /* If we are in a minority partition, change the cluster state
3472      * to FAIL. */
3473     {
3474         int needed_quorum = (server.cluster->size / 2) + 1;
3475 
3476         if (reachable_masters < needed_quorum) {
3477             new_state = CLUSTER_FAIL;
3478             among_minority_time = mstime();
3479         }
3480     }
3481 
3482     /* Log a state change */
3483     if (new_state != server.cluster->state) {
3484         mstime_t rejoin_delay = server.cluster_node_timeout;
3485 
3486         /* If the instance is a master and was partitioned away with the
3487          * minority, don't let it accept queries for some time after the
3488          * partition heals, to make sure there is enough time to receive
3489          * a configuration update. */
3490         if (rejoin_delay > CLUSTER_MAX_REJOIN_DELAY)
3491             rejoin_delay = CLUSTER_MAX_REJOIN_DELAY;
3492         if (rejoin_delay < CLUSTER_MIN_REJOIN_DELAY)
3493             rejoin_delay = CLUSTER_MIN_REJOIN_DELAY;
3494 
3495         if (new_state == CLUSTER_OK &&
3496             nodeIsMaster(myself) &&
3497             mstime() - among_minority_time < rejoin_delay)
3498         {
3499             return;
3500         }
3501 
3502         /* Change the state and log the event. */
3503         serverLog(LL_WARNING,"Cluster state changed: %s",
3504             new_state == CLUSTER_OK ? "ok" : "fail");
3505         server.cluster->state = new_state;
3506     }
3507 }
3508 
3509 /* This function is called after the node startup in order to verify that data
3510  * loaded from disk is in agreement with the cluster configuration:
3511  *
3512  * 1) If we find keys about hash slots we have no responsibility for, the
3513  *    following happens:
3514  *    A) If no other node is in charge according to the current cluster
3515  *       configuration, we add these slots to our node.
3516  *    B) If according to our config other nodes are already in charge for
3517  *       this lots, we set the slots as IMPORTING from our point of view
3518  *       in order to justify we have those slots, and in order to make
3519  *       redis-trib aware of the issue, so that it can try to fix it.
3520  * 2) If we find data in a DB different than DB0 we return C_ERR to
3521  *    signal the caller it should quit the server with an error message
3522  *    or take other actions.
3523  *
3524  * The function always returns C_OK even if it will try to correct
3525  * the error described in "1". However if data is found in DB different
3526  * from DB0, C_ERR is returned.
3527  *
3528  * The function also uses the logging facility in order to warn the user
3529  * about desynchronizations between the data we have in memory and the
3530  * cluster configuration. */
3531 int verifyClusterConfigWithData(void) {
3532     int j;
3533     int update_config = 0;
3534 
3535     /* If this node is a slave, don't perform the check at all as we
3536      * completely depend on the replication stream. */
3537     if (nodeIsSlave(myself)) return C_OK;
3538 
3539     /* Make sure we only have keys in DB0. */
3540     for (j = 1; j < server.dbnum; j++) {
3541         if (dictSize(server.db[j].dict)) return C_ERR;
3542     }
3543 
3544     /* Check that all the slots we see populated memory have a corresponding
3545      * entry in the cluster table. Otherwise fix the table. */
3546     for (j = 0; j < CLUSTER_SLOTS; j++) {
3547         if (!countKeysInSlot(j)) continue; /* No keys in this slot. */
3548         /* Check if we are assigned to this slot or if we are importing it.
3549          * In both cases check the next slot as the configuration makes
3550          * sense. */
3551         if (server.cluster->slots[j] == myself ||
3552             server.cluster->importing_slots_from[j] != NULL) continue;
3553 
3554         /* If we are here data and cluster config don't agree, and we have
3555          * slot 'j' populated even if we are not importing it, nor we are
3556          * assigned to this slot. Fix this condition. */
3557 
3558         update_config++;
3559         /* Case A: slot is unassigned. Take responsibility for it. */
3560         if (server.cluster->slots[j] == NULL) {
3561             serverLog(LL_WARNING, "I have keys for unassigned slot %d. "
3562                                     "Taking responsibility for it.",j);
3563             clusterAddSlot(myself,j);
3564         } else {
3565             serverLog(LL_WARNING, "I have keys for slot %d, but the slot is "
3566                                     "assigned to another node. "
3567                                     "Setting it to importing state.",j);
3568             server.cluster->importing_slots_from[j] = server.cluster->slots[j];
3569         }
3570     }
3571     if (update_config) clusterSaveConfigOrDie(1);
3572     return C_OK;
3573 }
3574 
3575 /* -----------------------------------------------------------------------------
3576  * SLAVE nodes handling
3577  * -------------------------------------------------------------------------- */
3578 
3579 /* Set the specified node 'n' as master for this node.
3580  * If this node is currently a master, it is turned into a slave. */
3581 void clusterSetMaster(clusterNode *n) {
3582     serverAssert(n != myself);
3583     serverAssert(myself->numslots == 0);
3584 
3585     if (nodeIsMaster(myself)) {
3586         myself->flags &= ~(CLUSTER_NODE_MASTER|CLUSTER_NODE_MIGRATE_TO);
3587         myself->flags |= CLUSTER_NODE_SLAVE;
3588         clusterCloseAllSlots();
3589     } else {
3590         if (myself->slaveof)
3591             clusterNodeRemoveSlave(myself->slaveof,myself);
3592     }
3593     myself->slaveof = n;
3594     clusterNodeAddSlave(n,myself);
3595     replicationSetMaster(n->ip, n->port);
3596     resetManualFailover();
3597 }
3598 
3599 /* -----------------------------------------------------------------------------
3600  * Nodes to string representation functions.
3601  * -------------------------------------------------------------------------- */
3602 
3603 struct redisNodeFlags {
3604     uint16_t flag;
3605     char *name;
3606 };
3607 
3608 static struct redisNodeFlags redisNodeFlagsTable[] = {
3609     {CLUSTER_NODE_MYSELF,       "myself,"},
3610     {CLUSTER_NODE_MASTER,       "master,"},
3611     {CLUSTER_NODE_SLAVE,        "slave,"},
3612     {CLUSTER_NODE_PFAIL,        "fail?,"},
3613     {CLUSTER_NODE_FAIL,         "fail,"},
3614     {CLUSTER_NODE_HANDSHAKE,    "handshake,"},
3615     {CLUSTER_NODE_NOADDR,       "noaddr,"}
3616 };
3617 
3618 /* Concatenate the comma separated list of node flags to the given SDS
3619  * string 'ci'. */
3620 sds representClusterNodeFlags(sds ci, uint16_t flags) {
3621     if (flags == 0) {
3622         ci = sdscat(ci,"noflags,");
3623     } else {
3624         int i, size = sizeof(redisNodeFlagsTable)/sizeof(struct redisNodeFlags);
3625         for (i = 0; i < size; i++) {
3626             struct redisNodeFlags *nodeflag = redisNodeFlagsTable + i;
3627             if (flags & nodeflag->flag) ci = sdscat(ci, nodeflag->name);
3628         }
3629     }
3630     sdsIncrLen(ci,-1); /* Remove trailing comma. */
3631     return ci;
3632 }
3633 
3634 /* Generate a csv-alike representation of the specified cluster node.
3635  * See clusterGenNodesDescription() top comment for more information.
3636  *
3637  * The function returns the string representation as an SDS string. */
3638 sds clusterGenNodeDescription(clusterNode *node) {
3639     int j, start;
3640     sds ci;
3641 
3642     /* Node coordinates */
3643     ci = sdscatprintf(sdsempty(),"%.40s %s:%d ",
3644         node->name,
3645         node->ip,
3646         node->port);
3647 
3648     /* Flags */
3649     ci = representClusterNodeFlags(ci, node->flags);
3650 
3651     /* Slave of... or just "-" */
3652     if (node->slaveof)
3653         ci = sdscatprintf(ci," %.40s ",node->slaveof->name);
3654     else
3655         ci = sdscatlen(ci," - ",3);
3656 
3657     /* Latency from the POV of this node, config epoch, link status */
3658     ci = sdscatprintf(ci,"%lld %lld %llu %s",
3659         (long long) node->ping_sent,
3660         (long long) node->pong_received,
3661         (unsigned long long) node->configEpoch,
3662         (node->link || node->flags & CLUSTER_NODE_MYSELF) ?
3663                     "connected" : "disconnected");
3664 
3665     /* Slots served by this instance */
3666     start = -1;
3667     for (j = 0; j < CLUSTER_SLOTS; j++) {
3668         int bit;
3669 
3670         if ((bit = clusterNodeGetSlotBit(node,j)) != 0) {
3671             if (start == -1) start = j;
3672         }
3673         if (start != -1 && (!bit || j == CLUSTER_SLOTS-1)) {
3674             if (bit && j == CLUSTER_SLOTS-1) j++;
3675 
3676             if (start == j-1) {
3677                 ci = sdscatprintf(ci," %d",start);
3678             } else {
3679                 ci = sdscatprintf(ci," %d-%d",start,j-1);
3680             }
3681             start = -1;
3682         }
3683     }
3684 
3685     /* Just for MYSELF node we also dump info about slots that
3686      * we are migrating to other instances or importing from other
3687      * instances. */
3688     if (node->flags & CLUSTER_NODE_MYSELF) {
3689         for (j = 0; j < CLUSTER_SLOTS; j++) {
3690             if (server.cluster->migrating_slots_to[j]) {
3691                 ci = sdscatprintf(ci," [%d->-%.40s]",j,
3692                     server.cluster->migrating_slots_to[j]->name);
3693             } else if (server.cluster->importing_slots_from[j]) {
3694                 ci = sdscatprintf(ci," [%d-<-%.40s]",j,
3695                     server.cluster->importing_slots_from[j]->name);
3696             }
3697         }
3698     }
3699     return ci;
3700 }
3701 
3702 /* Generate a csv-alike representation of the nodes we are aware of,
3703  * including the "myself" node, and return an SDS string containing the
3704  * representation (it is up to the caller to free it).
3705  *
3706  * All the nodes matching at least one of the node flags specified in
3707  * "filter" are excluded from the output, so using zero as a filter will
3708  * include all the known nodes in the representation, including nodes in
3709  * the HANDSHAKE state.
3710  *
3711  * The representation obtained using this function is used for the output
3712  * of the CLUSTER NODES function, and as format for the cluster
3713  * configuration file (nodes.conf) for a given node. */
3714 sds clusterGenNodesDescription(int filter) {
3715     sds ci = sdsempty(), ni;
3716     dictIterator *di;
3717     dictEntry *de;
3718 
3719     di = dictGetSafeIterator(server.cluster->nodes);
3720     while((de = dictNext(di)) != NULL) {
3721         clusterNode *node = dictGetVal(de);
3722 
3723         if (node->flags & filter) continue;
3724         ni = clusterGenNodeDescription(node);
3725         ci = sdscatsds(ci,ni);
3726         sdsfree(ni);
3727         ci = sdscatlen(ci,"\n",1);
3728     }
3729     dictReleaseIterator(di);
3730     return ci;
3731 }
3732 
3733 /* -----------------------------------------------------------------------------
3734  * CLUSTER command
3735  * -------------------------------------------------------------------------- */
3736 
3737 int getSlotOrReply(client *c, robj *o) {
3738     long long slot;
3739 
3740     if (getLongLongFromObject(o,&slot) != C_OK ||
3741         slot < 0 || slot >= CLUSTER_SLOTS)
3742     {
3743         addReplyError(c,"Invalid or out of range slot");
3744         return -1;
3745     }
3746     return (int) slot;
3747 }
3748 
3749 void clusterReplyMultiBulkSlots(client *c) {
3750     /* Format: 1) 1) start slot
3751      *            2) end slot
3752      *            3) 1) master IP
3753      *               2) master port
3754      *            4) 1) replica IP
3755      *               2) replica port
3756      *           ... continued until done
3757      */
3758 
3759     int num_masters = 0;
3760     void *slot_replylen = addDeferredMultiBulkLength(c);
3761 
3762     dictEntry *de;
3763     dictIterator *di = dictGetSafeIterator(server.cluster->nodes);
3764     while((de = dictNext(di)) != NULL) {
3765         clusterNode *node = dictGetVal(de);
3766         int j = 0, start = -1;
3767 
3768         /* Skip slaves (that are iterated when producing the output of their
3769          * master) and  masters not serving any slot. */
3770         if (!nodeIsMaster(node) || node->numslots == 0) continue;
3771 
3772         for (j = 0; j < CLUSTER_SLOTS; j++) {
3773             int bit, i;
3774 
3775             if ((bit = clusterNodeGetSlotBit(node,j)) != 0) {
3776                 if (start == -1) start = j;
3777             }
3778             if (start != -1 && (!bit || j == CLUSTER_SLOTS-1)) {
3779                 int nested_elements = 3; /* slots (2) + master addr (1). */
3780                 void *nested_replylen = addDeferredMultiBulkLength(c);
3781 
3782                 if (bit && j == CLUSTER_SLOTS-1) j++;
3783 
3784                 /* If slot exists in output map, add to it's list.
3785                  * else, create a new output map for this slot */
3786                 if (start == j-1) {
3787                     addReplyLongLong(c, start); /* only one slot; low==high */
3788                     addReplyLongLong(c, start);
3789                 } else {
3790                     addReplyLongLong(c, start); /* low */
3791                     addReplyLongLong(c, j-1);   /* high */
3792                 }
3793                 start = -1;
3794 
3795                 /* First node reply position is always the master */
3796                 addReplyMultiBulkLen(c, 2);
3797                 addReplyBulkCString(c, node->ip);
3798                 addReplyLongLong(c, node->port);
3799 
3800                 /* Remaining nodes in reply are replicas for slot range */
3801                 for (i = 0; i < node->numslaves; i++) {
3802                     /* This loop is copy/pasted from clusterGenNodeDescription()
3803                      * with modifications for per-slot node aggregation */
3804                     if (nodeFailed(node->slaves[i])) continue;
3805                     addReplyMultiBulkLen(c, 2);
3806                     addReplyBulkCString(c, node->slaves[i]->ip);
3807                     addReplyLongLong(c, node->slaves[i]->port);
3808                     nested_elements++;
3809                 }
3810                 setDeferredMultiBulkLength(c, nested_replylen, nested_elements);
3811                 num_masters++;
3812             }
3813         }
3814     }
3815     dictReleaseIterator(di);
3816     setDeferredMultiBulkLength(c, slot_replylen, num_masters);
3817 }
3818 
3819 void clusterCommand(client *c) {
3820     if (server.cluster_enabled == 0) {
3821         addReplyError(c,"This instance has cluster support disabled");
3822         return;
3823     }
3824 
3825     if (!strcasecmp(c->argv[1]->ptr,"meet") && c->argc == 4) {
3826         long long port;
3827 
3828         if (getLongLongFromObject(c->argv[3], &port) != C_OK) {
3829             addReplyErrorFormat(c,"Invalid TCP port specified: %s",
3830                                 (char*)c->argv[3]->ptr);
3831             return;
3832         }
3833 
3834         if (clusterStartHandshake(c->argv[2]->ptr,port) == 0 &&
3835             errno == EINVAL)
3836         {
3837             addReplyErrorFormat(c,"Invalid node address specified: %s:%s",
3838                             (char*)c->argv[2]->ptr, (char*)c->argv[3]->ptr);
3839         } else {
3840             addReply(c,shared.ok);
3841         }
3842     } else if (!strcasecmp(c->argv[1]->ptr,"nodes") && c->argc == 2) {
3843         /* CLUSTER NODES */
3844         robj *o;
3845         sds ci = clusterGenNodesDescription(0);
3846 
3847         o = createObject(OBJ_STRING,ci);
3848         addReplyBulk(c,o);
3849         decrRefCount(o);
3850     } else if (!strcasecmp(c->argv[1]->ptr,"myid") && c->argc == 2) {
3851         /* CLUSTER MYID */
3852         addReplyBulkCBuffer(c,myself->name, CLUSTER_NAMELEN);
3853     } else if (!strcasecmp(c->argv[1]->ptr,"slots") && c->argc == 2) {
3854         /* CLUSTER SLOTS */
3855         clusterReplyMultiBulkSlots(c);
3856     } else if (!strcasecmp(c->argv[1]->ptr,"flushslots") && c->argc == 2) {
3857         /* CLUSTER FLUSHSLOTS */
3858         if (dictSize(server.db[0].dict) != 0) {
3859             addReplyError(c,"DB must be empty to perform CLUSTER FLUSHSLOTS.");
3860             return;
3861         }
3862         clusterDelNodeSlots(myself);
3863         clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
3864         addReply(c,shared.ok);
3865     } else if ((!strcasecmp(c->argv[1]->ptr,"addslots") ||
3866                !strcasecmp(c->argv[1]->ptr,"delslots")) && c->argc >= 3)
3867     {
3868         /* CLUSTER ADDSLOTS <slot> [slot] ... */
3869         /* CLUSTER DELSLOTS <slot> [slot] ... */
3870         int j, slot;
3871         unsigned char *slots = zmalloc(CLUSTER_SLOTS);
3872         int del = !strcasecmp(c->argv[1]->ptr,"delslots");
3873 
3874         memset(slots,0,CLUSTER_SLOTS);
3875         /* Check that all the arguments are parseable and that all the
3876          * slots are not already busy. */
3877         for (j = 2; j < c->argc; j++) {
3878             if ((slot = getSlotOrReply(c,c->argv[j])) == -1) {
3879                 zfree(slots);
3880                 return;
3881             }
3882             if (del && server.cluster->slots[slot] == NULL) {
3883                 addReplyErrorFormat(c,"Slot %d is already unassigned", slot);
3884                 zfree(slots);
3885                 return;
3886             } else if (!del && server.cluster->slots[slot]) {
3887                 addReplyErrorFormat(c,"Slot %d is already busy", slot);
3888                 zfree(slots);
3889                 return;
3890             }
3891             if (slots[slot]++ == 1) {
3892                 addReplyErrorFormat(c,"Slot %d specified multiple times",
3893                     (int)slot);
3894                 zfree(slots);
3895                 return;
3896             }
3897         }
3898         for (j = 0; j < CLUSTER_SLOTS; j++) {
3899             if (slots[j]) {
3900                 int retval;
3901 
3902                 /* If this slot was set as importing we can clear this
3903                  * state as now we are the real owner of the slot. */
3904                 if (server.cluster->importing_slots_from[j])
3905                     server.cluster->importing_slots_from[j] = NULL;
3906 
3907                 retval = del ? clusterDelSlot(j) :
3908                                clusterAddSlot(myself,j);
3909                 serverAssertWithInfo(c,NULL,retval == C_OK);
3910             }
3911         }
3912         zfree(slots);
3913         clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
3914         addReply(c,shared.ok);
3915     } else if (!strcasecmp(c->argv[1]->ptr,"setslot") && c->argc >= 4) {
3916         /* SETSLOT 10 MIGRATING <node ID> */
3917         /* SETSLOT 10 IMPORTING <node ID> */
3918         /* SETSLOT 10 STABLE */
3919         /* SETSLOT 10 NODE <node ID> */
3920         int slot;
3921         clusterNode *n;
3922 
3923         if ((slot = getSlotOrReply(c,c->argv[2])) == -1) return;
3924 
3925         if (!strcasecmp(c->argv[3]->ptr,"migrating") && c->argc == 5) {
3926             if (server.cluster->slots[slot] != myself) {
3927                 addReplyErrorFormat(c,"I'm not the owner of hash slot %u",slot);
3928                 return;
3929             }
3930             if ((n = clusterLookupNode(c->argv[4]->ptr)) == NULL) {
3931                 addReplyErrorFormat(c,"I don't know about node %s",
3932                     (char*)c->argv[4]->ptr);
3933                 return;
3934             }
3935             server.cluster->migrating_slots_to[slot] = n;
3936         } else if (!strcasecmp(c->argv[3]->ptr,"importing") && c->argc == 5) {
3937             if (server.cluster->slots[slot] == myself) {
3938                 addReplyErrorFormat(c,
3939                     "I'm already the owner of hash slot %u",slot);
3940                 return;
3941             }
3942             if ((n = clusterLookupNode(c->argv[4]->ptr)) == NULL) {
3943                 addReplyErrorFormat(c,"I don't know about node %s",
3944                     (char*)c->argv[3]->ptr);
3945                 return;
3946             }
3947             server.cluster->importing_slots_from[slot] = n;
3948         } else if (!strcasecmp(c->argv[3]->ptr,"stable") && c->argc == 4) {
3949             /* CLUSTER SETSLOT <SLOT> STABLE */
3950             server.cluster->importing_slots_from[slot] = NULL;
3951             server.cluster->migrating_slots_to[slot] = NULL;
3952         } else if (!strcasecmp(c->argv[3]->ptr,"node") && c->argc == 5) {
3953             /* CLUSTER SETSLOT <SLOT> NODE <NODE ID> */
3954             clusterNode *n = clusterLookupNode(c->argv[4]->ptr);
3955 
3956             if (!n) {
3957                 addReplyErrorFormat(c,"Unknown node %s",
3958                     (char*)c->argv[4]->ptr);
3959                 return;
3960             }
3961             /* If this hash slot was served by 'myself' before to switch
3962              * make sure there are no longer local keys for this hash slot. */
3963             if (server.cluster->slots[slot] == myself && n != myself) {
3964                 if (countKeysInSlot(slot) != 0) {
3965                     addReplyErrorFormat(c,
3966                         "Can't assign hashslot %d to a different node "
3967                         "while I still hold keys for this hash slot.", slot);
3968                     return;
3969                 }
3970             }
3971             /* If this slot is in migrating status but we have no keys
3972              * for it assigning the slot to another node will clear
3973              * the migratig status. */
3974             if (countKeysInSlot(slot) == 0 &&
3975                 server.cluster->migrating_slots_to[slot])
3976                 server.cluster->migrating_slots_to[slot] = NULL;
3977 
3978             /* If this node was importing this slot, assigning the slot to
3979              * itself also clears the importing status. */
3980             if (n == myself &&
3981                 server.cluster->importing_slots_from[slot])
3982             {
3983                 /* This slot was manually migrated, set this node configEpoch
3984                  * to a new epoch so that the new version can be propagated
3985                  * by the cluster.
3986                  *
3987                  * Note that if this ever results in a collision with another
3988                  * node getting the same configEpoch, for example because a
3989                  * failover happens at the same time we close the slot, the
3990                  * configEpoch collision resolution will fix it assigning
3991                  * a different epoch to each node. */
3992                 if (clusterBumpConfigEpochWithoutConsensus() == C_OK) {
3993                     serverLog(LL_WARNING,
3994                         "configEpoch updated after importing slot %d", slot);
3995                 }
3996                 server.cluster->importing_slots_from[slot] = NULL;
3997             }
3998             clusterDelSlot(slot);
3999             clusterAddSlot(n,slot);
4000         } else {
4001             addReplyError(c,
4002                 "Invalid CLUSTER SETSLOT action or number of arguments");
4003             return;
4004         }
4005         clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|CLUSTER_TODO_UPDATE_STATE);
4006         addReply(c,shared.ok);
4007     } else if (!strcasecmp(c->argv[1]->ptr,"info") && c->argc == 2) {
4008         /* CLUSTER INFO */
4009         char *statestr[] = {"ok","fail","needhelp"};
4010         int slots_assigned = 0, slots_ok = 0, slots_pfail = 0, slots_fail = 0;
4011         uint64_t myepoch;
4012         int j;
4013 
4014         for (j = 0; j < CLUSTER_SLOTS; j++) {
4015             clusterNode *n = server.cluster->slots[j];
4016 
4017             if (n == NULL) continue;
4018             slots_assigned++;
4019             if (nodeFailed(n)) {
4020                 slots_fail++;
4021             } else if (nodeTimedOut(n)) {
4022                 slots_pfail++;
4023             } else {
4024                 slots_ok++;
4025             }
4026         }
4027 
4028         myepoch = (nodeIsSlave(myself) && myself->slaveof) ?
4029                   myself->slaveof->configEpoch : myself->configEpoch;
4030 
4031         sds info = sdscatprintf(sdsempty(),
4032             "cluster_state:%s\r\n"
4033             "cluster_slots_assigned:%d\r\n"
4034             "cluster_slots_ok:%d\r\n"
4035             "cluster_slots_pfail:%d\r\n"
4036             "cluster_slots_fail:%d\r\n"
4037             "cluster_known_nodes:%lu\r\n"
4038             "cluster_size:%d\r\n"
4039             "cluster_current_epoch:%llu\r\n"
4040             "cluster_my_epoch:%llu\r\n"
4041             "cluster_stats_messages_sent:%lld\r\n"
4042             "cluster_stats_messages_received:%lld\r\n"
4043             , statestr[server.cluster->state],
4044             slots_assigned,
4045             slots_ok,
4046             slots_pfail,
4047             slots_fail,
4048             dictSize(server.cluster->nodes),
4049             server.cluster->size,
4050             (unsigned long long) server.cluster->currentEpoch,
4051             (unsigned long long) myepoch,
4052             server.cluster->stats_bus_messages_sent,
4053             server.cluster->stats_bus_messages_received
4054         );
4055         addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
4056             (unsigned long)sdslen(info)));
4057         addReplySds(c,info);
4058         addReply(c,shared.crlf);
4059     } else if (!strcasecmp(c->argv[1]->ptr,"saveconfig") && c->argc == 2) {
4060         int retval = clusterSaveConfig(1);
4061 
4062         if (retval == 0)
4063             addReply(c,shared.ok);
4064         else
4065             addReplyErrorFormat(c,"error saving the cluster node config: %s",
4066                 strerror(errno));
4067     } else if (!strcasecmp(c->argv[1]->ptr,"keyslot") && c->argc == 3) {
4068         /* CLUSTER KEYSLOT <key> */
4069         sds key = c->argv[2]->ptr;
4070 
4071         addReplyLongLong(c,keyHashSlot(key,sdslen(key)));
4072     } else if (!strcasecmp(c->argv[1]->ptr,"countkeysinslot") && c->argc == 3) {
4073         /* CLUSTER COUNTKEYSINSLOT <slot> */
4074         long long slot;
4075 
4076         if (getLongLongFromObjectOrReply(c,c->argv[2],&slot,NULL) != C_OK)
4077             return;
4078         if (slot < 0 || slot >= CLUSTER_SLOTS) {
4079             addReplyError(c,"Invalid slot");
4080             return;
4081         }
4082         addReplyLongLong(c,countKeysInSlot(slot));
4083     } else if (!strcasecmp(c->argv[1]->ptr,"getkeysinslot") && c->argc == 4) {
4084         /* CLUSTER GETKEYSINSLOT <slot> <count> */
4085         long long maxkeys, slot;
4086         unsigned int numkeys, j;
4087         robj **keys;
4088 
4089         if (getLongLongFromObjectOrReply(c,c->argv[2],&slot,NULL) != C_OK)
4090             return;
4091         if (getLongLongFromObjectOrReply(c,c->argv[3],&maxkeys,NULL)
4092             != C_OK)
4093             return;
4094         if (slot < 0 || slot >= CLUSTER_SLOTS || maxkeys < 0) {
4095             addReplyError(c,"Invalid slot or number of keys");
4096             return;
4097         }
4098 
4099         keys = zmalloc(sizeof(robj*)*maxkeys);
4100         numkeys = getKeysInSlot(slot, keys, maxkeys);
4101         addReplyMultiBulkLen(c,numkeys);
4102         for (j = 0; j < numkeys; j++) addReplyBulk(c,keys[j]);
4103         zfree(keys);
4104     } else if (!strcasecmp(c->argv[1]->ptr,"forget") && c->argc == 3) {
4105         /* CLUSTER FORGET <NODE ID> */
4106         clusterNode *n = clusterLookupNode(c->argv[2]->ptr);
4107 
4108         if (!n) {
4109             addReplyErrorFormat(c,"Unknown node %s", (char*)c->argv[2]->ptr);
4110             return;
4111         } else if (n == myself) {
4112             addReplyError(c,"I tried hard but I can't forget myself...");
4113             return;
4114         } else if (nodeIsSlave(myself) && myself->slaveof == n) {
4115             addReplyError(c,"Can't forget my master!");
4116             return;
4117         }
4118         clusterBlacklistAddNode(n);
4119         clusterDelNode(n);
4120         clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|
4121                              CLUSTER_TODO_SAVE_CONFIG);
4122         addReply(c,shared.ok);
4123     } else if (!strcasecmp(c->argv[1]->ptr,"replicate") && c->argc == 3) {
4124         /* CLUSTER REPLICATE <NODE ID> */
4125         clusterNode *n = clusterLookupNode(c->argv[2]->ptr);
4126 
4127         /* Lookup the specified node in our table. */
4128         if (!n) {
4129             addReplyErrorFormat(c,"Unknown node %s", (char*)c->argv[2]->ptr);
4130             return;
4131         }
4132 
4133         /* I can't replicate myself. */
4134         if (n == myself) {
4135             addReplyError(c,"Can't replicate myself");
4136             return;
4137         }
4138 
4139         /* Can't replicate a slave. */
4140         if (nodeIsSlave(n)) {
4141             addReplyError(c,"I can only replicate a master, not a slave.");
4142             return;
4143         }
4144 
4145         /* If the instance is currently a master, it should have no assigned
4146          * slots nor keys to accept to replicate some other node.
4147          * Slaves can switch to another master without issues. */
4148         if (nodeIsMaster(myself) &&
4149             (myself->numslots != 0 || dictSize(server.db[0].dict) != 0)) {
4150             addReplyError(c,
4151                 "To set a master the node must be empty and "
4152                 "without assigned slots.");
4153             return;
4154         }
4155 
4156         /* Set the master. */
4157         clusterSetMaster(n);
4158         clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
4159         addReply(c,shared.ok);
4160     } else if (!strcasecmp(c->argv[1]->ptr,"slaves") && c->argc == 3) {
4161         /* CLUSTER SLAVES <NODE ID> */
4162         clusterNode *n = clusterLookupNode(c->argv[2]->ptr);
4163         int j;
4164 
4165         /* Lookup the specified node in our table. */
4166         if (!n) {
4167             addReplyErrorFormat(c,"Unknown node %s", (char*)c->argv[2]->ptr);
4168             return;
4169         }
4170 
4171         if (nodeIsSlave(n)) {
4172             addReplyError(c,"The specified node is not a master");
4173             return;
4174         }
4175 
4176         addReplyMultiBulkLen(c,n->numslaves);
4177         for (j = 0; j < n->numslaves; j++) {
4178             sds ni = clusterGenNodeDescription(n->slaves[j]);
4179             addReplyBulkCString(c,ni);
4180             sdsfree(ni);
4181         }
4182     } else if (!strcasecmp(c->argv[1]->ptr,"count-failure-reports") &&
4183                c->argc == 3)
4184     {
4185         /* CLUSTER COUNT-FAILURE-REPORTS <NODE ID> */
4186         clusterNode *n = clusterLookupNode(c->argv[2]->ptr);
4187 
4188         if (!n) {
4189             addReplyErrorFormat(c,"Unknown node %s", (char*)c->argv[2]->ptr);
4190             return;
4191         } else {
4192             addReplyLongLong(c,clusterNodeFailureReportsCount(n));
4193         }
4194     } else if (!strcasecmp(c->argv[1]->ptr,"failover") &&
4195                (c->argc == 2 || c->argc == 3))
4196     {
4197         /* CLUSTER FAILOVER [FORCE|TAKEOVER] */
4198         int force = 0, takeover = 0;
4199 
4200         if (c->argc == 3) {
4201             if (!strcasecmp(c->argv[2]->ptr,"force")) {
4202                 force = 1;
4203             } else if (!strcasecmp(c->argv[2]->ptr,"takeover")) {
4204                 takeover = 1;
4205                 force = 1; /* Takeover also implies force. */
4206             } else {
4207                 addReply(c,shared.syntaxerr);
4208                 return;
4209             }
4210         }
4211 
4212         /* Check preconditions. */
4213         if (nodeIsMaster(myself)) {
4214             addReplyError(c,"You should send CLUSTER FAILOVER to a slave");
4215             return;
4216         } else if (myself->slaveof == NULL) {
4217             addReplyError(c,"I'm a slave but my master is unknown to me");
4218             return;
4219         } else if (!force &&
4220                    (nodeFailed(myself->slaveof) ||
4221                     myself->slaveof->link == NULL))
4222         {
4223             addReplyError(c,"Master is down or failed, "
4224                             "please use CLUSTER FAILOVER FORCE");
4225             return;
4226         }
4227         resetManualFailover();
4228         server.cluster->mf_end = mstime() + CLUSTER_MF_TIMEOUT;
4229 
4230         if (takeover) {
4231             /* A takeover does not perform any initial check. It just
4232              * generates a new configuration epoch for this node without
4233              * consensus, claims the master's slots, and broadcast the new
4234              * configuration. */
4235             serverLog(LL_WARNING,"Taking over the master (user request).");
4236             clusterBumpConfigEpochWithoutConsensus();
4237             clusterFailoverReplaceYourMaster();
4238         } else if (force) {
4239             /* If this is a forced failover, we don't need to talk with our
4240              * master to agree about the offset. We just failover taking over
4241              * it without coordination. */
4242             serverLog(LL_WARNING,"Forced failover user request accepted.");
4243             server.cluster->mf_can_start = 1;
4244         } else {
4245             serverLog(LL_WARNING,"Manual failover user request accepted.");
4246             clusterSendMFStart(myself->slaveof);
4247         }
4248         addReply(c,shared.ok);
4249     } else if (!strcasecmp(c->argv[1]->ptr,"set-config-epoch") && c->argc == 3)
4250     {
4251         /* CLUSTER SET-CONFIG-EPOCH <epoch>
4252          *
4253          * The user is allowed to set the config epoch only when a node is
4254          * totally fresh: no config epoch, no other known node, and so forth.
4255          * This happens at cluster creation time to start with a cluster where
4256          * every node has a different node ID, without to rely on the conflicts
4257          * resolution system which is too slow when a big cluster is created. */
4258         long long epoch;
4259 
4260         if (getLongLongFromObjectOrReply(c,c->argv[2],&epoch,NULL) != C_OK)
4261             return;
4262 
4263         if (epoch < 0) {
4264             addReplyErrorFormat(c,"Invalid config epoch specified: %lld",epoch);
4265         } else if (dictSize(server.cluster->nodes) > 1) {
4266             addReplyError(c,"The user can assign a config epoch only when the "
4267                             "node does not know any other node.");
4268         } else if (myself->configEpoch != 0) {
4269             addReplyError(c,"Node config epoch is already non-zero");
4270         } else {
4271             myself->configEpoch = epoch;
4272             serverLog(LL_WARNING,
4273                 "configEpoch set to %llu via CLUSTER SET-CONFIG-EPOCH",
4274                 (unsigned long long) myself->configEpoch);
4275 
4276             if (server.cluster->currentEpoch < (uint64_t)epoch)
4277                 server.cluster->currentEpoch = epoch;
4278             /* No need to fsync the config here since in the unlucky event
4279              * of a failure to persist the config, the conflict resolution code
4280              * will assign an unique config to this node. */
4281             clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|
4282                                  CLUSTER_TODO_SAVE_CONFIG);
4283             addReply(c,shared.ok);
4284         }
4285     } else if (!strcasecmp(c->argv[1]->ptr,"reset") &&
4286                (c->argc == 2 || c->argc == 3))
4287     {
4288         /* CLUSTER RESET [SOFT|HARD] */
4289         int hard = 0;
4290 
4291         /* Parse soft/hard argument. Default is soft. */
4292         if (c->argc == 3) {
4293             if (!strcasecmp(c->argv[2]->ptr,"hard")) {
4294                 hard = 1;
4295             } else if (!strcasecmp(c->argv[2]->ptr,"soft")) {
4296                 hard = 0;
4297             } else {
4298                 addReply(c,shared.syntaxerr);
4299                 return;
4300             }
4301         }
4302 
4303         /* Slaves can be reset while containing data, but not master nodes
4304          * that must be empty. */
4305         if (nodeIsMaster(myself) && dictSize(c->db->dict) != 0) {
4306             addReplyError(c,"CLUSTER RESET can't be called with "
4307                             "master nodes containing keys");
4308             return;
4309         }
4310         clusterReset(hard);
4311         addReply(c,shared.ok);
4312     } else {
4313         addReplyError(c,"Wrong CLUSTER subcommand or number of arguments");
4314     }
4315 }
4316 
4317 /* -----------------------------------------------------------------------------
4318  * DUMP, RESTORE and MIGRATE commands
4319  * -------------------------------------------------------------------------- */
4320 
4321 /* Generates a DUMP-format representation of the object 'o', adding it to the
4322  * io stream pointed by 'rio'. This function can't fail. */
4323 void createDumpPayload(rio *payload, robj *o) {
4324     unsigned char buf[2];
4325     uint64_t crc;
4326 
4327     /* Serialize the object in a RDB-like format. It consist of an object type
4328      * byte followed by the serialized object. This is understood by RESTORE. */
4329     rioInitWithBuffer(payload,sdsempty());
4330     serverAssert(rdbSaveObjectType(payload,o));
4331     serverAssert(rdbSaveObject(payload,o));
4332 
4333     /* Write the footer, this is how it looks like:
4334      * ----------------+---------------------+---------------+
4335      * ... RDB payload | 2 bytes RDB version | 8 bytes CRC64 |
4336      * ----------------+---------------------+---------------+
4337      * RDB version and CRC are both in little endian.
4338      */
4339 
4340     /* RDB version */
4341     buf[0] = RDB_VERSION & 0xff;
4342     buf[1] = (RDB_VERSION >> 8) & 0xff;
4343     payload->io.buffer.ptr = sdscatlen(payload->io.buffer.ptr,buf,2);
4344 
4345     /* CRC64 */
4346     crc = crc64(0,(unsigned char*)payload->io.buffer.ptr,
4347                 sdslen(payload->io.buffer.ptr));
4348     memrev64ifbe(&crc);
4349     payload->io.buffer.ptr = sdscatlen(payload->io.buffer.ptr,&crc,8);
4350 }
4351 
4352 /* Verify that the RDB version of the dump payload matches the one of this Redis
4353  * instance and that the checksum is ok.
4354  * If the DUMP payload looks valid C_OK is returned, otherwise C_ERR
4355  * is returned. */
4356 int verifyDumpPayload(unsigned char *p, size_t len) {
4357     unsigned char *footer;
4358     uint16_t rdbver;
4359     uint64_t crc;
4360 
4361     /* At least 2 bytes of RDB version and 8 of CRC64 should be present. */
4362     if (len < 10) return C_ERR;
4363     footer = p+(len-10);
4364 
4365     /* Verify RDB version */
4366     rdbver = (footer[1] << 8) | footer[0];
4367     if (rdbver != RDB_VERSION) return C_ERR;
4368 
4369     /* Verify CRC64 */
4370     crc = crc64(0,p,len-8);
4371     memrev64ifbe(&crc);
4372     return (memcmp(&crc,footer+2,8) == 0) ? C_OK : C_ERR;
4373 }
4374 
4375 /* DUMP keyname
4376  * DUMP is actually not used by Redis Cluster but it is the obvious
4377  * complement of RESTORE and can be useful for different applications. */
4378 void dumpCommand(client *c) {
4379     robj *o, *dumpobj;
4380     rio payload;
4381 
4382     /* Check if the key is here. */
4383     if ((o = lookupKeyRead(c->db,c->argv[1])) == NULL) {
4384         addReply(c,shared.nullbulk);
4385         return;
4386     }
4387 
4388     /* Create the DUMP encoded representation. */
4389     createDumpPayload(&payload,o);
4390 
4391     /* Transfer to the client */
4392     dumpobj = createObject(OBJ_STRING,payload.io.buffer.ptr);
4393     addReplyBulk(c,dumpobj);
4394     decrRefCount(dumpobj);
4395     return;
4396 }
4397 
4398 /* RESTORE key ttl serialized-value [REPLACE] */
4399 void restoreCommand(client *c) {
4400     long long ttl;
4401     rio payload;
4402     int j, type, replace = 0;
4403     robj *obj;
4404 
4405     /* Parse additional options */
4406     for (j = 4; j < c->argc; j++) {
4407         if (!strcasecmp(c->argv[j]->ptr,"replace")) {
4408             replace = 1;
4409         } else {
4410             addReply(c,shared.syntaxerr);
4411             return;
4412         }
4413     }
4414 
4415     /* Make sure this key does not already exist here... */
4416     if (!replace && lookupKeyWrite(c->db,c->argv[1]) != NULL) {
4417         addReply(c,shared.busykeyerr);
4418         return;
4419     }
4420 
4421     /* Check if the TTL value makes sense */
4422     if (getLongLongFromObjectOrReply(c,c->argv[2],&ttl,NULL) != C_OK) {
4423         return;
4424     } else if (ttl < 0) {
4425         addReplyError(c,"Invalid TTL value, must be >= 0");
4426         return;
4427     }
4428 
4429     /* Verify RDB version and data checksum. */
4430     if (verifyDumpPayload(c->argv[3]->ptr,sdslen(c->argv[3]->ptr)) == C_ERR)
4431     {
4432         addReplyError(c,"DUMP payload version or checksum are wrong");
4433         return;
4434     }
4435 
4436     rioInitWithBuffer(&payload,c->argv[3]->ptr);
4437     if (((type = rdbLoadObjectType(&payload)) == -1) ||
4438         ((obj = rdbLoadObject(type,&payload)) == NULL))
4439     {
4440         addReplyError(c,"Bad data format");
4441         return;
4442     }
4443 
4444     /* Remove the old key if needed. */
4445     if (replace) dbDelete(c->db,c->argv[1]);
4446 
4447     /* Create the key and set the TTL if any */
4448     dbAdd(c->db,c->argv[1],obj);
4449     if (ttl) setExpire(c->db,c->argv[1],mstime()+ttl);
4450     signalModifiedKey(c->db,c->argv[1]);
4451     addReply(c,shared.ok);
4452     server.dirty++;
4453 }
4454 
4455 /* MIGRATE socket cache implementation.
4456  *
4457  * We take a map between host:ip and a TCP socket that we used to connect
4458  * to this instance in recent time.
4459  * This sockets are closed when the max number we cache is reached, and also
4460  * in serverCron() when they are around for more than a few seconds. */
4461 #define MIGRATE_SOCKET_CACHE_ITEMS 64 /* max num of items in the cache. */
4462 #define MIGRATE_SOCKET_CACHE_TTL 10 /* close cached sockets after 10 sec. */
4463 
4464 typedef struct migrateCachedSocket {
4465     int fd;
4466     long last_dbid;
4467     time_t last_use_time;
4468 } migrateCachedSocket;
4469 
4470 /* Return a migrateCachedSocket containing a TCP socket connected with the
4471  * target instance, possibly returning a cached one.
4472  *
4473  * This function is responsible of sending errors to the client if a
4474  * connection can't be established. In this case -1 is returned.
4475  * Otherwise on success the socket is returned, and the caller should not
4476  * attempt to free it after usage.
4477  *
4478  * If the caller detects an error while using the socket, migrateCloseSocket()
4479  * should be called so that the connection will be created from scratch
4480  * the next time. */
4481 migrateCachedSocket* migrateGetSocket(client *c, robj *host, robj *port, long timeout) {
4482     int fd;
4483     sds name = sdsempty();
4484     migrateCachedSocket *cs;
4485 
4486     /* Check if we have an already cached socket for this ip:port pair. */
4487     name = sdscatlen(name,host->ptr,sdslen(host->ptr));
4488     name = sdscatlen(name,":",1);
4489     name = sdscatlen(name,port->ptr,sdslen(port->ptr));
4490     cs = dictFetchValue(server.migrate_cached_sockets,name);
4491     if (cs) {
4492         sdsfree(name);
4493         cs->last_use_time = server.unixtime;
4494         return cs;
4495     }
4496 
4497     /* No cached socket, create one. */
4498     if (dictSize(server.migrate_cached_sockets) == MIGRATE_SOCKET_CACHE_ITEMS) {
4499         /* Too many items, drop one at random. */
4500         dictEntry *de = dictGetRandomKey(server.migrate_cached_sockets);
4501         cs = dictGetVal(de);
4502         close(cs->fd);
4503         zfree(cs);
4504         dictDelete(server.migrate_cached_sockets,dictGetKey(de));
4505     }
4506 
4507     /* Create the socket */
4508     fd = anetTcpNonBlockConnect(server.neterr,c->argv[1]->ptr,
4509                                 atoi(c->argv[2]->ptr));
4510     if (fd == -1) {
4511         sdsfree(name);
4512         addReplyErrorFormat(c,"Can't connect to target node: %s",
4513             server.neterr);
4514         return NULL;
4515     }
4516     anetEnableTcpNoDelay(server.neterr,fd);
4517 
4518     /* Check if it connects within the specified timeout. */
4519     if ((aeWait(fd,AE_WRITABLE,timeout) & AE_WRITABLE) == 0) {
4520         sdsfree(name);
4521         addReplySds(c,
4522             sdsnew("-IOERR error or timeout connecting to the client\r\n"));
4523         close(fd);
4524         return NULL;
4525     }
4526 
4527     /* Add to the cache and return it to the caller. */
4528     cs = zmalloc(sizeof(*cs));
4529     cs->fd = fd;
4530     cs->last_dbid = -1;
4531     cs->last_use_time = server.unixtime;
4532     dictAdd(server.migrate_cached_sockets,name,cs);
4533     return cs;
4534 }
4535 
4536 /* Free a migrate cached connection. */
4537 void migrateCloseSocket(robj *host, robj *port) {
4538     sds name = sdsempty();
4539     migrateCachedSocket *cs;
4540 
4541     name = sdscatlen(name,host->ptr,sdslen(host->ptr));
4542     name = sdscatlen(name,":",1);
4543     name = sdscatlen(name,port->ptr,sdslen(port->ptr));
4544     cs = dictFetchValue(server.migrate_cached_sockets,name);
4545     if (!cs) {
4546         sdsfree(name);
4547         return;
4548     }
4549 
4550     close(cs->fd);
4551     zfree(cs);
4552     dictDelete(server.migrate_cached_sockets,name);
4553     sdsfree(name);
4554 }
4555 
4556 void migrateCloseTimedoutSockets(void) {
4557     dictIterator *di = dictGetSafeIterator(server.migrate_cached_sockets);
4558     dictEntry *de;
4559 
4560     while((de = dictNext(di)) != NULL) {
4561         migrateCachedSocket *cs = dictGetVal(de);
4562 
4563         if ((server.unixtime - cs->last_use_time) > MIGRATE_SOCKET_CACHE_TTL) {
4564             close(cs->fd);
4565             zfree(cs);
4566             dictDelete(server.migrate_cached_sockets,dictGetKey(de));
4567         }
4568     }
4569     dictReleaseIterator(di);
4570 }
4571 
4572 /* MIGRATE host port key dbid timeout [COPY | REPLACE] */
4573 void migrateCommand(client *c) {
4574     migrateCachedSocket *cs;
4575     int copy, replace, j;
4576     long timeout;
4577     long dbid;
4578     long long ttl, expireat;
4579     robj *o;
4580     rio cmd, payload;
4581     int retry_num = 0;
4582 
4583 try_again:
4584     /* Initialization */
4585     copy = 0;
4586     replace = 0;
4587     ttl = 0;
4588 
4589     /* Parse additional options */
4590     for (j = 6; j < c->argc; j++) {
4591         if (!strcasecmp(c->argv[j]->ptr,"copy")) {
4592             copy = 1;
4593         } else if (!strcasecmp(c->argv[j]->ptr,"replace")) {
4594             replace = 1;
4595         } else {
4596             addReply(c,shared.syntaxerr);
4597             return;
4598         }
4599     }
4600 
4601     /* Sanity check */
4602     if (getLongFromObjectOrReply(c,c->argv[5],&timeout,NULL) != C_OK)
4603         return;
4604     if (getLongFromObjectOrReply(c,c->argv[4],&dbid,NULL) != C_OK)
4605         return;
4606     if (timeout <= 0) timeout = 1000;
4607 
4608     /* Check if the key is here. If not we reply with success as there is
4609      * nothing to migrate (for instance the key expired in the meantime), but
4610      * we include such information in the reply string. */
4611     if ((o = lookupKeyRead(c->db,c->argv[3])) == NULL) {
4612         addReplySds(c,sdsnew("+NOKEY\r\n"));
4613         return;
4614     }
4615 
4616     /* Connect */
4617     cs = migrateGetSocket(c,c->argv[1],c->argv[2],timeout);
4618     if (cs == NULL) return; /* error sent to the client by migrateGetSocket() */
4619 
4620     rioInitWithBuffer(&cmd,sdsempty());
4621 
4622     /* Send the SELECT command if the current DB is not already selected. */
4623     int select = cs->last_dbid != dbid; /* Should we emit SELECT? */
4624     if (select) {
4625         serverAssertWithInfo(c,NULL,rioWriteBulkCount(&cmd,'*',2));
4626         serverAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,"SELECT",6));
4627         serverAssertWithInfo(c,NULL,rioWriteBulkLongLong(&cmd,dbid));
4628     }
4629 
4630     /* Create RESTORE payload and generate the protocol to call the command. */
4631     expireat = getExpire(c->db,c->argv[3]);
4632     if (expireat != -1) {
4633         ttl = expireat-mstime();
4634         if (ttl < 1) ttl = 1;
4635     }
4636     serverAssertWithInfo(c,NULL,rioWriteBulkCount(&cmd,'*',replace ? 5 : 4));
4637     if (server.cluster_enabled)
4638         serverAssertWithInfo(c,NULL,
4639             rioWriteBulkString(&cmd,"RESTORE-ASKING",14));
4640     else
4641         serverAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,"RESTORE",7));
4642     serverAssertWithInfo(c,NULL,sdsEncodedObject(c->argv[3]));
4643     serverAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,c->argv[3]->ptr,
4644             sdslen(c->argv[3]->ptr)));
4645     serverAssertWithInfo(c,NULL,rioWriteBulkLongLong(&cmd,ttl));
4646 
4647     /* Emit the payload argument, that is the serialized object using
4648      * the DUMP format. */
4649     createDumpPayload(&payload,o);
4650     serverAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,payload.io.buffer.ptr,
4651                                 sdslen(payload.io.buffer.ptr)));
4652     sdsfree(payload.io.buffer.ptr);
4653 
4654     /* Add the REPLACE option to the RESTORE command if it was specified
4655      * as a MIGRATE option. */
4656     if (replace)
4657         serverAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,"REPLACE",7));
4658 
4659     /* Transfer the query to the other node in 64K chunks. */
4660     errno = 0;
4661     {
4662         sds buf = cmd.io.buffer.ptr;
4663         size_t pos = 0, towrite;
4664         int nwritten = 0;
4665 
4666         while ((towrite = sdslen(buf)-pos) > 0) {
4667             towrite = (towrite > (64*1024) ? (64*1024) : towrite);
4668             nwritten = syncWrite(cs->fd,buf+pos,towrite,timeout);
4669             if (nwritten != (signed)towrite) goto socket_wr_err;
4670             pos += nwritten;
4671         }
4672     }
4673 
4674     /* Read back the reply. */
4675     {
4676         char buf1[1024];
4677         char buf2[1024];
4678 
4679         /* Read the two replies */
4680         if (select && syncReadLine(cs->fd, buf1, sizeof(buf1), timeout) <= 0)
4681             goto socket_rd_err;
4682         if (syncReadLine(cs->fd, buf2, sizeof(buf2), timeout) <= 0)
4683             goto socket_rd_err;
4684         if ((select && buf1[0] == '-') || buf2[0] == '-') {
4685             /* On error assume that last_dbid is no longer valid. */
4686             cs->last_dbid = -1;
4687             addReplyErrorFormat(c,"Target instance replied with error: %s",
4688                 (select && buf1[0] == '-') ? buf1+1 : buf2+1);
4689         } else {
4690             /* Update the last_dbid in migrateCachedSocket */
4691             cs->last_dbid = dbid;
4692             robj *aux;
4693 
4694             addReply(c,shared.ok);
4695 
4696             if (!copy) {
4697                 /* No COPY option: remove the local key, signal the change. */
4698                 dbDelete(c->db,c->argv[3]);
4699                 signalModifiedKey(c->db,c->argv[3]);
4700                 server.dirty++;
4701 
4702                 /* Translate MIGRATE as DEL for replication/AOF. */
4703                 aux = createStringObject("DEL",3);
4704                 rewriteClientCommandVector(c,2,aux,c->argv[3]);
4705                 decrRefCount(aux);
4706             }
4707         }
4708     }
4709 
4710     sdsfree(cmd.io.buffer.ptr);
4711     return;
4712 
4713 socket_wr_err:
4714     sdsfree(cmd.io.buffer.ptr);
4715     migrateCloseSocket(c->argv[1],c->argv[2]);
4716     if (errno != ETIMEDOUT && retry_num++ == 0) goto try_again;
4717     addReplySds(c,
4718         sdsnew("-IOERR error or timeout writing to target instance\r\n"));
4719     return;
4720 
4721 socket_rd_err:
4722     sdsfree(cmd.io.buffer.ptr);
4723     migrateCloseSocket(c->argv[1],c->argv[2]);
4724     if (errno != ETIMEDOUT && retry_num++ == 0) goto try_again;
4725     addReplySds(c,
4726         sdsnew("-IOERR error or timeout reading from target node\r\n"));
4727     return;
4728 }
4729 
4730 /* -----------------------------------------------------------------------------
4731  * Cluster functions related to serving / redirecting clients
4732  * -------------------------------------------------------------------------- */
4733 
4734 /* The ASKING command is required after a -ASK redirection.
4735  * The client should issue ASKING before to actually send the command to
4736  * the target instance. See the Redis Cluster specification for more
4737  * information. */
4738 void askingCommand(client *c) {
4739     if (server.cluster_enabled == 0) {
4740         addReplyError(c,"This instance has cluster support disabled");
4741         return;
4742     }
4743     c->flags |= CLIENT_ASKING;
4744     addReply(c,shared.ok);
4745 }
4746 
4747 /* The READONLY command is used by clients to enter the read-only mode.
4748  * In this mode slaves will not redirect clients as long as clients access
4749  * with read-only commands to keys that are served by the slave's master. */
4750 void readonlyCommand(client *c) {
4751     if (server.cluster_enabled == 0) {
4752         addReplyError(c,"This instance has cluster support disabled");
4753         return;
4754     }
4755     c->flags |= CLIENT_READONLY;
4756     addReply(c,shared.ok);
4757 }
4758 
4759 /* The READWRITE command just clears the READONLY command state. */
4760 void readwriteCommand(client *c) {
4761     c->flags &= ~CLIENT_READONLY;
4762     addReply(c,shared.ok);
4763 }
4764 
4765 /* Return the pointer to the cluster node that is able to serve the command.
4766  * For the function to succeed the command should only target either:
4767  *
4768  * 1) A single key (even multiple times like LPOPRPUSH mylist mylist).
4769  * 2) Multiple keys in the same hash slot, while the slot is stable (no
4770  *    resharding in progress).
4771  *
4772  * On success the function returns the node that is able to serve the request.
4773  * If the node is not 'myself' a redirection must be perfomed. The kind of
4774  * redirection is specified setting the integer passed by reference
4775  * 'error_code', which will be set to CLUSTER_REDIR_ASK or
4776  * CLUSTER_REDIR_MOVED.
4777  *
4778  * When the node is 'myself' 'error_code' is set to CLUSTER_REDIR_NONE.
4779  *
4780  * If the command fails NULL is returned, and the reason of the failure is
4781  * provided via 'error_code', which will be set to:
4782  *
4783  * CLUSTER_REDIR_CROSS_SLOT if the request contains multiple keys that
4784  * don't belong to the same hash slot.
4785  *
4786  * CLUSTER_REDIR_UNSTABLE if the request contains mutliple keys
4787  * belonging to the same slot, but the slot is not stable (in migration or
4788  * importing state, likely because a resharding is in progress).
4789  *
4790  * CLUSTER_REDIR_DOWN_UNBOUND if the request addresses a slot which is
4791  * not bound to any node. In this case the cluster global state should be
4792  * already "down" but it is fragile to rely on the update of the global state,
4793  * so we also handle it here. */
4794 clusterNode *getNodeByQuery(client *c, struct redisCommand *cmd, robj **argv, int argc, int *hashslot, int *error_code) {
4795     clusterNode *n = NULL;
4796     robj *firstkey = NULL;
4797     int multiple_keys = 0;
4798     multiState *ms, _ms;
4799     multiCmd mc;
4800     int i, slot = 0, migrating_slot = 0, importing_slot = 0, missing_keys = 0;
4801 
4802     /* Set error code optimistically for the base case. */
4803     if (error_code) *error_code = CLUSTER_REDIR_NONE;
4804 
4805     /* We handle all the cases as if they were EXEC commands, so we have
4806      * a common code path for everything */
4807     if (cmd->proc == execCommand) {
4808         /* If CLIENT_MULTI flag is not set EXEC is just going to return an
4809          * error. */
4810         if (!(c->flags & CLIENT_MULTI)) return myself;
4811         ms = &c->mstate;
4812     } else {
4813         /* In order to have a single codepath create a fake Multi State
4814          * structure if the client is not in MULTI/EXEC state, this way
4815          * we have a single codepath below. */
4816         ms = &_ms;
4817         _ms.commands = &mc;
4818         _ms.count = 1;
4819         mc.argv = argv;
4820         mc.argc = argc;
4821         mc.cmd = cmd;
4822     }
4823 
4824     /* Check that all the keys are in the same hash slot, and obtain this
4825      * slot and the node associated. */
4826     for (i = 0; i < ms->count; i++) {
4827         struct redisCommand *mcmd;
4828         robj **margv;
4829         int margc, *keyindex, numkeys, j;
4830 
4831         mcmd = ms->commands[i].cmd;
4832         margc = ms->commands[i].argc;
4833         margv = ms->commands[i].argv;
4834 
4835         keyindex = getKeysFromCommand(mcmd,margv,margc,&numkeys);
4836         for (j = 0; j < numkeys; j++) {
4837             robj *thiskey = margv[keyindex[j]];
4838             int thisslot = keyHashSlot((char*)thiskey->ptr,
4839                                        sdslen(thiskey->ptr));
4840 
4841             if (firstkey == NULL) {
4842                 /* This is the first key we see. Check what is the slot
4843                  * and node. */
4844                 firstkey = thiskey;
4845                 slot = thisslot;
4846                 n = server.cluster->slots[slot];
4847 
4848                 /* Error: If a slot is not served, we are in "cluster down"
4849                  * state. However the state is yet to be updated, so this was
4850                  * not trapped earlier in processCommand(). Report the same
4851                  * error to the client. */
4852                 if (n == NULL) {
4853                     getKeysFreeResult(keyindex);
4854                     if (error_code)
4855                         *error_code = CLUSTER_REDIR_DOWN_UNBOUND;
4856                     return NULL;
4857                 }
4858 
4859                 /* If we are migrating or importing this slot, we need to check
4860                  * if we have all the keys in the request (the only way we
4861                  * can safely serve the request, otherwise we return a TRYAGAIN
4862                  * error). To do so we set the importing/migrating state and
4863                  * increment a counter for every missing key. */
4864                 if (n == myself &&
4865                     server.cluster->migrating_slots_to[slot] != NULL)
4866                 {
4867                     migrating_slot = 1;
4868                 } else if (server.cluster->importing_slots_from[slot] != NULL) {
4869                     importing_slot = 1;
4870                 }
4871             } else {
4872                 /* If it is not the first key, make sure it is exactly
4873                  * the same key as the first we saw. */
4874                 if (!equalStringObjects(firstkey,thiskey)) {
4875                     if (slot != thisslot) {
4876                         /* Error: multiple keys from different slots. */
4877                         getKeysFreeResult(keyindex);
4878                         if (error_code)
4879                             *error_code = CLUSTER_REDIR_CROSS_SLOT;
4880                         return NULL;
4881                     } else {
4882                         /* Flag this request as one with multiple different
4883                          * keys. */
4884                         multiple_keys = 1;
4885                     }
4886                 }
4887             }
4888 
4889             /* Migarting / Improrting slot? Count keys we don't have. */
4890             if ((migrating_slot || importing_slot) &&
4891                 lookupKeyRead(&server.db[0],thiskey) == NULL)
4892             {
4893                 missing_keys++;
4894             }
4895         }
4896         getKeysFreeResult(keyindex);
4897     }
4898 
4899     /* No key at all in command? then we can serve the request
4900      * without redirections or errors. */
4901     if (n == NULL) return myself;
4902 
4903     /* Return the hashslot by reference. */
4904     if (hashslot) *hashslot = slot;
4905 
4906     /* This request is about a slot we are migrating into another instance?
4907      * Then if we have all the keys. */
4908 
4909     /* If we don't have all the keys and we are migrating the slot, send
4910      * an ASK redirection. */
4911     if (migrating_slot && missing_keys) {
4912         if (error_code) *error_code = CLUSTER_REDIR_ASK;
4913         return server.cluster->migrating_slots_to[slot];
4914     }
4915 
4916     /* If we are receiving the slot, and the client correctly flagged the
4917      * request as "ASKING", we can serve the request. However if the request
4918      * involves multiple keys and we don't have them all, the only option is
4919      * to send a TRYAGAIN error. */
4920     if (importing_slot &&
4921         (c->flags & CLIENT_ASKING || cmd->flags & CMD_ASKING))
4922     {
4923         if (multiple_keys && missing_keys) {
4924             if (error_code) *error_code = CLUSTER_REDIR_UNSTABLE;
4925             return NULL;
4926         } else {
4927             return myself;
4928         }
4929     }
4930 
4931     /* Handle the read-only client case reading from a slave: if this
4932      * node is a slave and the request is about an hash slot our master
4933      * is serving, we can reply without redirection. */
4934     if (c->flags & CLIENT_READONLY &&
4935         cmd->flags & CMD_READONLY &&
4936         nodeIsSlave(myself) &&
4937         myself->slaveof == n)
4938     {
4939         return myself;
4940     }
4941 
4942     /* Base case: just return the right node. However if this node is not
4943      * myself, set error_code to MOVED since we need to issue a rediretion. */
4944     if (n != myself && error_code) *error_code = CLUSTER_REDIR_MOVED;
4945     return n;
4946 }
4947 
4948 /* Send the client the right redirection code, according to error_code
4949  * that should be set to one of CLUSTER_REDIR_* macros.
4950  *
4951  * If CLUSTER_REDIR_ASK or CLUSTER_REDIR_MOVED error codes
4952  * are used, then the node 'n' should not be NULL, but should be the
4953  * node we want to mention in the redirection. Moreover hashslot should
4954  * be set to the hash slot that caused the redirection. */
4955 void clusterRedirectClient(client *c, clusterNode *n, int hashslot, int error_code) {
4956     if (error_code == CLUSTER_REDIR_CROSS_SLOT) {
4957         addReplySds(c,sdsnew("-CROSSSLOT Keys in request don't hash to the same slot\r\n"));
4958     } else if (error_code == CLUSTER_REDIR_UNSTABLE) {
4959         /* The request spawns mutliple keys in the same slot,
4960          * but the slot is not "stable" currently as there is
4961          * a migration or import in progress. */
4962         addReplySds(c,sdsnew("-TRYAGAIN Multiple keys request during rehashing of slot\r\n"));
4963     } else if (error_code == CLUSTER_REDIR_DOWN_STATE) {
4964         addReplySds(c,sdsnew("-CLUSTERDOWN The cluster is down\r\n"));
4965     } else if (error_code == CLUSTER_REDIR_DOWN_UNBOUND) {
4966         addReplySds(c,sdsnew("-CLUSTERDOWN Hash slot not served\r\n"));
4967     } else if (error_code == CLUSTER_REDIR_MOVED ||
4968                error_code == CLUSTER_REDIR_ASK)
4969     {
4970         addReplySds(c,sdscatprintf(sdsempty(),
4971             "-%s %d %s:%d\r\n",
4972             (error_code == CLUSTER_REDIR_ASK) ? "ASK" : "MOVED",
4973             hashslot,n->ip,n->port));
4974     } else {
4975         serverPanic("getNodeByQuery() unknown error.");
4976     }
4977 }
4978 
4979 /* This function is called by the function processing clients incrementally
4980  * to detect timeouts, in order to handle the following case:
4981  *
4982  * 1) A client blocks with BLPOP or similar blocking operation.
4983  * 2) The master migrates the hash slot elsewhere or turns into a slave.
4984  * 3) The client may remain blocked forever (or up to the max timeout time)
4985  *    waiting for a key change that will never happen.
4986  *
4987  * If the client is found to be blocked into an hash slot this node no
4988  * longer handles, the client is sent a redirection error, and the function
4989  * returns 1. Otherwise 0 is returned and no operation is performed. */
4990 int clusterRedirectBlockedClientIfNeeded(client *c) {
4991     if (c->flags & CLIENT_BLOCKED && c->btype == BLOCKED_LIST) {
4992         dictEntry *de;
4993         dictIterator *di;
4994 
4995         /* If the cluster is down, unblock the client with the right error. */
4996         if (server.cluster->state == CLUSTER_FAIL) {
4997             clusterRedirectClient(c,NULL,0,CLUSTER_REDIR_DOWN_STATE);
4998             return 1;
4999         }
5000 
5001         di = dictGetIterator(c->bpop.keys);
5002         while((de = dictNext(di)) != NULL) {
5003             robj *key = dictGetKey(de);
5004             int slot = keyHashSlot((char*)key->ptr, sdslen(key->ptr));
5005             clusterNode *node = server.cluster->slots[slot];
5006 
5007             /* We send an error and unblock the client if:
5008              * 1) The slot is unassigned, emitting a cluster down error.
5009              * 2) The slot is not handled by this node, nor being imported. */
5010             if (node != myself &&
5011                 server.cluster->importing_slots_from[slot] == NULL)
5012             {
5013                 if (node == NULL) {
5014                     clusterRedirectClient(c,NULL,0,
5015                         CLUSTER_REDIR_DOWN_UNBOUND);
5016                 } else {
5017                     clusterRedirectClient(c,node,slot,
5018                         CLUSTER_REDIR_MOVED);
5019                 }
5020                 return 1;
5021             }
5022         }
5023         dictReleaseIterator(di);
5024     }
5025     return 0;
5026 }
5027