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