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