xref: /redis-3.2.3/src/cluster.c (revision 79d2f70f)
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 
76 /* -----------------------------------------------------------------------------
77  * Initialization
78  * -------------------------------------------------------------------------- */
79 
80 /* Return the greatest configEpoch found in the cluster. */
81 uint64_t clusterGetMaxEpoch(void) {
82     uint64_t max = 0;
83     dictIterator *di;
84     dictEntry *de;
85 
86     di = dictGetSafeIterator(server.cluster->nodes);
87     while((de = dictNext(di)) != NULL) {
88         clusterNode *node = dictGetVal(de);
89         if (node->configEpoch > max) max = node->configEpoch;
90     }
91     dictReleaseIterator(di);
92     if (max < server.cluster->currentEpoch) max = server.cluster->currentEpoch;
93     return max;
94 }
95 
96 /* Load the cluster config from 'filename'.
97  *
98  * If the file does not exist or is zero-length (this may happen because
99  * when we lock the nodes.conf file, we create a zero-length one for the
100  * sake of locking if it does not already exist), REDIS_ERR is returned.
101  * If the configuration was loaded from the file, REDIS_OK is returned. */
102 int clusterLoadConfig(char *filename) {
103     FILE *fp = fopen(filename,"r");
104     struct stat sb;
105     char *line;
106     int maxline, j;
107 
108     if (fp == NULL) {
109         if (errno == ENOENT) {
110             return REDIS_ERR;
111         } else {
112             redisLog(REDIS_WARNING,
113                 "Loading the cluster node config from %s: %s",
114                 filename, strerror(errno));
115             exit(1);
116         }
117     }
118 
119     /* Check if the file is zero-length: if so return REDIS_ERR to signal
120      * we have to write the config. */
121     if (fstat(fileno(fp),&sb) != -1 && sb.st_size == 0) {
122         fclose(fp);
123         return REDIS_ERR;
124     }
125 
126     /* Parse the file. Note that single liens of the cluster config file can
127      * be really long as they include all the hash slots of the node.
128      * This means in the worst possible case, half of the Redis slots will be
129      * present in a single line, possibly in importing or migrating state, so
130      * together with the node ID of the sender/receiver.
131      *
132      * To simplify we allocate 1024+REDIS_CLUSTER_SLOTS*128 bytes per line. */
133     maxline = 1024+REDIS_CLUSTER_SLOTS*128;
134     line = zmalloc(maxline);
135     while(fgets(line,maxline,fp) != NULL) {
136         int argc;
137         sds *argv;
138         clusterNode *n, *master;
139         char *p, *s;
140 
141         /* Skip blank lines, they can be created either by users manually
142          * editing nodes.conf or by the config writing process if stopped
143          * before the truncate() call. */
144         if (line[0] == '\n') continue;
145 
146         /* Split the line into arguments for processing. */
147         argv = sdssplitargs(line,&argc);
148         if (argv == NULL) goto fmterr;
149 
150         /* Handle the special "vars" line. Don't pretend it is the last
151          * line even if it actually is when generated by Redis. */
152         if (strcasecmp(argv[0],"vars") == 0) {
153             for (j = 1; j < argc; j += 2) {
154                 if (strcasecmp(argv[j],"currentEpoch") == 0) {
155                     server.cluster->currentEpoch =
156                             strtoull(argv[j+1],NULL,10);
157                 } else if (strcasecmp(argv[j],"lastVoteEpoch") == 0) {
158                     server.cluster->lastVoteEpoch =
159                             strtoull(argv[j+1],NULL,10);
160                 } else {
161                     redisLog(REDIS_WARNING,
162                         "Skipping unknown cluster config variable '%s'",
163                         argv[j]);
164                 }
165             }
166             continue;
167         }
168 
169         /* Create this node if it does not exist */
170         n = clusterLookupNode(argv[0]);
171         if (!n) {
172             n = createClusterNode(argv[0],0);
173             clusterAddNode(n);
174         }
175         /* Address and port */
176         if ((p = strchr(argv[1],':')) == NULL) goto fmterr;
177         *p = '\0';
178         memcpy(n->ip,argv[1],strlen(argv[1])+1);
179         n->port = atoi(p+1);
180 
181         /* Parse flags */
182         p = s = argv[2];
183         while(p) {
184             p = strchr(s,',');
185             if (p) *p = '\0';
186             if (!strcasecmp(s,"myself")) {
187                 redisAssert(server.cluster->myself == NULL);
188                 myself = server.cluster->myself = n;
189                 n->flags |= REDIS_NODE_MYSELF;
190             } else if (!strcasecmp(s,"master")) {
191                 n->flags |= REDIS_NODE_MASTER;
192             } else if (!strcasecmp(s,"slave")) {
193                 n->flags |= REDIS_NODE_SLAVE;
194             } else if (!strcasecmp(s,"fail?")) {
195                 n->flags |= REDIS_NODE_PFAIL;
196             } else if (!strcasecmp(s,"fail")) {
197                 n->flags |= REDIS_NODE_FAIL;
198                 n->fail_time = mstime();
199             } else if (!strcasecmp(s,"handshake")) {
200                 n->flags |= REDIS_NODE_HANDSHAKE;
201             } else if (!strcasecmp(s,"noaddr")) {
202                 n->flags |= REDIS_NODE_NOADDR;
203             } else if (!strcasecmp(s,"noflags")) {
204                 /* nothing to do */
205             } else {
206                 redisPanic("Unknown flag in redis cluster config file");
207             }
208             if (p) s = p+1;
209         }
210 
211         /* Get master if any. Set the master and populate master's
212          * slave list. */
213         if (argv[3][0] != '-') {
214             master = clusterLookupNode(argv[3]);
215             if (!master) {
216                 master = createClusterNode(argv[3],0);
217                 clusterAddNode(master);
218             }
219             n->slaveof = master;
220             clusterNodeAddSlave(master,n);
221         }
222 
223         /* Set ping sent / pong received timestamps */
224         if (atoi(argv[4])) n->ping_sent = mstime();
225         if (atoi(argv[5])) n->pong_received = mstime();
226 
227         /* Set configEpoch for this node. */
228         n->configEpoch = strtoull(argv[6],NULL,10);
229 
230         /* Populate hash slots served by this instance. */
231         for (j = 8; j < argc; j++) {
232             int start, stop;
233 
234             if (argv[j][0] == '[') {
235                 /* Here we handle migrating / importing slots */
236                 int slot;
237                 char direction;
238                 clusterNode *cn;
239 
240                 p = strchr(argv[j],'-');
241                 redisAssert(p != NULL);
242                 *p = '\0';
243                 direction = p[1]; /* Either '>' or '<' */
244                 slot = atoi(argv[j]+1);
245                 p += 3;
246                 cn = clusterLookupNode(p);
247                 if (!cn) {
248                     cn = createClusterNode(p,0);
249                     clusterAddNode(cn);
250                 }
251                 if (direction == '>') {
252                     server.cluster->migrating_slots_to[slot] = cn;
253                 } else {
254                     server.cluster->importing_slots_from[slot] = cn;
255                 }
256                 continue;
257             } else if ((p = strchr(argv[j],'-')) != NULL) {
258                 *p = '\0';
259                 start = atoi(argv[j]);
260                 stop = atoi(p+1);
261             } else {
262                 start = stop = atoi(argv[j]);
263             }
264             while(start <= stop) clusterAddSlot(n, start++);
265         }
266 
267         sdsfreesplitres(argv,argc);
268     }
269     zfree(line);
270     fclose(fp);
271 
272     /* Config sanity check */
273     redisAssert(server.cluster->myself != NULL);
274     redisLog(REDIS_NOTICE,"Node configuration loaded, I'm %.40s", myself->name);
275 
276     /* Something that should never happen: currentEpoch smaller than
277      * the max epoch found in the nodes configuration. However we handle this
278      * as some form of protection against manual editing of critical files. */
279     if (clusterGetMaxEpoch() > server.cluster->currentEpoch) {
280         server.cluster->currentEpoch = clusterGetMaxEpoch();
281     }
282     return REDIS_OK;
283 
284 fmterr:
285     redisLog(REDIS_WARNING,
286         "Unrecoverable error: corrupted cluster config file.");
287     fclose(fp);
288     exit(1);
289 }
290 
291 /* Cluster node configuration is exactly the same as CLUSTER NODES output.
292  *
293  * This function writes the node config and returns 0, on error -1
294  * is returned.
295  *
296  * Note: we need to write the file in an atomic way from the point of view
297  * of the POSIX filesystem semantics, so that if the server is stopped
298  * or crashes during the write, we'll end with either the old file or the
299  * new one. Since we have the full payload to write available we can use
300  * a single write to write the whole file. If the pre-existing file was
301  * bigger we pad our payload with newlines that are anyway ignored and truncate
302  * the file afterward. */
303 int clusterSaveConfig(int do_fsync) {
304     sds ci;
305     size_t content_size;
306     struct stat sb;
307     int fd;
308 
309     server.cluster->todo_before_sleep &= ~CLUSTER_TODO_SAVE_CONFIG;
310 
311     /* Get the nodes description and concatenate our "vars" directive to
312      * save currentEpoch and lastVoteEpoch. */
313     ci = clusterGenNodesDescription(REDIS_NODE_HANDSHAKE);
314     ci = sdscatprintf(ci,"vars currentEpoch %llu lastVoteEpoch %llu\n",
315         (unsigned long long) server.cluster->currentEpoch,
316         (unsigned long long) server.cluster->lastVoteEpoch);
317     content_size = sdslen(ci);
318 
319     if ((fd = open(server.cluster_configfile,O_WRONLY|O_CREAT,0644))
320         == -1) goto err;
321 
322     /* Pad the new payload if the existing file length is greater. */
323     if (fstat(fd,&sb) != -1) {
324         if (sb.st_size > content_size) {
325             ci = sdsgrowzero(ci,sb.st_size);
326             memset(ci+content_size,'\n',sb.st_size-content_size);
327         }
328     }
329     if (write(fd,ci,sdslen(ci)) != (ssize_t)sdslen(ci)) goto err;
330     if (do_fsync) {
331         server.cluster->todo_before_sleep &= ~CLUSTER_TODO_FSYNC_CONFIG;
332         fsync(fd);
333     }
334 
335     /* Truncate the file if needed to remove the final \n padding that
336      * is just garbage. */
337     if (content_size != sdslen(ci) && ftruncate(fd,content_size) == -1) {
338         /* ftruncate() failing is not a critical error. */
339     }
340     close(fd);
341     sdsfree(ci);
342     return 0;
343 
344 err:
345     if (fd != -1) close(fd);
346     sdsfree(ci);
347     return -1;
348 }
349 
350 void clusterSaveConfigOrDie(int do_fsync) {
351     if (clusterSaveConfig(do_fsync) == -1) {
352         redisLog(REDIS_WARNING,"Fatal: can't update cluster config file.");
353         exit(1);
354     }
355 }
356 
357 /* Lock the cluster config using flock(), and leaks the file descritor used to
358  * acquire the lock so that the file will be locked forever.
359  *
360  * This works because we always update nodes.conf with a new version
361  * in-place, reopening the file, and writing to it in place (later adjusting
362  * the length with ftruncate()).
363  *
364  * On success REDIS_OK is returned, otherwise an error is logged and
365  * the function returns REDIS_ERR to signal a lock was not acquired. */
366 int clusterLockConfig(char *filename) {
367     /* To lock it, we need to open the file in a way it is created if
368      * it does not exist, otherwise there is a race condition with other
369      * processes. */
370     int fd = open(filename,O_WRONLY|O_CREAT,0644);
371     if (fd == -1) {
372         redisLog(REDIS_WARNING,
373             "Can't open %s in order to acquire a lock: %s",
374             filename, strerror(errno));
375         return REDIS_ERR;
376     }
377 
378     if (flock(fd,LOCK_EX|LOCK_NB) == -1) {
379         if (errno == EWOULDBLOCK) {
380             redisLog(REDIS_WARNING,
381                  "Sorry, the cluster configuration file %s is already used "
382                  "by a different Redis Cluster node. Please make sure that "
383                  "different nodes use different cluster configuration "
384                  "files.", filename);
385         } else {
386             redisLog(REDIS_WARNING,
387                 "Impossible to lock %s: %s", filename, strerror(errno));
388         }
389         close(fd);
390         return REDIS_ERR;
391     }
392     /* Lock acquired: leak the 'fd' by not closing it, so that we'll retain the
393      * lock to the file as long as the process exists. */
394     return REDIS_OK;
395 }
396 
397 void clusterInit(void) {
398     int saveconf = 0;
399 
400     server.cluster = zmalloc(sizeof(clusterState));
401     server.cluster->myself = NULL;
402     server.cluster->currentEpoch = 0;
403     server.cluster->state = REDIS_CLUSTER_FAIL;
404     server.cluster->size = 1;
405     server.cluster->todo_before_sleep = 0;
406     server.cluster->nodes = dictCreate(&clusterNodesDictType,NULL);
407     server.cluster->nodes_black_list =
408         dictCreate(&clusterNodesBlackListDictType,NULL);
409     server.cluster->failover_auth_time = 0;
410     server.cluster->failover_auth_count = 0;
411     server.cluster->failover_auth_rank = 0;
412     server.cluster->failover_auth_epoch = 0;
413     server.cluster->lastVoteEpoch = 0;
414     server.cluster->stats_bus_messages_sent = 0;
415     server.cluster->stats_bus_messages_received = 0;
416     memset(server.cluster->slots,0, sizeof(server.cluster->slots));
417     clusterCloseAllSlots();
418 
419     /* Lock the cluster config file to make sure every node uses
420      * its own nodes.conf. */
421     if (clusterLockConfig(server.cluster_configfile) == REDIS_ERR)
422         exit(1);
423 
424     /* Load or create a new nodes configuration. */
425     if (clusterLoadConfig(server.cluster_configfile) == REDIS_ERR) {
426         /* No configuration found. We will just use the random name provided
427          * by the createClusterNode() function. */
428         myself = server.cluster->myself =
429             createClusterNode(NULL,REDIS_NODE_MYSELF|REDIS_NODE_MASTER);
430         redisLog(REDIS_NOTICE,"No cluster configuration found, I'm %.40s",
431             myself->name);
432         clusterAddNode(myself);
433         saveconf = 1;
434     }
435     if (saveconf) clusterSaveConfigOrDie(1);
436 
437     /* We need a listening TCP port for our cluster messaging needs. */
438     server.cfd_count = 0;
439 
440     /* Port sanity check II
441      * The other handshake port check is triggered too late to stop
442      * us from trying to use a too-high cluster port number. */
443     if (server.port > (65535-REDIS_CLUSTER_PORT_INCR)) {
444         redisLog(REDIS_WARNING, "Redis port number too high. "
445                    "Cluster communication port is 10,000 port "
446                    "numbers higher than your Redis port. "
447                    "Your Redis port number must be "
448                    "lower than 55535.");
449         exit(1);
450     }
451 
452     if (listenToPort(server.port+REDIS_CLUSTER_PORT_INCR,
453         server.cfd,&server.cfd_count) == REDIS_ERR)
454     {
455         exit(1);
456     } else {
457         int j;
458 
459         for (j = 0; j < server.cfd_count; j++) {
460             if (aeCreateFileEvent(server.el, server.cfd[j], AE_READABLE,
461                 clusterAcceptHandler, NULL) == AE_ERR)
462                     redisPanic("Unrecoverable error creating Redis Cluster "
463                                 "file event.");
464         }
465     }
466 
467     /* The slots -> keys map is a sorted set. Init it. */
468     server.cluster->slots_to_keys = zslCreate();
469 
470     /* Set myself->port to my listening port, we'll just need to discover
471      * the IP address via MEET messages. */
472     myself->port = server.port;
473 
474     resetManualFailover();
475 }
476 
477 /* Reset a node performing a soft or hard reset:
478  *
479  * 1) All other nodes are forget.
480  * 2) All the assigned / open slots are released.
481  * 3) If the node is a slave, it turns into a master.
482  * 5) Only for hard reset: a new Node ID is generated.
483  * 6) Only for hard reset: currentEpoch and configEpoch are set to 0.
484  * 7) The new configuration is saved and the cluster state updated.  */
485 void clusterReset(int hard) {
486     dictIterator *di;
487     dictEntry *de;
488     int j;
489 
490     /* Turn into master. */
491     if (nodeIsSlave(myself)) {
492         clusterSetNodeAsMaster(myself);
493         replicationUnsetMaster();
494     }
495 
496     /* Close slots, reset manual failover state. */
497     clusterCloseAllSlots();
498     resetManualFailover();
499 
500     /* Unassign all the slots. */
501     for (j = 0; j < REDIS_CLUSTER_SLOTS; j++) clusterDelSlot(j);
502 
503     /* Forget all the nodes, but myself. */
504     di = dictGetSafeIterator(server.cluster->nodes);
505     while((de = dictNext(di)) != NULL) {
506         clusterNode *node = dictGetVal(de);
507 
508         if (node == myself) continue;
509         clusterDelNode(node);
510     }
511     dictReleaseIterator(di);
512 
513     /* Hard reset only: set epochs to 0, change node ID. */
514     if (hard) {
515         sds oldname;
516 
517         server.cluster->currentEpoch = 0;
518         server.cluster->lastVoteEpoch = 0;
519         myself->configEpoch = 0;
520         redisLog(REDIS_WARNING, "configEpoch set to 0 via CLUSTER RESET HARD");
521 
522         /* To change the Node ID we need to remove the old name from the
523          * nodes table, change the ID, and re-add back with new name. */
524         oldname = sdsnewlen(myself->name, REDIS_CLUSTER_NAMELEN);
525         dictDelete(server.cluster->nodes,oldname);
526         sdsfree(oldname);
527         getRandomHexChars(myself->name, REDIS_CLUSTER_NAMELEN);
528         clusterAddNode(myself);
529     }
530 
531     /* Make sure to persist the new config and update the state. */
532     clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
533                          CLUSTER_TODO_UPDATE_STATE|
534                          CLUSTER_TODO_FSYNC_CONFIG);
535 }
536 
537 /* -----------------------------------------------------------------------------
538  * CLUSTER communication link
539  * -------------------------------------------------------------------------- */
540 
541 clusterLink *createClusterLink(clusterNode *node) {
542     clusterLink *link = zmalloc(sizeof(*link));
543     link->ctime = mstime();
544     link->sndbuf = sdsempty();
545     link->rcvbuf = sdsempty();
546     link->node = node;
547     link->fd = -1;
548     return link;
549 }
550 
551 /* Free a cluster link, but does not free the associated node of course.
552  * This function will just make sure that the original node associated
553  * with this link will have the 'link' field set to NULL. */
554 void freeClusterLink(clusterLink *link) {
555     if (link->fd != -1) {
556         aeDeleteFileEvent(server.el, link->fd, AE_WRITABLE);
557         aeDeleteFileEvent(server.el, link->fd, AE_READABLE);
558     }
559     sdsfree(link->sndbuf);
560     sdsfree(link->rcvbuf);
561     if (link->node)
562         link->node->link = NULL;
563     close(link->fd);
564     zfree(link);
565 }
566 
567 #define MAX_CLUSTER_ACCEPTS_PER_CALL 1000
568 void clusterAcceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
569     int cport, cfd;
570     int max = MAX_CLUSTER_ACCEPTS_PER_CALL;
571     char cip[REDIS_IP_STR_LEN];
572     clusterLink *link;
573     REDIS_NOTUSED(el);
574     REDIS_NOTUSED(mask);
575     REDIS_NOTUSED(privdata);
576 
577     /* If the server is starting up, don't accept cluster connections:
578      * UPDATE messages may interact with the database content. */
579     if (server.masterhost == NULL && server.loading) return;
580 
581     while(max--) {
582         cfd = anetTcpAccept(server.neterr, fd, cip, sizeof(cip), &cport);
583         if (cfd == ANET_ERR) {
584             if (errno != EWOULDBLOCK)
585                 redisLog(REDIS_VERBOSE,
586                     "Accepting cluster node: %s", server.neterr);
587             return;
588         }
589         anetNonBlock(NULL,cfd);
590         anetEnableTcpNoDelay(NULL,cfd);
591 
592         /* Use non-blocking I/O for cluster messages. */
593         redisLog(REDIS_VERBOSE,"Accepted cluster node %s:%d", cip, cport);
594         /* Create a link object we use to handle the connection.
595          * It gets passed to the readable handler when data is available.
596          * Initiallly the link->node pointer is set to NULL as we don't know
597          * which node is, but the right node is references once we know the
598          * node identity. */
599         link = createClusterLink(NULL);
600         link->fd = cfd;
601         aeCreateFileEvent(server.el,cfd,AE_READABLE,clusterReadHandler,link);
602     }
603 }
604 
605 /* -----------------------------------------------------------------------------
606  * Key space handling
607  * -------------------------------------------------------------------------- */
608 
609 /* We have 16384 hash slots. The hash slot of a given key is obtained
610  * as the least significant 14 bits of the crc16 of the key.
611  *
612  * However if the key contains the {...} pattern, only the part between
613  * { and } is hashed. This may be useful in the future to force certain
614  * keys to be in the same node (assuming no resharding is in progress). */
615 unsigned int keyHashSlot(char *key, int keylen) {
616     int s, e; /* start-end indexes of { and } */
617 
618     for (s = 0; s < keylen; s++)
619         if (key[s] == '{') break;
620 
621     /* No '{' ? Hash the whole key. This is the base case. */
622     if (s == keylen) return crc16(key,keylen) & 0x3FFF;
623 
624     /* '{' found? Check if we have the corresponding '}'. */
625     for (e = s+1; e < keylen; e++)
626         if (key[e] == '}') break;
627 
628     /* No '}' or nothing betweeen {} ? Hash the whole key. */
629     if (e == keylen || e == s+1) return crc16(key,keylen) & 0x3FFF;
630 
631     /* If we are here there is both a { and a } on its right. Hash
632      * what is in the middle between { and }. */
633     return crc16(key+s+1,e-s-1) & 0x3FFF;
634 }
635 
636 /* -----------------------------------------------------------------------------
637  * CLUSTER node API
638  * -------------------------------------------------------------------------- */
639 
640 /* Create a new cluster node, with the specified flags.
641  * If "nodename" is NULL this is considered a first handshake and a random
642  * node name is assigned to this node (it will be fixed later when we'll
643  * receive the first pong).
644  *
645  * The node is created and returned to the user, but it is not automatically
646  * added to the nodes hash table. */
647 clusterNode *createClusterNode(char *nodename, int flags) {
648     clusterNode *node = zmalloc(sizeof(*node));
649 
650     if (nodename)
651         memcpy(node->name, nodename, REDIS_CLUSTER_NAMELEN);
652     else
653         getRandomHexChars(node->name, REDIS_CLUSTER_NAMELEN);
654     node->ctime = mstime();
655     node->configEpoch = 0;
656     node->flags = flags;
657     memset(node->slots,0,sizeof(node->slots));
658     node->numslots = 0;
659     node->numslaves = 0;
660     node->slaves = NULL;
661     node->slaveof = NULL;
662     node->ping_sent = node->pong_received = 0;
663     node->fail_time = 0;
664     node->link = NULL;
665     memset(node->ip,0,sizeof(node->ip));
666     node->port = 0;
667     node->fail_reports = listCreate();
668     node->voted_time = 0;
669     node->repl_offset_time = 0;
670     node->repl_offset = 0;
671     listSetFreeMethod(node->fail_reports,zfree);
672     return node;
673 }
674 
675 /* This function is called every time we get a failure report from a node.
676  * The side effect is to populate the fail_reports list (or to update
677  * the timestamp of an existing report).
678  *
679  * 'failing' is the node that is in failure state according to the
680  * 'sender' node.
681  *
682  * The function returns 0 if it just updates a timestamp of an existing
683  * failure report from the same sender. 1 is returned if a new failure
684  * report is created. */
685 int clusterNodeAddFailureReport(clusterNode *failing, clusterNode *sender) {
686     list *l = failing->fail_reports;
687     listNode *ln;
688     listIter li;
689     clusterNodeFailReport *fr;
690 
691     /* If a failure report from the same sender already exists, just update
692      * the timestamp. */
693     listRewind(l,&li);
694     while ((ln = listNext(&li)) != NULL) {
695         fr = ln->value;
696         if (fr->node == sender) {
697             fr->time = mstime();
698             return 0;
699         }
700     }
701 
702     /* Otherwise create a new report. */
703     fr = zmalloc(sizeof(*fr));
704     fr->node = sender;
705     fr->time = mstime();
706     listAddNodeTail(l,fr);
707     return 1;
708 }
709 
710 /* Remove failure reports that are too old, where too old means reasonably
711  * older than the global node timeout. Note that anyway for a node to be
712  * flagged as FAIL we need to have a local PFAIL state that is at least
713  * older than the global node timeout, so we don't just trust the number
714  * of failure reports from other nodes. */
715 void clusterNodeCleanupFailureReports(clusterNode *node) {
716     list *l = node->fail_reports;
717     listNode *ln;
718     listIter li;
719     clusterNodeFailReport *fr;
720     mstime_t maxtime = server.cluster_node_timeout *
721                      REDIS_CLUSTER_FAIL_REPORT_VALIDITY_MULT;
722     mstime_t now = mstime();
723 
724     listRewind(l,&li);
725     while ((ln = listNext(&li)) != NULL) {
726         fr = ln->value;
727         if (now - fr->time > maxtime) listDelNode(l,ln);
728     }
729 }
730 
731 /* Remove the failing report for 'node' if it was previously considered
732  * failing by 'sender'. This function is called when a node informs us via
733  * gossip that a node is OK from its point of view (no FAIL or PFAIL flags).
734  *
735  * Note that this function is called relatively often as it gets called even
736  * when there are no nodes failing, and is O(N), however when the cluster is
737  * fine the failure reports list is empty so the function runs in constant
738  * time.
739  *
740  * The function returns 1 if the failure report was found and removed.
741  * Otherwise 0 is returned. */
742 int clusterNodeDelFailureReport(clusterNode *node, clusterNode *sender) {
743     list *l = node->fail_reports;
744     listNode *ln;
745     listIter li;
746     clusterNodeFailReport *fr;
747 
748     /* Search for a failure report from this sender. */
749     listRewind(l,&li);
750     while ((ln = listNext(&li)) != NULL) {
751         fr = ln->value;
752         if (fr->node == sender) break;
753     }
754     if (!ln) return 0; /* No failure report from this sender. */
755 
756     /* Remove the failure report. */
757     listDelNode(l,ln);
758     clusterNodeCleanupFailureReports(node);
759     return 1;
760 }
761 
762 /* Return the number of external nodes that believe 'node' is failing,
763  * not including this node, that may have a PFAIL or FAIL state for this
764  * node as well. */
765 int clusterNodeFailureReportsCount(clusterNode *node) {
766     clusterNodeCleanupFailureReports(node);
767     return listLength(node->fail_reports);
768 }
769 
770 int clusterNodeRemoveSlave(clusterNode *master, clusterNode *slave) {
771     int j;
772 
773     for (j = 0; j < master->numslaves; j++) {
774         if (master->slaves[j] == slave) {
775             memmove(master->slaves+j,master->slaves+(j+1),
776                 (master->numslaves-1)-j);
777             master->numslaves--;
778             return REDIS_OK;
779         }
780     }
781     return REDIS_ERR;
782 }
783 
784 int clusterNodeAddSlave(clusterNode *master, clusterNode *slave) {
785     int j;
786 
787     /* If it's already a slave, don't add it again. */
788     for (j = 0; j < master->numslaves; j++)
789         if (master->slaves[j] == slave) return REDIS_ERR;
790     master->slaves = zrealloc(master->slaves,
791         sizeof(clusterNode*)*(master->numslaves+1));
792     master->slaves[master->numslaves] = slave;
793     master->numslaves++;
794     return REDIS_OK;
795 }
796 
797 void clusterNodeResetSlaves(clusterNode *n) {
798     zfree(n->slaves);
799     n->numslaves = 0;
800     n->slaves = NULL;
801 }
802 
803 int clusterCountNonFailingSlaves(clusterNode *n) {
804     int j, okslaves = 0;
805 
806     for (j = 0; j < n->numslaves; j++)
807         if (!nodeFailed(n->slaves[j])) okslaves++;
808     return okslaves;
809 }
810 
811 void freeClusterNode(clusterNode *n) {
812     sds nodename;
813 
814     nodename = sdsnewlen(n->name, REDIS_CLUSTER_NAMELEN);
815     redisAssert(dictDelete(server.cluster->nodes,nodename) == DICT_OK);
816     sdsfree(nodename);
817     if (n->slaveof) clusterNodeRemoveSlave(n->slaveof, n);
818     if (n->link) freeClusterLink(n->link);
819     listRelease(n->fail_reports);
820     zfree(n);
821 }
822 
823 /* Add a node to the nodes hash table */
824 int clusterAddNode(clusterNode *node) {
825     int retval;
826 
827     retval = dictAdd(server.cluster->nodes,
828             sdsnewlen(node->name,REDIS_CLUSTER_NAMELEN), node);
829     return (retval == DICT_OK) ? REDIS_OK : REDIS_ERR;
830 }
831 
832 /* Remove a node from the cluster:
833  * 1) Mark all the nodes handled by it as unassigned.
834  * 2) Remove all the failure reports sent by this node.
835  * 3) Free the node, that will in turn remove it from the hash table
836  *    and from the list of slaves of its master, if it is a slave node.
837  */
838 void clusterDelNode(clusterNode *delnode) {
839     int j;
840     dictIterator *di;
841     dictEntry *de;
842 
843     /* 1) Mark slots as unassigned. */
844     for (j = 0; j < REDIS_CLUSTER_SLOTS; j++) {
845         if (server.cluster->importing_slots_from[j] == delnode)
846             server.cluster->importing_slots_from[j] = NULL;
847         if (server.cluster->migrating_slots_to[j] == delnode)
848             server.cluster->migrating_slots_to[j] = NULL;
849         if (server.cluster->slots[j] == delnode)
850             clusterDelSlot(j);
851     }
852 
853     /* 2) Remove failure reports. */
854     di = dictGetSafeIterator(server.cluster->nodes);
855     while((de = dictNext(di)) != NULL) {
856         clusterNode *node = dictGetVal(de);
857 
858         if (node == delnode) continue;
859         clusterNodeDelFailureReport(node,delnode);
860     }
861     dictReleaseIterator(di);
862 
863     /* 3) Remove this node from its master's slaves if needed. */
864     if (nodeIsSlave(delnode) && delnode->slaveof)
865         clusterNodeRemoveSlave(delnode->slaveof,delnode);
866 
867     /* 4) Free the node, unlinking it from the cluster. */
868     freeClusterNode(delnode);
869 }
870 
871 /* Node lookup by name */
872 clusterNode *clusterLookupNode(char *name) {
873     sds s = sdsnewlen(name, REDIS_CLUSTER_NAMELEN);
874     dictEntry *de;
875 
876     de = dictFind(server.cluster->nodes,s);
877     sdsfree(s);
878     if (de == NULL) return NULL;
879     return dictGetVal(de);
880 }
881 
882 /* This is only used after the handshake. When we connect a given IP/PORT
883  * as a result of CLUSTER MEET we don't have the node name yet, so we
884  * pick a random one, and will fix it when we receive the PONG request using
885  * this function. */
886 void clusterRenameNode(clusterNode *node, char *newname) {
887     int retval;
888     sds s = sdsnewlen(node->name, REDIS_CLUSTER_NAMELEN);
889 
890     redisLog(REDIS_DEBUG,"Renaming node %.40s into %.40s",
891         node->name, newname);
892     retval = dictDelete(server.cluster->nodes, s);
893     sdsfree(s);
894     redisAssert(retval == DICT_OK);
895     memcpy(node->name, newname, REDIS_CLUSTER_NAMELEN);
896     clusterAddNode(node);
897 }
898 
899 /* -----------------------------------------------------------------------------
900  * CLUSTER nodes blacklist
901  *
902  * The nodes blacklist is just a way to ensure that a given node with a given
903  * Node ID is not readded before some time elapsed (this time is specified
904  * in seconds in REDIS_CLUSTER_BLACKLIST_TTL).
905  *
906  * This is useful when we want to remove a node from the cluster completely:
907  * when CLUSTER FORGET is called, it also puts the node into the blacklist so
908  * that even if we receive gossip messages from other nodes that still remember
909  * about the node we want to remove, we don't re-add it before some time.
910  *
911  * Currently the REDIS_CLUSTER_BLACKLIST_TTL is set to 1 minute, this means
912  * that redis-trib has 60 seconds to send CLUSTER FORGET messages to nodes
913  * in the cluster without dealing with the problem of other nodes re-adding
914  * back the node to nodes we already sent the FORGET command to.
915  *
916  * The data structure used is a hash table with an sds string representing
917  * the node ID as key, and the time when it is ok to re-add the node as
918  * value.
919  * -------------------------------------------------------------------------- */
920 
921 #define REDIS_CLUSTER_BLACKLIST_TTL 60      /* 1 minute. */
922 
923 
924 /* Before of the addNode() or Exists() operations we always remove expired
925  * entries from the black list. This is an O(N) operation but it is not a
926  * problem since add / exists operations are called very infrequently and
927  * the hash table is supposed to contain very little elements at max.
928  * However without the cleanup during long uptimes and with some automated
929  * node add/removal procedures, entries could accumulate. */
930 void clusterBlacklistCleanup(void) {
931     dictIterator *di;
932     dictEntry *de;
933 
934     di = dictGetSafeIterator(server.cluster->nodes_black_list);
935     while((de = dictNext(di)) != NULL) {
936         int64_t expire = dictGetUnsignedIntegerVal(de);
937 
938         if (expire < server.unixtime)
939             dictDelete(server.cluster->nodes_black_list,dictGetKey(de));
940     }
941     dictReleaseIterator(di);
942 }
943 
944 /* Cleanup the blacklist and add a new node ID to the black list. */
945 void clusterBlacklistAddNode(clusterNode *node) {
946     dictEntry *de;
947     sds id = sdsnewlen(node->name,REDIS_CLUSTER_NAMELEN);
948 
949     clusterBlacklistCleanup();
950     if (dictAdd(server.cluster->nodes_black_list,id,NULL) == DICT_OK) {
951         /* If the key was added, duplicate the sds string representation of
952          * the key for the next lookup. We'll free it at the end. */
953         id = sdsdup(id);
954     }
955     de = dictFind(server.cluster->nodes_black_list,id);
956     dictSetUnsignedIntegerVal(de,time(NULL)+REDIS_CLUSTER_BLACKLIST_TTL);
957     sdsfree(id);
958 }
959 
960 /* Return non-zero if the specified node ID exists in the blacklist.
961  * You don't need to pass an sds string here, any pointer to 40 bytes
962  * will work. */
963 int clusterBlacklistExists(char *nodeid) {
964     sds id = sdsnewlen(nodeid,REDIS_CLUSTER_NAMELEN);
965     int retval;
966 
967     clusterBlacklistCleanup();
968     retval = dictFind(server.cluster->nodes_black_list,id) != NULL;
969     sdsfree(id);
970     return retval;
971 }
972 
973 /* -----------------------------------------------------------------------------
974  * CLUSTER messages exchange - PING/PONG and gossip
975  * -------------------------------------------------------------------------- */
976 
977 /* This function checks if a given node should be marked as FAIL.
978  * It happens if the following conditions are met:
979  *
980  * 1) We received enough failure reports from other master nodes via gossip.
981  *    Enough means that the majority of the masters signaled the node is
982  *    down recently.
983  * 2) We believe this node is in PFAIL state.
984  *
985  * If a failure is detected we also inform the whole cluster about this
986  * event trying to force every other node to set the FAIL flag for the node.
987  *
988  * Note that the form of agreement used here is weak, as we collect the majority
989  * of masters state during some time, and even if we force agreement by
990  * propagating the FAIL message, because of partitions we may not reach every
991  * node. However:
992  *
993  * 1) Either we reach the majority and eventually the FAIL state will propagate
994  *    to all the cluster.
995  * 2) Or there is no majority so no slave promotion will be authorized and the
996  *    FAIL flag will be cleared after some time.
997  */
998 void markNodeAsFailingIfNeeded(clusterNode *node) {
999     int failures;
1000     int needed_quorum = (server.cluster->size / 2) + 1;
1001 
1002     if (!nodeTimedOut(node)) return; /* We can reach it. */
1003     if (nodeFailed(node)) return; /* Already FAILing. */
1004 
1005     failures = clusterNodeFailureReportsCount(node);
1006     /* Also count myself as a voter if I'm a master. */
1007     if (nodeIsMaster(myself)) failures++;
1008     if (failures < needed_quorum) return; /* No weak agreement from masters. */
1009 
1010     redisLog(REDIS_NOTICE,
1011         "Marking node %.40s as failing (quorum reached).", node->name);
1012 
1013     /* Mark the node as failing. */
1014     node->flags &= ~REDIS_NODE_PFAIL;
1015     node->flags |= REDIS_NODE_FAIL;
1016     node->fail_time = mstime();
1017 
1018     /* Broadcast the failing node name to everybody, forcing all the other
1019      * reachable nodes to flag the node as FAIL. */
1020     if (nodeIsMaster(myself)) clusterSendFail(node->name);
1021     clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
1022 }
1023 
1024 /* This function is called only if a node is marked as FAIL, but we are able
1025  * to reach it again. It checks if there are the conditions to undo the FAIL
1026  * state. */
1027 void clearNodeFailureIfNeeded(clusterNode *node) {
1028     mstime_t now = mstime();
1029 
1030     redisAssert(nodeFailed(node));
1031 
1032     /* For slaves we always clear the FAIL flag if we can contact the
1033      * node again. */
1034     if (nodeIsSlave(node) || node->numslots == 0) {
1035         redisLog(REDIS_NOTICE,
1036             "Clear FAIL state for node %.40s: %s is reachable again.",
1037                 node->name,
1038                 nodeIsSlave(node) ? "slave" : "master without slots");
1039         node->flags &= ~REDIS_NODE_FAIL;
1040         clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
1041     }
1042 
1043     /* If it is a master and...
1044      * 1) The FAIL state is old enough.
1045      * 2) It is yet serving slots from our point of view (not failed over).
1046      * Apparently no one is going to fix these slots, clear the FAIL flag. */
1047     if (nodeIsMaster(node) && node->numslots > 0 &&
1048         (now - node->fail_time) >
1049         (server.cluster_node_timeout * REDIS_CLUSTER_FAIL_UNDO_TIME_MULT))
1050     {
1051         redisLog(REDIS_NOTICE,
1052             "Clear FAIL state for node %.40s: is reachable again and nobody is serving its slots after some time.",
1053                 node->name);
1054         node->flags &= ~REDIS_NODE_FAIL;
1055         clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
1056     }
1057 }
1058 
1059 /* Return true if we already have a node in HANDSHAKE state matching the
1060  * specified ip address and port number. This function is used in order to
1061  * avoid adding a new handshake node for the same address multiple times. */
1062 int clusterHandshakeInProgress(char *ip, int port) {
1063     dictIterator *di;
1064     dictEntry *de;
1065 
1066     di = dictGetSafeIterator(server.cluster->nodes);
1067     while((de = dictNext(di)) != NULL) {
1068         clusterNode *node = dictGetVal(de);
1069 
1070         if (!nodeInHandshake(node)) continue;
1071         if (!strcasecmp(node->ip,ip) && node->port == port) break;
1072     }
1073     dictReleaseIterator(di);
1074     return de != NULL;
1075 }
1076 
1077 /* Start an handshake with the specified address if there is not one
1078  * already in progress. Returns non-zero if the handshake was actually
1079  * started. On error zero is returned and errno is set to one of the
1080  * following values:
1081  *
1082  * EAGAIN - There is already an handshake in progress for this address.
1083  * EINVAL - IP or port are not valid. */
1084 int clusterStartHandshake(char *ip, int port) {
1085     clusterNode *n;
1086     char norm_ip[REDIS_IP_STR_LEN];
1087     struct sockaddr_storage sa;
1088 
1089     /* IP sanity check */
1090     if (inet_pton(AF_INET,ip,
1091             &(((struct sockaddr_in *)&sa)->sin_addr)))
1092     {
1093         sa.ss_family = AF_INET;
1094     } else if (inet_pton(AF_INET6,ip,
1095             &(((struct sockaddr_in6 *)&sa)->sin6_addr)))
1096     {
1097         sa.ss_family = AF_INET6;
1098     } else {
1099         errno = EINVAL;
1100         return 0;
1101     }
1102 
1103     /* Port sanity check */
1104     if (port <= 0 || port > (65535-REDIS_CLUSTER_PORT_INCR)) {
1105         errno = EINVAL;
1106         return 0;
1107     }
1108 
1109     /* Set norm_ip as the normalized string representation of the node
1110      * IP address. */
1111     if (sa.ss_family == AF_INET)
1112         inet_ntop(AF_INET,
1113             (void*)&(((struct sockaddr_in *)&sa)->sin_addr),
1114             norm_ip,REDIS_IP_STR_LEN);
1115     else
1116         inet_ntop(AF_INET6,
1117             (void*)&(((struct sockaddr_in6 *)&sa)->sin6_addr),
1118             norm_ip,REDIS_IP_STR_LEN);
1119 
1120     if (clusterHandshakeInProgress(norm_ip,port)) {
1121         errno = EAGAIN;
1122         return 0;
1123     }
1124 
1125     /* Add the node with a random address (NULL as first argument to
1126      * createClusterNode()). Everything will be fixed during the
1127      * handskake. */
1128     n = createClusterNode(NULL,REDIS_NODE_HANDSHAKE|REDIS_NODE_MEET);
1129     memcpy(n->ip,norm_ip,sizeof(n->ip));
1130     n->port = port;
1131     clusterAddNode(n);
1132     return 1;
1133 }
1134 
1135 /* Process the gossip section of PING or PONG packets.
1136  * Note that this function assumes that the packet is already sanity-checked
1137  * by the caller, not in the content of the gossip section, but in the
1138  * length. */
1139 void clusterProcessGossipSection(clusterMsg *hdr, clusterLink *link) {
1140     uint16_t count = ntohs(hdr->count);
1141     clusterMsgDataGossip *g = (clusterMsgDataGossip*) hdr->data.ping.gossip;
1142     clusterNode *sender = link->node ? link->node : clusterLookupNode(hdr->sender);
1143 
1144     while(count--) {
1145         sds ci = sdsempty();
1146         uint16_t flags = ntohs(g->flags);
1147         clusterNode *node;
1148 
1149         if (flags == 0) ci = sdscat(ci,"noflags,");
1150         if (flags & REDIS_NODE_MYSELF) ci = sdscat(ci,"myself,");
1151         if (flags & REDIS_NODE_MASTER) ci = sdscat(ci,"master,");
1152         if (flags & REDIS_NODE_SLAVE) ci = sdscat(ci,"slave,");
1153         if (flags & REDIS_NODE_PFAIL) ci = sdscat(ci,"fail?,");
1154         if (flags & REDIS_NODE_FAIL) ci = sdscat(ci,"fail,");
1155         if (flags & REDIS_NODE_HANDSHAKE) ci = sdscat(ci,"handshake,");
1156         if (flags & REDIS_NODE_NOADDR) ci = sdscat(ci,"noaddr,");
1157         if (ci[sdslen(ci)-1] == ',') ci[sdslen(ci)-1] = ' ';
1158 
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     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         okslaves = clusterCountNonFailingSlaves(node);
2676 
2677         if (okslaves == 0 && target == NULL && node->numslots > 0)
2678             target = node;
2679 
2680         if (okslaves == max_slaves) {
2681             for (j = 0; j < node->numslaves; j++) {
2682                 if (memcmp(node->slaves[j]->name,
2683                            candidate->name,
2684                            REDIS_CLUSTER_NAMELEN) < 0)
2685                 {
2686                     candidate = node->slaves[j];
2687                 }
2688             }
2689         }
2690     }
2691 
2692     /* Step 4: perform the migration if there is a target, and if I'm the
2693      * candidate. */
2694     if (target && candidate == myself) {
2695         redisLog(REDIS_WARNING,"Migrating to orphaned master %.40s",
2696             target->name);
2697         clusterSetMaster(target);
2698     }
2699 }
2700 
2701 /* -----------------------------------------------------------------------------
2702  * CLUSTER manual failover
2703  *
2704  * This are the important steps performed by slaves during a manual failover:
2705  * 1) User send CLUSTER FAILOVER command. The failover state is initialized
2706  *    setting mf_end to the millisecond unix time at which we'll abort the
2707  *    attempt.
2708  * 2) Slave sends a MFSTART message to the master requesting to pause clients
2709  *    for two times the manual failover timeout REDIS_CLUSTER_MF_TIMEOUT.
2710  *    When master is paused for manual failover, it also starts to flag
2711  *    packets with CLUSTERMSG_FLAG0_PAUSED.
2712  * 3) Slave waits for master to send its replication offset flagged as PAUSED.
2713  * 4) If slave received the offset from the master, and its offset matches,
2714  *    mf_can_start is set to 1, and clusterHandleSlaveFailover() will perform
2715  *    the failover as usually, with the difference that the vote request
2716  *    will be modified to force masters to vote for a slave that has a
2717  *    working master.
2718  *
2719  * From the point of view of the master things are simpler: when a
2720  * PAUSE_CLIENTS packet is received the master sets mf_end as well and
2721  * the sender in mf_slave. During the time limit for the manual failover
2722  * the master will just send PINGs more often to this slave, flagged with
2723  * the PAUSED flag, so that the slave will set mf_master_offset when receiving
2724  * a packet from the master with this flag set.
2725  *
2726  * The gaol of the manual failover is to perform a fast failover without
2727  * data loss due to the asynchronous master-slave replication.
2728  * -------------------------------------------------------------------------- */
2729 
2730 /* Reset the manual failover state. This works for both masters and slavesa
2731  * as all the state about manual failover is cleared.
2732  *
2733  * The function can be used both to initialize the manual failover state at
2734  * startup or to abort a manual failover in progress. */
2735 void resetManualFailover(void) {
2736     if (server.cluster->mf_end && clientsArePaused()) {
2737         server.clients_pause_end_time = 0;
2738         clientsArePaused(); /* Just use the side effect of the function. */
2739     }
2740     server.cluster->mf_end = 0; /* No manual failover in progress. */
2741     server.cluster->mf_can_start = 0;
2742     server.cluster->mf_slave = NULL;
2743     server.cluster->mf_master_offset = 0;
2744 }
2745 
2746 /* If a manual failover timed out, abort it. */
2747 void manualFailoverCheckTimeout(void) {
2748     if (server.cluster->mf_end && server.cluster->mf_end < mstime()) {
2749         redisLog(REDIS_WARNING,"Manual failover timed out.");
2750         resetManualFailover();
2751     }
2752 }
2753 
2754 /* This function is called from the cluster cron function in order to go
2755  * forward with a manual failover state machine. */
2756 void clusterHandleManualFailover(void) {
2757     /* Return ASAP if no manual failover is in progress. */
2758     if (server.cluster->mf_end == 0) return;
2759 
2760     /* If mf_can_start is non-zero, the failover was alrady triggered so the
2761      * next steps are performed by clusterHandleSlaveFailover(). */
2762     if (server.cluster->mf_can_start) return;
2763 
2764     if (server.cluster->mf_master_offset == 0) return; /* Wait for offset... */
2765 
2766     if (server.cluster->mf_master_offset == replicationGetSlaveOffset()) {
2767         /* Our replication offset matches the master replication offset
2768          * announced after clients were paused. We can start the failover. */
2769         server.cluster->mf_can_start = 1;
2770         redisLog(REDIS_WARNING,
2771             "All master replication stream processed, "
2772             "manual failover can start.");
2773     }
2774 }
2775 
2776 /* -----------------------------------------------------------------------------
2777  * CLUSTER cron job
2778  * -------------------------------------------------------------------------- */
2779 
2780 /* This is executed 10 times every second */
2781 void clusterCron(void) {
2782     dictIterator *di;
2783     dictEntry *de;
2784     int update_state = 0;
2785     int orphaned_masters; /* How many masters there are without ok slaves. */
2786     int max_slaves; /* Max number of ok slaves for a single master. */
2787     int this_slaves; /* Number of ok slaves for our master (if we are slave). */
2788     mstime_t min_pong = 0, now = mstime();
2789     clusterNode *min_pong_node = NULL;
2790     static unsigned long long iteration = 0;
2791     mstime_t handshake_timeout;
2792 
2793     iteration++; /* Number of times this function was called so far. */
2794 
2795     /* The handshake timeout is the time after which a handshake node that was
2796      * not turned into a normal node is removed from the nodes. Usually it is
2797      * just the NODE_TIMEOUT value, but when NODE_TIMEOUT is too small we use
2798      * the value of 1 second. */
2799     handshake_timeout = server.cluster_node_timeout;
2800     if (handshake_timeout < 1000) handshake_timeout = 1000;
2801 
2802     /* Check if we have disconnected nodes and re-establish the connection. */
2803     di = dictGetSafeIterator(server.cluster->nodes);
2804     while((de = dictNext(di)) != NULL) {
2805         clusterNode *node = dictGetVal(de);
2806 
2807         if (node->flags & (REDIS_NODE_MYSELF|REDIS_NODE_NOADDR)) continue;
2808 
2809         /* A Node in HANDSHAKE state has a limited lifespan equal to the
2810          * configured node timeout. */
2811         if (nodeInHandshake(node) && now - node->ctime > handshake_timeout) {
2812             freeClusterNode(node);
2813             continue;
2814         }
2815 
2816         if (node->link == NULL) {
2817             int fd;
2818             mstime_t old_ping_sent;
2819             clusterLink *link;
2820 
2821             fd = anetTcpNonBlockBindConnect(server.neterr, node->ip,
2822                 node->port+REDIS_CLUSTER_PORT_INCR, REDIS_BIND_ADDR);
2823             if (fd == -1) {
2824                 redisLog(REDIS_DEBUG, "Unable to connect to "
2825                     "Cluster Node [%s]:%d -> %s", node->ip,
2826                     node->port+REDIS_CLUSTER_PORT_INCR,
2827                     server.neterr);
2828                 continue;
2829             }
2830             link = createClusterLink(node);
2831             link->fd = fd;
2832             node->link = link;
2833             aeCreateFileEvent(server.el,link->fd,AE_READABLE,
2834                     clusterReadHandler,link);
2835             /* Queue a PING in the new connection ASAP: this is crucial
2836              * to avoid false positives in failure detection.
2837              *
2838              * If the node is flagged as MEET, we send a MEET message instead
2839              * of a PING one, to force the receiver to add us in its node
2840              * table. */
2841             old_ping_sent = node->ping_sent;
2842             clusterSendPing(link, node->flags & REDIS_NODE_MEET ?
2843                     CLUSTERMSG_TYPE_MEET : CLUSTERMSG_TYPE_PING);
2844             if (old_ping_sent) {
2845                 /* If there was an active ping before the link was
2846                  * disconnected, we want to restore the ping time, otherwise
2847                  * replaced by the clusterSendPing() call. */
2848                 node->ping_sent = old_ping_sent;
2849             }
2850             /* We can clear the flag after the first packet is sent.
2851              * If we'll never receive a PONG, we'll never send new packets
2852              * to this node. Instead after the PONG is received and we
2853              * are no longer in meet/handshake status, we want to send
2854              * normal PING packets. */
2855             node->flags &= ~REDIS_NODE_MEET;
2856 
2857             redisLog(REDIS_DEBUG,"Connecting with Node %.40s at %s:%d",
2858                     node->name, node->ip, node->port+REDIS_CLUSTER_PORT_INCR);
2859         }
2860     }
2861     dictReleaseIterator(di);
2862 
2863     /* Ping some random node 1 time every 10 iterations, so that we usually ping
2864      * one random node every second. */
2865     if (!(iteration % 10)) {
2866         int j;
2867 
2868         /* Check a few random nodes and ping the one with the oldest
2869          * pong_received time. */
2870         for (j = 0; j < 5; j++) {
2871             de = dictGetRandomKey(server.cluster->nodes);
2872             clusterNode *this = dictGetVal(de);
2873 
2874             /* Don't ping nodes disconnected or with a ping currently active. */
2875             if (this->link == NULL || this->ping_sent != 0) continue;
2876             if (this->flags & (REDIS_NODE_MYSELF|REDIS_NODE_HANDSHAKE))
2877                 continue;
2878             if (min_pong_node == NULL || min_pong > this->pong_received) {
2879                 min_pong_node = this;
2880                 min_pong = this->pong_received;
2881             }
2882         }
2883         if (min_pong_node) {
2884             redisLog(REDIS_DEBUG,"Pinging node %.40s", min_pong_node->name);
2885             clusterSendPing(min_pong_node->link, CLUSTERMSG_TYPE_PING);
2886         }
2887     }
2888 
2889     /* Iterate nodes to check if we need to flag something as failing.
2890      * This loop is also responsible to:
2891      * 1) Check if there are orphaned masters (masters without non failing
2892      *    slaves).
2893      * 2) Count the max number of non failing slaves for a single master.
2894      * 3) Count the number of slaves for our master, if we are a slave. */
2895     orphaned_masters = 0;
2896     max_slaves = 0;
2897     this_slaves = 0;
2898     di = dictGetSafeIterator(server.cluster->nodes);
2899     while((de = dictNext(di)) != NULL) {
2900         clusterNode *node = dictGetVal(de);
2901         now = mstime(); /* Use an updated time at every iteration. */
2902         mstime_t delay;
2903 
2904         if (node->flags &
2905             (REDIS_NODE_MYSELF|REDIS_NODE_NOADDR|REDIS_NODE_HANDSHAKE))
2906                 continue;
2907 
2908         /* Orphaned master check, useful only if the current instance
2909          * is a slave that may migrate to another master. */
2910         if (nodeIsSlave(myself) && nodeIsMaster(node) && !nodeFailed(node)) {
2911             int okslaves = clusterCountNonFailingSlaves(node);
2912 
2913             if (okslaves == 0 && node->numslots > 0) orphaned_masters++;
2914             if (okslaves > max_slaves) max_slaves = okslaves;
2915             if (nodeIsSlave(myself) && myself->slaveof == node)
2916                 this_slaves = okslaves;
2917         }
2918 
2919         /* If we are waiting for the PONG more than half the cluster
2920          * timeout, reconnect the link: maybe there is a connection
2921          * issue even if the node is alive. */
2922         if (node->link && /* is connected */
2923             now - node->link->ctime >
2924             server.cluster_node_timeout && /* was not already reconnected */
2925             node->ping_sent && /* we already sent a ping */
2926             node->pong_received < node->ping_sent && /* still waiting pong */
2927             /* and we are waiting for the pong more than timeout/2 */
2928             now - node->ping_sent > server.cluster_node_timeout/2)
2929         {
2930             /* Disconnect the link, it will be reconnected automatically. */
2931             freeClusterLink(node->link);
2932         }
2933 
2934         /* If we have currently no active ping in this instance, and the
2935          * received PONG is older than half the cluster timeout, send
2936          * a new ping now, to ensure all the nodes are pinged without
2937          * a too big delay. */
2938         if (node->link &&
2939             node->ping_sent == 0 &&
2940             (now - node->pong_received) > server.cluster_node_timeout/2)
2941         {
2942             clusterSendPing(node->link, CLUSTERMSG_TYPE_PING);
2943             continue;
2944         }
2945 
2946         /* If we are a master and one of the slaves requested a manual
2947          * failover, ping it continuously. */
2948         if (server.cluster->mf_end &&
2949             nodeIsMaster(myself) &&
2950             server.cluster->mf_slave == node &&
2951             node->link)
2952         {
2953             clusterSendPing(node->link, CLUSTERMSG_TYPE_PING);
2954             continue;
2955         }
2956 
2957         /* Check only if we have an active ping for this instance. */
2958         if (node->ping_sent == 0) continue;
2959 
2960         /* Compute the delay of the PONG. Note that if we already received
2961          * the PONG, then node->ping_sent is zero, so can't reach this
2962          * code at all. */
2963         delay = now - node->ping_sent;
2964 
2965         if (delay > server.cluster_node_timeout) {
2966             /* Timeout reached. Set the node as possibly failing if it is
2967              * not already in this state. */
2968             if (!(node->flags & (REDIS_NODE_PFAIL|REDIS_NODE_FAIL))) {
2969                 redisLog(REDIS_DEBUG,"*** NODE %.40s possibly failing",
2970                     node->name);
2971                 node->flags |= REDIS_NODE_PFAIL;
2972                 update_state = 1;
2973             }
2974         }
2975     }
2976     dictReleaseIterator(di);
2977 
2978     /* If we are a slave node but the replication is still turned off,
2979      * enable it if we know the address of our master and it appears to
2980      * be up. */
2981     if (nodeIsSlave(myself) &&
2982         server.masterhost == NULL &&
2983         myself->slaveof &&
2984         nodeHasAddr(myself->slaveof))
2985     {
2986         replicationSetMaster(myself->slaveof->ip, myself->slaveof->port);
2987     }
2988 
2989     /* Abourt a manual failover if the timeout is reached. */
2990     manualFailoverCheckTimeout();
2991 
2992     if (nodeIsSlave(myself)) {
2993         clusterHandleManualFailover();
2994         clusterHandleSlaveFailover();
2995         /* If there are orphaned slaves, and we are a slave among the masters
2996          * with the max number of non-failing slaves, consider migrating to
2997          * the orphaned masters. Note that it does not make sense to try
2998          * a migration if there is no master with at least *two* working
2999          * slaves. */
3000         if (orphaned_masters && max_slaves >= 2 && this_slaves == max_slaves)
3001             clusterHandleSlaveMigration(max_slaves);
3002     }
3003 
3004     if (update_state || server.cluster->state == REDIS_CLUSTER_FAIL)
3005         clusterUpdateState();
3006 }
3007 
3008 /* This function is called before the event handler returns to sleep for
3009  * events. It is useful to perform operations that must be done ASAP in
3010  * reaction to events fired but that are not safe to perform inside event
3011  * handlers, or to perform potentially expansive tasks that we need to do
3012  * a single time before replying to clients. */
3013 void clusterBeforeSleep(void) {
3014     /* Handle failover, this is needed when it is likely that there is already
3015      * the quorum from masters in order to react fast. */
3016     if (server.cluster->todo_before_sleep & CLUSTER_TODO_HANDLE_FAILOVER)
3017         clusterHandleSlaveFailover();
3018 
3019     /* Update the cluster state. */
3020     if (server.cluster->todo_before_sleep & CLUSTER_TODO_UPDATE_STATE)
3021         clusterUpdateState();
3022 
3023     /* Save the config, possibly using fsync. */
3024     if (server.cluster->todo_before_sleep & CLUSTER_TODO_SAVE_CONFIG) {
3025         int fsync = server.cluster->todo_before_sleep &
3026                     CLUSTER_TODO_FSYNC_CONFIG;
3027         clusterSaveConfigOrDie(fsync);
3028     }
3029 
3030     /* Reset our flags (not strictly needed since every single function
3031      * called for flags set should be able to clear its flag). */
3032     server.cluster->todo_before_sleep = 0;
3033 }
3034 
3035 void clusterDoBeforeSleep(int flags) {
3036     server.cluster->todo_before_sleep |= flags;
3037 }
3038 
3039 /* -----------------------------------------------------------------------------
3040  * Slots management
3041  * -------------------------------------------------------------------------- */
3042 
3043 /* Test bit 'pos' in a generic bitmap. Return 1 if the bit is set,
3044  * otherwise 0. */
3045 int bitmapTestBit(unsigned char *bitmap, int pos) {
3046     off_t byte = pos/8;
3047     int bit = pos&7;
3048     return (bitmap[byte] & (1<<bit)) != 0;
3049 }
3050 
3051 /* Set the bit at position 'pos' in a bitmap. */
3052 void bitmapSetBit(unsigned char *bitmap, int pos) {
3053     off_t byte = pos/8;
3054     int bit = pos&7;
3055     bitmap[byte] |= 1<<bit;
3056 }
3057 
3058 /* Clear the bit at position 'pos' in a bitmap. */
3059 void bitmapClearBit(unsigned char *bitmap, int pos) {
3060     off_t byte = pos/8;
3061     int bit = pos&7;
3062     bitmap[byte] &= ~(1<<bit);
3063 }
3064 
3065 /* Set the slot bit and return the old value. */
3066 int clusterNodeSetSlotBit(clusterNode *n, int slot) {
3067     int old = bitmapTestBit(n->slots,slot);
3068     bitmapSetBit(n->slots,slot);
3069     if (!old) n->numslots++;
3070     return old;
3071 }
3072 
3073 /* Clear the slot bit and return the old value. */
3074 int clusterNodeClearSlotBit(clusterNode *n, int slot) {
3075     int old = bitmapTestBit(n->slots,slot);
3076     bitmapClearBit(n->slots,slot);
3077     if (old) n->numslots--;
3078     return old;
3079 }
3080 
3081 /* Return the slot bit from the cluster node structure. */
3082 int clusterNodeGetSlotBit(clusterNode *n, int slot) {
3083     return bitmapTestBit(n->slots,slot);
3084 }
3085 
3086 /* Add the specified slot to the list of slots that node 'n' will
3087  * serve. Return REDIS_OK if the operation ended with success.
3088  * If the slot is already assigned to another instance this is considered
3089  * an error and REDIS_ERR is returned. */
3090 int clusterAddSlot(clusterNode *n, int slot) {
3091     if (server.cluster->slots[slot]) return REDIS_ERR;
3092     clusterNodeSetSlotBit(n,slot);
3093     server.cluster->slots[slot] = n;
3094     return REDIS_OK;
3095 }
3096 
3097 /* Delete the specified slot marking it as unassigned.
3098  * Returns REDIS_OK if the slot was assigned, otherwise if the slot was
3099  * already unassigned REDIS_ERR is returned. */
3100 int clusterDelSlot(int slot) {
3101     clusterNode *n = server.cluster->slots[slot];
3102 
3103     if (!n) return REDIS_ERR;
3104     redisAssert(clusterNodeClearSlotBit(n,slot) == 1);
3105     server.cluster->slots[slot] = NULL;
3106     return REDIS_OK;
3107 }
3108 
3109 /* Delete all the slots associated with the specified node.
3110  * The number of deleted slots is returned. */
3111 int clusterDelNodeSlots(clusterNode *node) {
3112     int deleted = 0, j;
3113 
3114     for (j = 0; j < REDIS_CLUSTER_SLOTS; j++) {
3115         if (clusterNodeGetSlotBit(node,j)) clusterDelSlot(j);
3116         deleted++;
3117     }
3118     return deleted;
3119 }
3120 
3121 /* Clear the migrating / importing state for all the slots.
3122  * This is useful at initialization and when turning a master into slave. */
3123 void clusterCloseAllSlots(void) {
3124     memset(server.cluster->migrating_slots_to,0,
3125         sizeof(server.cluster->migrating_slots_to));
3126     memset(server.cluster->importing_slots_from,0,
3127         sizeof(server.cluster->importing_slots_from));
3128 }
3129 
3130 /* -----------------------------------------------------------------------------
3131  * Cluster state evaluation function
3132  * -------------------------------------------------------------------------- */
3133 
3134 /* The following are defines that are only used in the evaluation function
3135  * and are based on heuristics. Actaully the main point about the rejoin and
3136  * writable delay is that they should be a few orders of magnitude larger
3137  * than the network latency. */
3138 #define REDIS_CLUSTER_MAX_REJOIN_DELAY 5000
3139 #define REDIS_CLUSTER_MIN_REJOIN_DELAY 500
3140 #define REDIS_CLUSTER_WRITABLE_DELAY 2000
3141 
3142 void clusterUpdateState(void) {
3143     int j, new_state;
3144     int unreachable_masters = 0;
3145     static mstime_t among_minority_time;
3146     static mstime_t first_call_time = 0;
3147 
3148     server.cluster->todo_before_sleep &= ~CLUSTER_TODO_UPDATE_STATE;
3149 
3150     /* If this is a master node, wait some time before turning the state
3151      * into OK, since it is not a good idea to rejoin the cluster as a writable
3152      * master, after a reboot, without giving the cluster a chance to
3153      * reconfigure this node. Note that the delay is calculated starting from
3154      * the first call to this function and not since the server start, in order
3155      * to don't count the DB loading time. */
3156     if (first_call_time == 0) first_call_time = mstime();
3157     if (nodeIsMaster(myself) &&
3158         server.cluster->state == REDIS_CLUSTER_FAIL &&
3159         mstime() - first_call_time < REDIS_CLUSTER_WRITABLE_DELAY) return;
3160 
3161     /* Start assuming the state is OK. We'll turn it into FAIL if there
3162      * are the right conditions. */
3163     new_state = REDIS_CLUSTER_OK;
3164 
3165     /* Check if all the slots are covered. */
3166     for (j = 0; j < REDIS_CLUSTER_SLOTS; j++) {
3167         if (server.cluster->slots[j] == NULL ||
3168             server.cluster->slots[j]->flags & (REDIS_NODE_FAIL))
3169         {
3170             new_state = REDIS_CLUSTER_FAIL;
3171             break;
3172         }
3173     }
3174 
3175     /* Compute the cluster size, that is the number of master nodes
3176      * serving at least a single slot.
3177      *
3178      * At the same time count the number of unreachable masters with
3179      * at least one node. */
3180     {
3181         dictIterator *di;
3182         dictEntry *de;
3183 
3184         server.cluster->size = 0;
3185         di = dictGetSafeIterator(server.cluster->nodes);
3186         while((de = dictNext(di)) != NULL) {
3187             clusterNode *node = dictGetVal(de);
3188 
3189             if (nodeIsMaster(node) && node->numslots) {
3190                 server.cluster->size++;
3191                 if (node->flags & (REDIS_NODE_FAIL|REDIS_NODE_PFAIL))
3192                     unreachable_masters++;
3193             }
3194         }
3195         dictReleaseIterator(di);
3196     }
3197 
3198     /* If we can't reach at least half the masters, change the cluster state
3199      * to FAIL, as we are not even able to mark nodes as FAIL in this side
3200      * of the netsplit because of lack of majority. */
3201     {
3202         int needed_quorum = (server.cluster->size / 2) + 1;
3203 
3204         if (unreachable_masters >= needed_quorum) {
3205             new_state = REDIS_CLUSTER_FAIL;
3206             among_minority_time = mstime();
3207         }
3208     }
3209 
3210     /* Log a state change */
3211     if (new_state != server.cluster->state) {
3212         mstime_t rejoin_delay = server.cluster_node_timeout;
3213 
3214         /* If the instance is a master and was partitioned away with the
3215          * minority, don't let it accept queries for some time after the
3216          * partition heals, to make sure there is enough time to receive
3217          * a configuration update. */
3218         if (rejoin_delay > REDIS_CLUSTER_MAX_REJOIN_DELAY)
3219             rejoin_delay = REDIS_CLUSTER_MAX_REJOIN_DELAY;
3220         if (rejoin_delay < REDIS_CLUSTER_MIN_REJOIN_DELAY)
3221             rejoin_delay = REDIS_CLUSTER_MIN_REJOIN_DELAY;
3222 
3223         if (new_state == REDIS_CLUSTER_OK &&
3224             nodeIsMaster(myself) &&
3225             mstime() - among_minority_time < rejoin_delay)
3226         {
3227             return;
3228         }
3229 
3230         /* Change the state and log the event. */
3231         redisLog(REDIS_WARNING,"Cluster state changed: %s",
3232             new_state == REDIS_CLUSTER_OK ? "ok" : "fail");
3233         server.cluster->state = new_state;
3234     }
3235 }
3236 
3237 /* This function is called after the node startup in order to verify that data
3238  * loaded from disk is in agreement with the cluster configuration:
3239  *
3240  * 1) If we find keys about hash slots we have no responsibility for, the
3241  *    following happens:
3242  *    A) If no other node is in charge according to the current cluster
3243  *       configuration, we add these slots to our node.
3244  *    B) If according to our config other nodes are already in charge for
3245  *       this lots, we set the slots as IMPORTING from our point of view
3246  *       in order to justify we have those slots, and in order to make
3247  *       redis-trib aware of the issue, so that it can try to fix it.
3248  * 2) If we find data in a DB different than DB0 we return REDIS_ERR to
3249  *    signal the caller it should quit the server with an error message
3250  *    or take other actions.
3251  *
3252  * The function always returns REDIS_OK even if it will try to correct
3253  * the error described in "1". However if data is found in DB different
3254  * from DB0, REDIS_ERR is returned.
3255  *
3256  * The function also uses the logging facility in order to warn the user
3257  * about desynchronizations between the data we have in memory and the
3258  * cluster configuration. */
3259 int verifyClusterConfigWithData(void) {
3260     int j;
3261     int update_config = 0;
3262 
3263     /* If this node is a slave, don't perform the check at all as we
3264      * completely depend on the replication stream. */
3265     if (nodeIsSlave(myself)) return REDIS_OK;
3266 
3267     /* Make sure we only have keys in DB0. */
3268     for (j = 1; j < server.dbnum; j++) {
3269         if (dictSize(server.db[j].dict)) return REDIS_ERR;
3270     }
3271 
3272     /* Check that all the slots we see populated memory have a corresponding
3273      * entry in the cluster table. Otherwise fix the table. */
3274     for (j = 0; j < REDIS_CLUSTER_SLOTS; j++) {
3275         if (!countKeysInSlot(j)) continue; /* No keys in this slot. */
3276         /* Check if we are assigned to this slot or if we are importing it.
3277          * In both cases check the next slot as the configuration makes
3278          * sense. */
3279         if (server.cluster->slots[j] == myself ||
3280             server.cluster->importing_slots_from[j] != NULL) continue;
3281 
3282         /* If we are here data and cluster config don't agree, and we have
3283          * slot 'j' populated even if we are not importing it, nor we are
3284          * assigned to this slot. Fix this condition. */
3285 
3286         update_config++;
3287         /* Case A: slot is unassigned. Take responsability for it. */
3288         if (server.cluster->slots[j] == NULL) {
3289             redisLog(REDIS_WARNING, "I've keys about slot %d that is "
3290                                     "unassigned. Taking responsability "
3291                                     "for it.",j);
3292             clusterAddSlot(myself,j);
3293         } else {
3294             redisLog(REDIS_WARNING, "I've keys about slot %d that is "
3295                                     "already assigned to a different node. "
3296                                     "Setting it in importing state.",j);
3297             server.cluster->importing_slots_from[j] = server.cluster->slots[j];
3298         }
3299     }
3300     if (update_config) clusterSaveConfigOrDie(1);
3301     return REDIS_OK;
3302 }
3303 
3304 /* -----------------------------------------------------------------------------
3305  * SLAVE nodes handling
3306  * -------------------------------------------------------------------------- */
3307 
3308 /* Set the specified node 'n' as master for this node.
3309  * If this node is currently a master, it is turned into a slave. */
3310 void clusterSetMaster(clusterNode *n) {
3311     redisAssert(n != myself);
3312     redisAssert(myself->numslots == 0);
3313 
3314     if (nodeIsMaster(myself)) {
3315         myself->flags &= ~REDIS_NODE_MASTER;
3316         myself->flags |= REDIS_NODE_SLAVE;
3317         clusterCloseAllSlots();
3318     } else {
3319         if (myself->slaveof)
3320             clusterNodeRemoveSlave(myself->slaveof,myself);
3321     }
3322     myself->slaveof = n;
3323     clusterNodeAddSlave(n,myself);
3324     replicationSetMaster(n->ip, n->port);
3325     resetManualFailover();
3326 }
3327 
3328 /* -----------------------------------------------------------------------------
3329  * CLUSTER command
3330  * -------------------------------------------------------------------------- */
3331 
3332 /* Generate a csv-alike representation of the specified cluster node.
3333  * See clusterGenNodesDescription() top comment for more information.
3334  *
3335  * The function returns the string representation as an SDS string. */
3336 sds clusterGenNodeDescription(clusterNode *node) {
3337     int j, start;
3338     sds ci;
3339 
3340     /* Node coordinates */
3341     ci = sdscatprintf(sdsempty(),"%.40s %s:%d ",
3342         node->name,
3343         node->ip,
3344         node->port);
3345 
3346     /* Flags */
3347     if (node->flags == 0) ci = sdscat(ci,"noflags,");
3348     if (node->flags & REDIS_NODE_MYSELF) ci = sdscat(ci,"myself,");
3349     if (node->flags & REDIS_NODE_MASTER) ci = sdscat(ci,"master,");
3350     if (node->flags & REDIS_NODE_SLAVE) ci = sdscat(ci,"slave,");
3351     if (node->flags & REDIS_NODE_PFAIL) ci = sdscat(ci,"fail?,");
3352     if (node->flags & REDIS_NODE_FAIL) ci = sdscat(ci,"fail,");
3353     if (node->flags & REDIS_NODE_HANDSHAKE) ci =sdscat(ci,"handshake,");
3354     if (node->flags & REDIS_NODE_NOADDR) ci = sdscat(ci,"noaddr,");
3355     if (ci[sdslen(ci)-1] == ',') ci[sdslen(ci)-1] = ' ';
3356 
3357     /* Slave of... or just "-" */
3358     if (node->slaveof)
3359         ci = sdscatprintf(ci,"%.40s ",node->slaveof->name);
3360     else
3361         ci = sdscatprintf(ci,"- ");
3362 
3363     /* Latency from the POV of this node, link status */
3364     ci = sdscatprintf(ci,"%lld %lld %llu %s",
3365         (long long) node->ping_sent,
3366         (long long) node->pong_received,
3367         (unsigned long long) node->configEpoch,
3368         (node->link || node->flags & REDIS_NODE_MYSELF) ?
3369                     "connected" : "disconnected");
3370 
3371     /* Slots served by this instance */
3372     start = -1;
3373     for (j = 0; j < REDIS_CLUSTER_SLOTS; j++) {
3374         int bit;
3375 
3376         if ((bit = clusterNodeGetSlotBit(node,j)) != 0) {
3377             if (start == -1) start = j;
3378         }
3379         if (start != -1 && (!bit || j == REDIS_CLUSTER_SLOTS-1)) {
3380             if (bit && j == REDIS_CLUSTER_SLOTS-1) j++;
3381 
3382             if (start == j-1) {
3383                 ci = sdscatprintf(ci," %d",start);
3384             } else {
3385                 ci = sdscatprintf(ci," %d-%d",start,j-1);
3386             }
3387             start = -1;
3388         }
3389     }
3390 
3391     /* Just for MYSELF node we also dump info about slots that
3392      * we are migrating to other instances or importing from other
3393      * instances. */
3394     if (node->flags & REDIS_NODE_MYSELF) {
3395         for (j = 0; j < REDIS_CLUSTER_SLOTS; j++) {
3396             if (server.cluster->migrating_slots_to[j]) {
3397                 ci = sdscatprintf(ci," [%d->-%.40s]",j,
3398                     server.cluster->migrating_slots_to[j]->name);
3399             } else if (server.cluster->importing_slots_from[j]) {
3400                 ci = sdscatprintf(ci," [%d-<-%.40s]",j,
3401                     server.cluster->importing_slots_from[j]->name);
3402             }
3403         }
3404     }
3405     return ci;
3406 }
3407 
3408 /* Generate a csv-alike representation of the nodes we are aware of,
3409  * including the "myself" node, and return an SDS string containing the
3410  * representation (it is up to the caller to free it).
3411  *
3412  * All the nodes matching at least one of the node flags specified in
3413  * "filter" are excluded from the output, so using zero as a filter will
3414  * include all the known nodes in the representation, including nodes in
3415  * the HANDSHAKE state.
3416  *
3417  * The representation obtained using this function is used for the output
3418  * of the CLUSTER NODES function, and as format for the cluster
3419  * configuration file (nodes.conf) for a given node. */
3420 sds clusterGenNodesDescription(int filter) {
3421     sds ci = sdsempty(), ni;
3422     dictIterator *di;
3423     dictEntry *de;
3424 
3425     di = dictGetSafeIterator(server.cluster->nodes);
3426     while((de = dictNext(di)) != NULL) {
3427         clusterNode *node = dictGetVal(de);
3428 
3429         if (node->flags & filter) continue;
3430         ni = clusterGenNodeDescription(node);
3431         ci = sdscatsds(ci,ni);
3432         sdsfree(ni);
3433         ci = sdscatlen(ci,"\n",1);
3434     }
3435     dictReleaseIterator(di);
3436     return ci;
3437 }
3438 
3439 int getSlotOrReply(redisClient *c, robj *o) {
3440     long long slot;
3441 
3442     if (getLongLongFromObject(o,&slot) != REDIS_OK ||
3443         slot < 0 || slot >= REDIS_CLUSTER_SLOTS)
3444     {
3445         addReplyError(c,"Invalid or out of range slot");
3446         return -1;
3447     }
3448     return (int) slot;
3449 }
3450 
3451 void clusterReplyMultiBulkSlots(redisClient *c) {
3452     /* Format: 1) 1) start slot
3453      *            2) end slot
3454      *            3) 1) master IP
3455      *               2) master port
3456      *            4) 1) replica IP
3457      *               2) replica port
3458      *           ... continued until done
3459      */
3460 
3461     int num_masters = 0;
3462     void *slot_replylen = addDeferredMultiBulkLength(c);
3463 
3464     dictEntry *de;
3465     dictIterator *di = dictGetSafeIterator(server.cluster->nodes);
3466     while((de = dictNext(di)) != NULL) {
3467         clusterNode *node = dictGetVal(de);
3468         int j = 0, start = -1;
3469 
3470         /* Skip slaves (that are iterated when producing the output of their
3471          * master) and  masters not serving any slot. */
3472         if (!nodeIsMaster(node) || node->numslots == 0) continue;
3473 
3474         for (j = 0; j < REDIS_CLUSTER_SLOTS; j++) {
3475             int bit, i;
3476 
3477             if ((bit = clusterNodeGetSlotBit(node,j)) != 0) {
3478                 if (start == -1) start = j;
3479             }
3480             if (start != -1 && (!bit || j == REDIS_CLUSTER_SLOTS-1)) {
3481                 int nested_elements = 3; /* slots (2) + master addr (1). */
3482                 void *nested_replylen = addDeferredMultiBulkLength(c);
3483 
3484                 if (bit && j == REDIS_CLUSTER_SLOTS-1) j++;
3485 
3486                 /* If slot exists in output map, add to it's list.
3487                  * else, create a new output map for this slot */
3488                 if (start == j-1) {
3489                     addReplyLongLong(c, start); /* only one slot; low==high */
3490                     addReplyLongLong(c, start);
3491                 } else {
3492                     addReplyLongLong(c, start); /* low */
3493                     addReplyLongLong(c, j-1);   /* high */
3494                 }
3495                 start = -1;
3496 
3497                 /* First node reply position is always the master */
3498                 addReplyMultiBulkLen(c, 2);
3499                 addReplyBulkCString(c, node->ip);
3500                 addReplyLongLong(c, node->port);
3501 
3502                 /* Remaining nodes in reply are replicas for slot range */
3503                 for (i = 0; i < node->numslaves; i++) {
3504                     /* This loop is copy/pasted from clusterGenNodeDescription()
3505                      * with modifications for per-slot node aggregation */
3506                     if (nodeFailed(node->slaves[i])) continue;
3507                     addReplyMultiBulkLen(c, 2);
3508                     addReplyBulkCString(c, node->slaves[i]->ip);
3509                     addReplyLongLong(c, node->slaves[i]->port);
3510                     nested_elements++;
3511                 }
3512                 setDeferredMultiBulkLength(c, nested_replylen, nested_elements);
3513                 num_masters++;
3514             }
3515         }
3516     }
3517     dictReleaseIterator(di);
3518     setDeferredMultiBulkLength(c, slot_replylen, num_masters);
3519 }
3520 
3521 void clusterCommand(redisClient *c) {
3522     if (server.cluster_enabled == 0) {
3523         addReplyError(c,"This instance has cluster support disabled");
3524         return;
3525     }
3526 
3527     if (!strcasecmp(c->argv[1]->ptr,"meet") && c->argc == 4) {
3528         long long port;
3529 
3530         if (getLongLongFromObject(c->argv[3], &port) != REDIS_OK) {
3531             addReplyErrorFormat(c,"Invalid TCP port specified: %s",
3532                                 (char*)c->argv[3]->ptr);
3533             return;
3534         }
3535 
3536         if (clusterStartHandshake(c->argv[2]->ptr,port) == 0 &&
3537             errno == EINVAL)
3538         {
3539             addReplyErrorFormat(c,"Invalid node address specified: %s:%s",
3540                             (char*)c->argv[2]->ptr, (char*)c->argv[3]->ptr);
3541         } else {
3542             addReply(c,shared.ok);
3543         }
3544     } else if (!strcasecmp(c->argv[1]->ptr,"nodes") && c->argc == 2) {
3545         /* CLUSTER NODES */
3546         robj *o;
3547         sds ci = clusterGenNodesDescription(0);
3548 
3549         o = createObject(REDIS_STRING,ci);
3550         addReplyBulk(c,o);
3551         decrRefCount(o);
3552     } else if (!strcasecmp(c->argv[1]->ptr,"slots") && c->argc == 2) {
3553         /* CLUSTER SLOTS */
3554         clusterReplyMultiBulkSlots(c);
3555     } else if (!strcasecmp(c->argv[1]->ptr,"flushslots") && c->argc == 2) {
3556         /* CLUSTER FLUSHSLOTS */
3557         if (dictSize(server.db[0].dict) != 0) {
3558             addReplyError(c,"DB must be empty to perform CLUSTER FLUSHSLOTS.");
3559             return;
3560         }
3561         clusterDelNodeSlots(myself);
3562         clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
3563         addReply(c,shared.ok);
3564     } else if ((!strcasecmp(c->argv[1]->ptr,"addslots") ||
3565                !strcasecmp(c->argv[1]->ptr,"delslots")) && c->argc >= 3)
3566     {
3567         /* CLUSTER ADDSLOTS <slot> [slot] ... */
3568         /* CLUSTER DELSLOTS <slot> [slot] ... */
3569         int j, slot;
3570         unsigned char *slots = zmalloc(REDIS_CLUSTER_SLOTS);
3571         int del = !strcasecmp(c->argv[1]->ptr,"delslots");
3572 
3573         memset(slots,0,REDIS_CLUSTER_SLOTS);
3574         /* Check that all the arguments are parsable and that all the
3575          * slots are not already busy. */
3576         for (j = 2; j < c->argc; j++) {
3577             if ((slot = getSlotOrReply(c,c->argv[j])) == -1) {
3578                 zfree(slots);
3579                 return;
3580             }
3581             if (del && server.cluster->slots[slot] == NULL) {
3582                 addReplyErrorFormat(c,"Slot %d is already unassigned", slot);
3583                 zfree(slots);
3584                 return;
3585             } else if (!del && server.cluster->slots[slot]) {
3586                 addReplyErrorFormat(c,"Slot %d is already busy", slot);
3587                 zfree(slots);
3588                 return;
3589             }
3590             if (slots[slot]++ == 1) {
3591                 addReplyErrorFormat(c,"Slot %d specified multiple times",
3592                     (int)slot);
3593                 zfree(slots);
3594                 return;
3595             }
3596         }
3597         for (j = 0; j < REDIS_CLUSTER_SLOTS; j++) {
3598             if (slots[j]) {
3599                 int retval;
3600 
3601                 /* If this slot was set as importing we can clear this
3602                  * state as now we are the real owner of the slot. */
3603                 if (server.cluster->importing_slots_from[j])
3604                     server.cluster->importing_slots_from[j] = NULL;
3605 
3606                 retval = del ? clusterDelSlot(j) :
3607                                clusterAddSlot(myself,j);
3608                 redisAssertWithInfo(c,NULL,retval == REDIS_OK);
3609             }
3610         }
3611         zfree(slots);
3612         clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
3613         addReply(c,shared.ok);
3614     } else if (!strcasecmp(c->argv[1]->ptr,"setslot") && c->argc >= 4) {
3615         /* SETSLOT 10 MIGRATING <node ID> */
3616         /* SETSLOT 10 IMPORTING <node ID> */
3617         /* SETSLOT 10 STABLE */
3618         /* SETSLOT 10 NODE <node ID> */
3619         int slot;
3620         clusterNode *n;
3621 
3622         if ((slot = getSlotOrReply(c,c->argv[2])) == -1) return;
3623 
3624         if (!strcasecmp(c->argv[3]->ptr,"migrating") && c->argc == 5) {
3625             if (server.cluster->slots[slot] != myself) {
3626                 addReplyErrorFormat(c,"I'm not the owner of hash slot %u",slot);
3627                 return;
3628             }
3629             if ((n = clusterLookupNode(c->argv[4]->ptr)) == NULL) {
3630                 addReplyErrorFormat(c,"I don't know about node %s",
3631                     (char*)c->argv[4]->ptr);
3632                 return;
3633             }
3634             server.cluster->migrating_slots_to[slot] = n;
3635         } else if (!strcasecmp(c->argv[3]->ptr,"importing") && c->argc == 5) {
3636             if (server.cluster->slots[slot] == myself) {
3637                 addReplyErrorFormat(c,
3638                     "I'm already the owner of hash slot %u",slot);
3639                 return;
3640             }
3641             if ((n = clusterLookupNode(c->argv[4]->ptr)) == NULL) {
3642                 addReplyErrorFormat(c,"I don't know about node %s",
3643                     (char*)c->argv[3]->ptr);
3644                 return;
3645             }
3646             server.cluster->importing_slots_from[slot] = n;
3647         } else if (!strcasecmp(c->argv[3]->ptr,"stable") && c->argc == 4) {
3648             /* CLUSTER SETSLOT <SLOT> STABLE */
3649             server.cluster->importing_slots_from[slot] = NULL;
3650             server.cluster->migrating_slots_to[slot] = NULL;
3651         } else if (!strcasecmp(c->argv[3]->ptr,"node") && c->argc == 5) {
3652             /* CLUSTER SETSLOT <SLOT> NODE <NODE ID> */
3653             clusterNode *n = clusterLookupNode(c->argv[4]->ptr);
3654 
3655             if (!n) {
3656                 addReplyErrorFormat(c,"Unknown node %s",
3657                     (char*)c->argv[4]->ptr);
3658                 return;
3659             }
3660             /* If this hash slot was served by 'myself' before to switch
3661              * make sure there are no longer local keys for this hash slot. */
3662             if (server.cluster->slots[slot] == myself && n != myself) {
3663                 if (countKeysInSlot(slot) != 0) {
3664                     addReplyErrorFormat(c,
3665                         "Can't assign hashslot %d to a different node "
3666                         "while I still hold keys for this hash slot.", slot);
3667                     return;
3668                 }
3669             }
3670             /* If this slot is in migrating status but we have no keys
3671              * for it assigning the slot to another node will clear
3672              * the migratig status. */
3673             if (countKeysInSlot(slot) == 0 &&
3674                 server.cluster->migrating_slots_to[slot])
3675                 server.cluster->migrating_slots_to[slot] = NULL;
3676 
3677             /* If this node was importing this slot, assigning the slot to
3678              * itself also clears the importing status. */
3679             if (n == myself &&
3680                 server.cluster->importing_slots_from[slot])
3681             {
3682                 /* This slot was manually migrated, set this node configEpoch
3683                  * to a new epoch so that the new version can be propagated
3684                  * by the cluster.
3685                  *
3686                  * Note that if this ever results in a collision with another
3687                  * node getting the same configEpoch, for example because a
3688                  * failover happens at the same time we close the slot, the
3689                  * configEpoch collision resolution will fix it assigning
3690                  * a different epoch to each node. */
3691                 uint64_t maxEpoch = clusterGetMaxEpoch();
3692 
3693                 if (myself->configEpoch == 0 ||
3694                     myself->configEpoch != maxEpoch)
3695                 {
3696                     server.cluster->currentEpoch++;
3697                     myself->configEpoch = server.cluster->currentEpoch;
3698                     clusterDoBeforeSleep(CLUSTER_TODO_FSYNC_CONFIG);
3699                     redisLog(REDIS_WARNING,
3700                         "configEpoch set to %llu after importing slot %d",
3701                         (unsigned long long) myself->configEpoch, slot);
3702                 }
3703                 server.cluster->importing_slots_from[slot] = NULL;
3704             }
3705             clusterDelSlot(slot);
3706             clusterAddSlot(n,slot);
3707         } else {
3708             addReplyError(c,
3709                 "Invalid CLUSTER SETSLOT action or number of arguments");
3710             return;
3711         }
3712         clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|CLUSTER_TODO_UPDATE_STATE);
3713         addReply(c,shared.ok);
3714     } else if (!strcasecmp(c->argv[1]->ptr,"info") && c->argc == 2) {
3715         /* CLUSTER INFO */
3716         char *statestr[] = {"ok","fail","needhelp"};
3717         int slots_assigned = 0, slots_ok = 0, slots_pfail = 0, slots_fail = 0;
3718         uint64_t myepoch;
3719         int j;
3720 
3721         for (j = 0; j < REDIS_CLUSTER_SLOTS; j++) {
3722             clusterNode *n = server.cluster->slots[j];
3723 
3724             if (n == NULL) continue;
3725             slots_assigned++;
3726             if (nodeFailed(n)) {
3727                 slots_fail++;
3728             } else if (nodeTimedOut(n)) {
3729                 slots_pfail++;
3730             } else {
3731                 slots_ok++;
3732             }
3733         }
3734 
3735         myepoch = (nodeIsSlave(myself) && myself->slaveof) ?
3736                   myself->slaveof->configEpoch : myself->configEpoch;
3737 
3738         sds info = sdscatprintf(sdsempty(),
3739             "cluster_state:%s\r\n"
3740             "cluster_slots_assigned:%d\r\n"
3741             "cluster_slots_ok:%d\r\n"
3742             "cluster_slots_pfail:%d\r\n"
3743             "cluster_slots_fail:%d\r\n"
3744             "cluster_known_nodes:%lu\r\n"
3745             "cluster_size:%d\r\n"
3746             "cluster_current_epoch:%llu\r\n"
3747             "cluster_my_epoch:%llu\r\n"
3748             "cluster_stats_messages_sent:%lld\r\n"
3749             "cluster_stats_messages_received:%lld\r\n"
3750             , statestr[server.cluster->state],
3751             slots_assigned,
3752             slots_ok,
3753             slots_pfail,
3754             slots_fail,
3755             dictSize(server.cluster->nodes),
3756             server.cluster->size,
3757             (unsigned long long) server.cluster->currentEpoch,
3758             (unsigned long long) myepoch,
3759             server.cluster->stats_bus_messages_sent,
3760             server.cluster->stats_bus_messages_received
3761         );
3762         addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
3763             (unsigned long)sdslen(info)));
3764         addReplySds(c,info);
3765         addReply(c,shared.crlf);
3766     } else if (!strcasecmp(c->argv[1]->ptr,"saveconfig") && c->argc == 2) {
3767         int retval = clusterSaveConfig(1);
3768 
3769         if (retval == 0)
3770             addReply(c,shared.ok);
3771         else
3772             addReplyErrorFormat(c,"error saving the cluster node config: %s",
3773                 strerror(errno));
3774     } else if (!strcasecmp(c->argv[1]->ptr,"keyslot") && c->argc == 3) {
3775         /* CLUSTER KEYSLOT <key> */
3776         sds key = c->argv[2]->ptr;
3777 
3778         addReplyLongLong(c,keyHashSlot(key,sdslen(key)));
3779     } else if (!strcasecmp(c->argv[1]->ptr,"countkeysinslot") && c->argc == 3) {
3780         /* CLUSTER COUNTKEYSINSLOT <slot> */
3781         long long slot;
3782 
3783         if (getLongLongFromObjectOrReply(c,c->argv[2],&slot,NULL) != REDIS_OK)
3784             return;
3785         if (slot < 0 || slot >= REDIS_CLUSTER_SLOTS) {
3786             addReplyError(c,"Invalid slot");
3787             return;
3788         }
3789         addReplyLongLong(c,countKeysInSlot(slot));
3790     } else if (!strcasecmp(c->argv[1]->ptr,"getkeysinslot") && c->argc == 4) {
3791         /* CLUSTER GETKEYSINSLOT <slot> <count> */
3792         long long maxkeys, slot;
3793         unsigned int numkeys, j;
3794         robj **keys;
3795 
3796         if (getLongLongFromObjectOrReply(c,c->argv[2],&slot,NULL) != REDIS_OK)
3797             return;
3798         if (getLongLongFromObjectOrReply(c,c->argv[3],&maxkeys,NULL)
3799             != REDIS_OK)
3800             return;
3801         if (slot < 0 || slot >= REDIS_CLUSTER_SLOTS || maxkeys < 0) {
3802             addReplyError(c,"Invalid slot or number of keys");
3803             return;
3804         }
3805 
3806         keys = zmalloc(sizeof(robj*)*maxkeys);
3807         numkeys = getKeysInSlot(slot, keys, maxkeys);
3808         addReplyMultiBulkLen(c,numkeys);
3809         for (j = 0; j < numkeys; j++) addReplyBulk(c,keys[j]);
3810         zfree(keys);
3811     } else if (!strcasecmp(c->argv[1]->ptr,"forget") && c->argc == 3) {
3812         /* CLUSTER FORGET <NODE ID> */
3813         clusterNode *n = clusterLookupNode(c->argv[2]->ptr);
3814 
3815         if (!n) {
3816             addReplyErrorFormat(c,"Unknown node %s", (char*)c->argv[2]->ptr);
3817             return;
3818         } else if (n == myself) {
3819             addReplyError(c,"I tried hard but I can't forget myself...");
3820             return;
3821         } else if (nodeIsSlave(myself) && myself->slaveof == n) {
3822             addReplyError(c,"Can't forget my master!");
3823             return;
3824         }
3825         clusterBlacklistAddNode(n);
3826         clusterDelNode(n);
3827         clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|
3828                              CLUSTER_TODO_SAVE_CONFIG);
3829         addReply(c,shared.ok);
3830     } else if (!strcasecmp(c->argv[1]->ptr,"replicate") && c->argc == 3) {
3831         /* CLUSTER REPLICATE <NODE ID> */
3832         clusterNode *n = clusterLookupNode(c->argv[2]->ptr);
3833 
3834         /* Lookup the specified node in our table. */
3835         if (!n) {
3836             addReplyErrorFormat(c,"Unknown node %s", (char*)c->argv[2]->ptr);
3837             return;
3838         }
3839 
3840         /* I can't replicate myself. */
3841         if (n == myself) {
3842             addReplyError(c,"Can't replicate myself");
3843             return;
3844         }
3845 
3846         /* Can't replicate a slave. */
3847         if (n->slaveof != NULL) {
3848             addReplyError(c,"I can only replicate a master, not a slave.");
3849             return;
3850         }
3851 
3852         /* If the instance is currently a master, it should have no assigned
3853          * slots nor keys to accept to replicate some other node.
3854          * Slaves can switch to another master without issues. */
3855         if (nodeIsMaster(myself) &&
3856             (myself->numslots != 0 || dictSize(server.db[0].dict) != 0)) {
3857             addReplyError(c,
3858                 "To set a master the node must be empty and "
3859                 "without assigned slots.");
3860             return;
3861         }
3862 
3863         /* Set the master. */
3864         clusterSetMaster(n);
3865         clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
3866         addReply(c,shared.ok);
3867     } else if (!strcasecmp(c->argv[1]->ptr,"slaves") && c->argc == 3) {
3868         /* CLUSTER SLAVES <NODE ID> */
3869         clusterNode *n = clusterLookupNode(c->argv[2]->ptr);
3870         int j;
3871 
3872         /* Lookup the specified node in our table. */
3873         if (!n) {
3874             addReplyErrorFormat(c,"Unknown node %s", (char*)c->argv[2]->ptr);
3875             return;
3876         }
3877 
3878         if (nodeIsSlave(n)) {
3879             addReplyError(c,"The specified node is not a master");
3880             return;
3881         }
3882 
3883         addReplyMultiBulkLen(c,n->numslaves);
3884         for (j = 0; j < n->numslaves; j++) {
3885             sds ni = clusterGenNodeDescription(n->slaves[j]);
3886             addReplyBulkCString(c,ni);
3887             sdsfree(ni);
3888         }
3889     } else if (!strcasecmp(c->argv[1]->ptr,"failover") &&
3890                (c->argc == 2 || c->argc == 3))
3891     {
3892         /* CLUSTER FAILOVER [FORCE] */
3893         int force = 0;
3894 
3895         if (c->argc == 3) {
3896             if (!strcasecmp(c->argv[2]->ptr,"force")) {
3897                 force = 1;
3898             } else {
3899                 addReply(c,shared.syntaxerr);
3900                 return;
3901             }
3902         }
3903 
3904         if (nodeIsMaster(myself)) {
3905             addReplyError(c,"You should send CLUSTER FAILOVER to a slave");
3906             return;
3907         } else if (!force &&
3908                    (myself->slaveof == NULL || nodeFailed(myself->slaveof) ||
3909                    myself->slaveof->link == NULL))
3910         {
3911             addReplyError(c,"Master is down or failed, "
3912                             "please use CLUSTER FAILOVER FORCE");
3913             return;
3914         }
3915         resetManualFailover();
3916         server.cluster->mf_end = mstime() + REDIS_CLUSTER_MF_TIMEOUT;
3917 
3918         /* If this is a forced failover, we don't need to talk with our master
3919          * to agree about the offset. We just failover taking over it without
3920          * coordination. */
3921         if (force) {
3922             server.cluster->mf_can_start = 1;
3923         } else {
3924             clusterSendMFStart(myself->slaveof);
3925         }
3926         redisLog(REDIS_WARNING,"Manual failover user request accepted.");
3927         addReply(c,shared.ok);
3928     } else if (!strcasecmp(c->argv[1]->ptr,"set-config-epoch") && c->argc == 3)
3929     {
3930         /* CLUSTER SET-CONFIG-EPOCH <epoch>
3931          *
3932          * The user is allowed to set the config epoch only when a node is
3933          * totally fresh: no config epoch, no other known node, and so forth.
3934          * This happens at cluster creation time to start with a cluster where
3935          * every node has a different node ID, without to rely on the conflicts
3936          * resolution system which is too slow when a big cluster is created. */
3937         long long epoch;
3938 
3939         if (getLongLongFromObjectOrReply(c,c->argv[2],&epoch,NULL) != REDIS_OK)
3940             return;
3941 
3942         if (epoch < 0) {
3943             addReplyErrorFormat(c,"Invalid config epoch specified: %lld",epoch);
3944         } else if (dictSize(server.cluster->nodes) > 1) {
3945             addReplyError(c,"The user can assign a config epoch only when the "
3946                             "node does not know any other node.");
3947         } else if (myself->configEpoch != 0) {
3948             addReplyError(c,"Node config epoch is already non-zero");
3949         } else {
3950             myself->configEpoch = epoch;
3951             redisLog(REDIS_WARNING,
3952                 "configEpoch set to %llu via CLUSTER SET-CONFIG-EPOCH",
3953                 (unsigned long long) myself->configEpoch);
3954 
3955             if (server.cluster->currentEpoch < epoch)
3956                 server.cluster->currentEpoch = epoch;
3957             /* No need to fsync the config here since in the unlucky event
3958              * of a failure to persist the config, the conflict resolution code
3959              * will assign an unique config to this node. */
3960             clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|
3961                                  CLUSTER_TODO_SAVE_CONFIG);
3962             addReply(c,shared.ok);
3963         }
3964     } else if (!strcasecmp(c->argv[1]->ptr,"reset") &&
3965                (c->argc == 2 || c->argc == 3))
3966     {
3967         /* CLUSTER RESET [SOFT|HARD] */
3968         int hard = 0;
3969 
3970         /* Parse soft/hard argument. Default is soft. */
3971         if (c->argc == 3) {
3972             if (!strcasecmp(c->argv[2]->ptr,"hard")) {
3973                 hard = 1;
3974             } else if (!strcasecmp(c->argv[2]->ptr,"soft")) {
3975                 hard = 0;
3976             } else {
3977                 addReply(c,shared.syntaxerr);
3978                 return;
3979             }
3980         }
3981 
3982         /* Slaves can be reset while containing data, but not master nodes
3983          * that must be empty. */
3984         if (nodeIsMaster(myself) && dictSize(c->db->dict) != 0) {
3985             addReplyError(c,"CLUSTER RESET can't be called with "
3986                             "master nodes containing keys");
3987             return;
3988         }
3989         clusterReset(hard);
3990         addReply(c,shared.ok);
3991     } else {
3992         addReplyError(c,"Wrong CLUSTER subcommand or number of arguments");
3993     }
3994 }
3995 
3996 /* -----------------------------------------------------------------------------
3997  * DUMP, RESTORE and MIGRATE commands
3998  * -------------------------------------------------------------------------- */
3999 
4000 /* Generates a DUMP-format representation of the object 'o', adding it to the
4001  * io stream pointed by 'rio'. This function can't fail. */
4002 void createDumpPayload(rio *payload, robj *o) {
4003     unsigned char buf[2];
4004     uint64_t crc;
4005 
4006     /* Serialize the object in a RDB-like format. It consist of an object type
4007      * byte followed by the serialized object. This is understood by RESTORE. */
4008     rioInitWithBuffer(payload,sdsempty());
4009     redisAssert(rdbSaveObjectType(payload,o));
4010     redisAssert(rdbSaveObject(payload,o));
4011 
4012     /* Write the footer, this is how it looks like:
4013      * ----------------+---------------------+---------------+
4014      * ... RDB payload | 2 bytes RDB version | 8 bytes CRC64 |
4015      * ----------------+---------------------+---------------+
4016      * RDB version and CRC are both in little endian.
4017      */
4018 
4019     /* RDB version */
4020     buf[0] = REDIS_RDB_VERSION & 0xff;
4021     buf[1] = (REDIS_RDB_VERSION >> 8) & 0xff;
4022     payload->io.buffer.ptr = sdscatlen(payload->io.buffer.ptr,buf,2);
4023 
4024     /* CRC64 */
4025     crc = crc64(0,(unsigned char*)payload->io.buffer.ptr,
4026                 sdslen(payload->io.buffer.ptr));
4027     memrev64ifbe(&crc);
4028     payload->io.buffer.ptr = sdscatlen(payload->io.buffer.ptr,&crc,8);
4029 }
4030 
4031 /* Verify that the RDB version of the dump payload matches the one of this Redis
4032  * instance and that the checksum is ok.
4033  * If the DUMP payload looks valid REDIS_OK is returned, otherwise REDIS_ERR
4034  * is returned. */
4035 int verifyDumpPayload(unsigned char *p, size_t len) {
4036     unsigned char *footer;
4037     uint16_t rdbver;
4038     uint64_t crc;
4039 
4040     /* At least 2 bytes of RDB version and 8 of CRC64 should be present. */
4041     if (len < 10) return REDIS_ERR;
4042     footer = p+(len-10);
4043 
4044     /* Verify RDB version */
4045     rdbver = (footer[1] << 8) | footer[0];
4046     if (rdbver != REDIS_RDB_VERSION) return REDIS_ERR;
4047 
4048     /* Verify CRC64 */
4049     crc = crc64(0,p,len-8);
4050     memrev64ifbe(&crc);
4051     return (memcmp(&crc,footer+2,8) == 0) ? REDIS_OK : REDIS_ERR;
4052 }
4053 
4054 /* DUMP keyname
4055  * DUMP is actually not used by Redis Cluster but it is the obvious
4056  * complement of RESTORE and can be useful for different applications. */
4057 void dumpCommand(redisClient *c) {
4058     robj *o, *dumpobj;
4059     rio payload;
4060 
4061     /* Check if the key is here. */
4062     if ((o = lookupKeyRead(c->db,c->argv[1])) == NULL) {
4063         addReply(c,shared.nullbulk);
4064         return;
4065     }
4066 
4067     /* Create the DUMP encoded representation. */
4068     createDumpPayload(&payload,o);
4069 
4070     /* Transfer to the client */
4071     dumpobj = createObject(REDIS_STRING,payload.io.buffer.ptr);
4072     addReplyBulk(c,dumpobj);
4073     decrRefCount(dumpobj);
4074     return;
4075 }
4076 
4077 /* RESTORE key ttl serialized-value [REPLACE] */
4078 void restoreCommand(redisClient *c) {
4079     long long ttl;
4080     rio payload;
4081     int j, type, replace = 0;
4082     robj *obj;
4083 
4084     /* Parse additional options */
4085     for (j = 4; j < c->argc; j++) {
4086         if (!strcasecmp(c->argv[j]->ptr,"replace")) {
4087             replace = 1;
4088         } else {
4089             addReply(c,shared.syntaxerr);
4090             return;
4091         }
4092     }
4093 
4094     /* Make sure this key does not already exist here... */
4095     if (!replace && lookupKeyWrite(c->db,c->argv[1]) != NULL) {
4096         addReply(c,shared.busykeyerr);
4097         return;
4098     }
4099 
4100     /* Check if the TTL value makes sense */
4101     if (getLongLongFromObjectOrReply(c,c->argv[2],&ttl,NULL) != REDIS_OK) {
4102         return;
4103     } else if (ttl < 0) {
4104         addReplyError(c,"Invalid TTL value, must be >= 0");
4105         return;
4106     }
4107 
4108     /* Verify RDB version and data checksum. */
4109     if (verifyDumpPayload(c->argv[3]->ptr,sdslen(c->argv[3]->ptr)) == REDIS_ERR)
4110     {
4111         addReplyError(c,"DUMP payload version or checksum are wrong");
4112         return;
4113     }
4114 
4115     rioInitWithBuffer(&payload,c->argv[3]->ptr);
4116     if (((type = rdbLoadObjectType(&payload)) == -1) ||
4117         ((obj = rdbLoadObject(type,&payload)) == NULL))
4118     {
4119         addReplyError(c,"Bad data format");
4120         return;
4121     }
4122 
4123     /* Remove the old key if needed. */
4124     if (replace) dbDelete(c->db,c->argv[1]);
4125 
4126     /* Create the key and set the TTL if any */
4127     dbAdd(c->db,c->argv[1],obj);
4128     if (ttl) setExpire(c->db,c->argv[1],mstime()+ttl);
4129     signalModifiedKey(c->db,c->argv[1]);
4130     addReply(c,shared.ok);
4131     server.dirty++;
4132 }
4133 
4134 /* MIGRATE socket cache implementation.
4135  *
4136  * We take a map between host:ip and a TCP socket that we used to connect
4137  * to this instance in recent time.
4138  * This sockets are closed when the max number we cache is reached, and also
4139  * in serverCron() when they are around for more than a few seconds. */
4140 #define MIGRATE_SOCKET_CACHE_ITEMS 64 /* max num of items in the cache. */
4141 #define MIGRATE_SOCKET_CACHE_TTL 10 /* close cached socekts after 10 sec. */
4142 
4143 typedef struct migrateCachedSocket {
4144     int fd;
4145     time_t last_use_time;
4146 } migrateCachedSocket;
4147 
4148 /* Return a TCP scoket connected with the target instance, possibly returning
4149  * a cached one.
4150  *
4151  * This function is responsible of sending errors to the client if a
4152  * connection can't be established. In this case -1 is returned.
4153  * Otherwise on success the socket is returned, and the caller should not
4154  * attempt to free it after usage.
4155  *
4156  * If the caller detects an error while using the socket, migrateCloseSocket()
4157  * should be called so that the connection will be craeted from scratch
4158  * the next time. */
4159 int migrateGetSocket(redisClient *c, robj *host, robj *port, long timeout) {
4160     int fd;
4161     sds name = sdsempty();
4162     migrateCachedSocket *cs;
4163 
4164     /* Check if we have an already cached socket for this ip:port pair. */
4165     name = sdscatlen(name,host->ptr,sdslen(host->ptr));
4166     name = sdscatlen(name,":",1);
4167     name = sdscatlen(name,port->ptr,sdslen(port->ptr));
4168     cs = dictFetchValue(server.migrate_cached_sockets,name);
4169     if (cs) {
4170         sdsfree(name);
4171         cs->last_use_time = server.unixtime;
4172         return cs->fd;
4173     }
4174 
4175     /* No cached socket, create one. */
4176     if (dictSize(server.migrate_cached_sockets) == MIGRATE_SOCKET_CACHE_ITEMS) {
4177         /* Too many items, drop one at random. */
4178         dictEntry *de = dictGetRandomKey(server.migrate_cached_sockets);
4179         cs = dictGetVal(de);
4180         close(cs->fd);
4181         zfree(cs);
4182         dictDelete(server.migrate_cached_sockets,dictGetKey(de));
4183     }
4184 
4185     /* Create the socket */
4186     fd = anetTcpNonBlockConnect(server.neterr,c->argv[1]->ptr,
4187                 atoi(c->argv[2]->ptr));
4188     if (fd == -1) {
4189         sdsfree(name);
4190         addReplyErrorFormat(c,"Can't connect to target node: %s",
4191             server.neterr);
4192         return -1;
4193     }
4194     anetEnableTcpNoDelay(server.neterr,fd);
4195 
4196     /* Check if it connects within the specified timeout. */
4197     if ((aeWait(fd,AE_WRITABLE,timeout) & AE_WRITABLE) == 0) {
4198         sdsfree(name);
4199         addReplySds(c,
4200             sdsnew("-IOERR error or timeout connecting to the client\r\n"));
4201         close(fd);
4202         return -1;
4203     }
4204 
4205     /* Add to the cache and return it to the caller. */
4206     cs = zmalloc(sizeof(*cs));
4207     cs->fd = fd;
4208     cs->last_use_time = server.unixtime;
4209     dictAdd(server.migrate_cached_sockets,name,cs);
4210     return fd;
4211 }
4212 
4213 /* Free a migrate cached connection. */
4214 void migrateCloseSocket(robj *host, robj *port) {
4215     sds name = sdsempty();
4216     migrateCachedSocket *cs;
4217 
4218     name = sdscatlen(name,host->ptr,sdslen(host->ptr));
4219     name = sdscatlen(name,":",1);
4220     name = sdscatlen(name,port->ptr,sdslen(port->ptr));
4221     cs = dictFetchValue(server.migrate_cached_sockets,name);
4222     if (!cs) {
4223         sdsfree(name);
4224         return;
4225     }
4226 
4227     close(cs->fd);
4228     zfree(cs);
4229     dictDelete(server.migrate_cached_sockets,name);
4230     sdsfree(name);
4231 }
4232 
4233 void migrateCloseTimedoutSockets(void) {
4234     dictIterator *di = dictGetSafeIterator(server.migrate_cached_sockets);
4235     dictEntry *de;
4236 
4237     while((de = dictNext(di)) != NULL) {
4238         migrateCachedSocket *cs = dictGetVal(de);
4239 
4240         if ((server.unixtime - cs->last_use_time) > MIGRATE_SOCKET_CACHE_TTL) {
4241             close(cs->fd);
4242             zfree(cs);
4243             dictDelete(server.migrate_cached_sockets,dictGetKey(de));
4244         }
4245     }
4246     dictReleaseIterator(di);
4247 }
4248 
4249 /* MIGRATE host port key dbid timeout [COPY | REPLACE] */
4250 void migrateCommand(redisClient *c) {
4251     int fd, copy, replace, j;
4252     long timeout;
4253     long dbid;
4254     long long ttl, expireat;
4255     robj *o;
4256     rio cmd, payload;
4257     int retry_num = 0;
4258 
4259 try_again:
4260     /* Initialization */
4261     copy = 0;
4262     replace = 0;
4263     ttl = 0;
4264 
4265     /* Parse additional options */
4266     for (j = 6; j < c->argc; j++) {
4267         if (!strcasecmp(c->argv[j]->ptr,"copy")) {
4268             copy = 1;
4269         } else if (!strcasecmp(c->argv[j]->ptr,"replace")) {
4270             replace = 1;
4271         } else {
4272             addReply(c,shared.syntaxerr);
4273             return;
4274         }
4275     }
4276 
4277     /* Sanity check */
4278     if (getLongFromObjectOrReply(c,c->argv[5],&timeout,NULL) != REDIS_OK)
4279         return;
4280     if (getLongFromObjectOrReply(c,c->argv[4],&dbid,NULL) != REDIS_OK)
4281         return;
4282     if (timeout <= 0) timeout = 1000;
4283 
4284     /* Check if the key is here. If not we reply with success as there is
4285      * nothing to migrate (for instance the key expired in the meantime), but
4286      * we include such information in the reply string. */
4287     if ((o = lookupKeyRead(c->db,c->argv[3])) == NULL) {
4288         addReplySds(c,sdsnew("+NOKEY\r\n"));
4289         return;
4290     }
4291 
4292     /* Connect */
4293     fd = migrateGetSocket(c,c->argv[1],c->argv[2],timeout);
4294     if (fd == -1) return; /* error sent to the client by migrateGetSocket() */
4295 
4296     /* Create RESTORE payload and generate the protocol to call the command. */
4297     rioInitWithBuffer(&cmd,sdsempty());
4298     redisAssertWithInfo(c,NULL,rioWriteBulkCount(&cmd,'*',2));
4299     redisAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,"SELECT",6));
4300     redisAssertWithInfo(c,NULL,rioWriteBulkLongLong(&cmd,dbid));
4301 
4302     expireat = getExpire(c->db,c->argv[3]);
4303     if (expireat != -1) {
4304         ttl = expireat-mstime();
4305         if (ttl < 1) ttl = 1;
4306     }
4307     redisAssertWithInfo(c,NULL,rioWriteBulkCount(&cmd,'*',replace ? 5 : 4));
4308     if (server.cluster_enabled)
4309         redisAssertWithInfo(c,NULL,
4310             rioWriteBulkString(&cmd,"RESTORE-ASKING",14));
4311     else
4312         redisAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,"RESTORE",7));
4313     redisAssertWithInfo(c,NULL,sdsEncodedObject(c->argv[3]));
4314     redisAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,c->argv[3]->ptr,
4315             sdslen(c->argv[3]->ptr)));
4316     redisAssertWithInfo(c,NULL,rioWriteBulkLongLong(&cmd,ttl));
4317 
4318     /* Emit the payload argument, that is the serialized object using
4319      * the DUMP format. */
4320     createDumpPayload(&payload,o);
4321     redisAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,payload.io.buffer.ptr,
4322                                 sdslen(payload.io.buffer.ptr)));
4323     sdsfree(payload.io.buffer.ptr);
4324 
4325     /* Add the REPLACE option to the RESTORE command if it was specified
4326      * as a MIGRATE option. */
4327     if (replace)
4328         redisAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,"REPLACE",7));
4329 
4330     /* Transfer the query to the other node in 64K chunks. */
4331     errno = 0;
4332     {
4333         sds buf = cmd.io.buffer.ptr;
4334         size_t pos = 0, towrite;
4335         int nwritten = 0;
4336 
4337         while ((towrite = sdslen(buf)-pos) > 0) {
4338             towrite = (towrite > (64*1024) ? (64*1024) : towrite);
4339             nwritten = syncWrite(fd,buf+pos,towrite,timeout);
4340             if (nwritten != (signed)towrite) goto socket_wr_err;
4341             pos += nwritten;
4342         }
4343     }
4344 
4345     /* Read back the reply. */
4346     {
4347         char buf1[1024];
4348         char buf2[1024];
4349 
4350         /* Read the two replies */
4351         if (syncReadLine(fd, buf1, sizeof(buf1), timeout) <= 0)
4352             goto socket_rd_err;
4353         if (syncReadLine(fd, buf2, sizeof(buf2), timeout) <= 0)
4354             goto socket_rd_err;
4355         if (buf1[0] == '-' || buf2[0] == '-') {
4356             addReplyErrorFormat(c,"Target instance replied with error: %s",
4357                 (buf1[0] == '-') ? buf1+1 : buf2+1);
4358         } else {
4359             robj *aux;
4360 
4361             if (!copy) {
4362                 /* No COPY option: remove the local key, signal the change. */
4363                 dbDelete(c->db,c->argv[3]);
4364                 signalModifiedKey(c->db,c->argv[3]);
4365             }
4366             addReply(c,shared.ok);
4367             server.dirty++;
4368 
4369             /* Translate MIGRATE as DEL for replication/AOF. */
4370             aux = createStringObject("DEL",3);
4371             rewriteClientCommandVector(c,2,aux,c->argv[3]);
4372             decrRefCount(aux);
4373         }
4374     }
4375 
4376     sdsfree(cmd.io.buffer.ptr);
4377     return;
4378 
4379 socket_wr_err:
4380     sdsfree(cmd.io.buffer.ptr);
4381     migrateCloseSocket(c->argv[1],c->argv[2]);
4382     if (errno != ETIMEDOUT && retry_num++ == 0) goto try_again;
4383     addReplySds(c,
4384         sdsnew("-IOERR error or timeout writing to target instance\r\n"));
4385     return;
4386 
4387 socket_rd_err:
4388     sdsfree(cmd.io.buffer.ptr);
4389     migrateCloseSocket(c->argv[1],c->argv[2]);
4390     if (errno != ETIMEDOUT && retry_num++ == 0) goto try_again;
4391     addReplySds(c,
4392         sdsnew("-IOERR error or timeout reading from target node\r\n"));
4393     return;
4394 }
4395 
4396 /* -----------------------------------------------------------------------------
4397  * Cluster functions related to serving / redirecting clients
4398  * -------------------------------------------------------------------------- */
4399 
4400 /* The ASKING command is required after a -ASK redirection.
4401  * The client should issue ASKING before to actually send the command to
4402  * the target instance. See the Redis Cluster specification for more
4403  * information. */
4404 void askingCommand(redisClient *c) {
4405     if (server.cluster_enabled == 0) {
4406         addReplyError(c,"This instance has cluster support disabled");
4407         return;
4408     }
4409     c->flags |= REDIS_ASKING;
4410     addReply(c,shared.ok);
4411 }
4412 
4413 /* The READONLY command is uesd by clients to enter the read-only mode.
4414  * In this mode slaves will not redirect clients as long as clients access
4415  * with read-only commands to keys that are served by the slave's master. */
4416 void readonlyCommand(redisClient *c) {
4417     if (server.cluster_enabled == 0) {
4418         addReplyError(c,"This instance has cluster support disabled");
4419         return;
4420     }
4421     c->flags |= REDIS_READONLY;
4422     addReply(c,shared.ok);
4423 }
4424 
4425 /* The READWRITE command just clears the READONLY command state. */
4426 void readwriteCommand(redisClient *c) {
4427     c->flags &= ~REDIS_READONLY;
4428     addReply(c,shared.ok);
4429 }
4430 
4431 /* Return the pointer to the cluster node that is able to serve the command.
4432  * For the function to succeed the command should only target either:
4433  *
4434  * 1) A single key (even multiple times like LPOPRPUSH mylist mylist).
4435  * 2) Multiple keys in the same hash slot, while the slot is stable (no
4436  *    resharding in progress).
4437  *
4438  * On success the function returns the node that is able to serve the request.
4439  * If the node is not 'myself' a redirection must be perfomed. The kind of
4440  * redirection is specified setting the integer passed by reference
4441  * 'error_code', which will be set to REDIS_CLUSTER_REDIR_ASK or
4442  * REDIS_CLUSTER_REDIR_MOVED.
4443  *
4444  * When the node is 'myself' 'error_code' is set to REDIS_CLUSTER_REDIR_NONE.
4445  *
4446  * If the command fails NULL is returned, and the reason of the failure is
4447  * provided via 'error_code', which will be set to:
4448  *
4449  * REDIS_CLUSTER_REDIR_CROSS_SLOT if the request contains multiple keys that
4450  * don't belong to the same hash slot.
4451  *
4452  * REDIS_CLUSTER_REDIR_UNSTABLE if the request contains mutliple keys
4453  * belonging to the same slot, but the slot is not stable (in migration or
4454  * importing state, likely because a resharding is in progress). */
4455 clusterNode *getNodeByQuery(redisClient *c, struct redisCommand *cmd, robj **argv, int argc, int *hashslot, int *error_code) {
4456     clusterNode *n = NULL;
4457     robj *firstkey = NULL;
4458     int multiple_keys = 0;
4459     multiState *ms, _ms;
4460     multiCmd mc;
4461     int i, slot = 0, migrating_slot = 0, importing_slot = 0, missing_keys = 0;
4462 
4463     /* Set error code optimistically for the base case. */
4464     if (error_code) *error_code = REDIS_CLUSTER_REDIR_NONE;
4465 
4466     /* We handle all the cases as if they were EXEC commands, so we have
4467      * a common code path for everything */
4468     if (cmd->proc == execCommand) {
4469         /* If REDIS_MULTI flag is not set EXEC is just going to return an
4470          * error. */
4471         if (!(c->flags & REDIS_MULTI)) return myself;
4472         ms = &c->mstate;
4473     } else {
4474         /* In order to have a single codepath create a fake Multi State
4475          * structure if the client is not in MULTI/EXEC state, this way
4476          * we have a single codepath below. */
4477         ms = &_ms;
4478         _ms.commands = &mc;
4479         _ms.count = 1;
4480         mc.argv = argv;
4481         mc.argc = argc;
4482         mc.cmd = cmd;
4483     }
4484 
4485     /* Check that all the keys are in the same hash slot, and obtain this
4486      * slot and the node associated. */
4487     for (i = 0; i < ms->count; i++) {
4488         struct redisCommand *mcmd;
4489         robj **margv;
4490         int margc, *keyindex, numkeys, j;
4491 
4492         mcmd = ms->commands[i].cmd;
4493         margc = ms->commands[i].argc;
4494         margv = ms->commands[i].argv;
4495 
4496         keyindex = getKeysFromCommand(mcmd,margv,margc,&numkeys);
4497         for (j = 0; j < numkeys; j++) {
4498             robj *thiskey = margv[keyindex[j]];
4499             int thisslot = keyHashSlot((char*)thiskey->ptr,
4500                                        sdslen(thiskey->ptr));
4501 
4502             if (firstkey == NULL) {
4503                 /* This is the first key we see. Check what is the slot
4504                  * and node. */
4505                 firstkey = thiskey;
4506                 slot = thisslot;
4507                 n = server.cluster->slots[slot];
4508                 redisAssertWithInfo(c,firstkey,n != NULL);
4509                 /* If we are migrating or importing this slot, we need to check
4510                  * if we have all the keys in the request (the only way we
4511                  * can safely serve the request, otherwise we return a TRYAGAIN
4512                  * error). To do so we set the importing/migrating state and
4513                  * increment a counter for every missing key. */
4514                 if (n == myself &&
4515                     server.cluster->migrating_slots_to[slot] != NULL)
4516                 {
4517                     migrating_slot = 1;
4518                 } else if (server.cluster->importing_slots_from[slot] != NULL) {
4519                     importing_slot = 1;
4520                 }
4521             } else {
4522                 /* If it is not the first key, make sure it is exactly
4523                  * the same key as the first we saw. */
4524                 if (!equalStringObjects(firstkey,thiskey)) {
4525                     if (slot != thisslot) {
4526                         /* Error: multiple keys from different slots. */
4527                         getKeysFreeResult(keyindex);
4528                         if (error_code)
4529                             *error_code = REDIS_CLUSTER_REDIR_CROSS_SLOT;
4530                         return NULL;
4531                     } else {
4532                         /* Flag this request as one with multiple different
4533                          * keys. */
4534                         multiple_keys = 1;
4535                     }
4536                 }
4537             }
4538 
4539             /* Migarting / Improrting slot? Count keys we don't have. */
4540             if ((migrating_slot || importing_slot) &&
4541                 lookupKeyRead(&server.db[0],thiskey) == NULL)
4542             {
4543                 missing_keys++;
4544             }
4545         }
4546         getKeysFreeResult(keyindex);
4547     }
4548 
4549     /* No key at all in command? then we can serve the request
4550      * without redirections or errors. */
4551     if (n == NULL) return myself;
4552 
4553     /* Return the hashslot by reference. */
4554     if (hashslot) *hashslot = slot;
4555 
4556     /* This request is about a slot we are migrating into another instance?
4557      * Then if we have all the keys. */
4558 
4559     /* If we don't have all the keys and we are migrating the slot, send
4560      * an ASK redirection. */
4561     if (migrating_slot && missing_keys) {
4562         if (error_code) *error_code = REDIS_CLUSTER_REDIR_ASK;
4563         return server.cluster->migrating_slots_to[slot];
4564     }
4565 
4566     /* If we are receiving the slot, and the client correctly flagged the
4567      * request as "ASKING", we can serve the request. However if the request
4568      * involves multiple keys and we don't have them all, the only option is
4569      * to send a TRYAGAIN error. */
4570     if (importing_slot &&
4571         (c->flags & REDIS_ASKING || cmd->flags & REDIS_CMD_ASKING))
4572     {
4573         if (multiple_keys && missing_keys) {
4574             if (error_code) *error_code = REDIS_CLUSTER_REDIR_UNSTABLE;
4575             return NULL;
4576         } else {
4577             return myself;
4578         }
4579     }
4580 
4581     /* Handle the read-only client case reading from a slave: if this
4582      * node is a slave and the request is about an hash slot our master
4583      * is serving, we can reply without redirection. */
4584     if (c->flags & REDIS_READONLY &&
4585         cmd->flags & REDIS_CMD_READONLY &&
4586         nodeIsSlave(myself) &&
4587         myself->slaveof == n)
4588     {
4589         return myself;
4590     }
4591 
4592     /* Base case: just return the right node. However if this node is not
4593      * myself, set error_code to MOVED since we need to issue a rediretion. */
4594     if (n != myself && error_code) *error_code = REDIS_CLUSTER_REDIR_MOVED;
4595     return n;
4596 }
4597