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