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