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