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