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