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