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