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