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