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 redisLog(REDIS_WARNING,"Address updated for node %.40s, now %s:%d", 1247 node->name, node->ip, node->port); 1248 1249 /* Check if this is our master and we have to change the 1250 * replication target as well. */ 1251 if (nodeIsSlave(myself) && myself->slaveof == node) 1252 replicationSetMaster(node->ip, node->port); 1253 return 1; 1254 } 1255 1256 /* Reconfigure the specified node 'n' as a master. This function is called when 1257 * a node that we believed to be a slave is now acting as master in order to 1258 * update the state of the node. */ 1259 void clusterSetNodeAsMaster(clusterNode *n) { 1260 if (nodeIsMaster(n)) return; 1261 1262 if (n->slaveof) clusterNodeRemoveSlave(n->slaveof,n); 1263 n->flags &= ~REDIS_NODE_SLAVE; 1264 n->flags |= REDIS_NODE_MASTER; 1265 n->slaveof = NULL; 1266 1267 /* Update config and state. */ 1268 clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG| 1269 CLUSTER_TODO_UPDATE_STATE); 1270 } 1271 1272 /* This function is called when we receive a master configuration via a 1273 * PING, PONG or UPDATE packet. What we receive is a node, a configEpoch of the 1274 * node, and the set of slots claimed under this configEpoch. 1275 * 1276 * What we do is to rebind the slots with newer configuration compared to our 1277 * local configuration, and if needed, we turn ourself into a replica of the 1278 * node (see the function comments for more info). 1279 * 1280 * The 'sender' is the node for which we received a configuration update. 1281 * Sometimes it is not actaully the "Sender" of the information, like in the case 1282 * we receive the info via an UPDATE packet. */ 1283 void clusterUpdateSlotsConfigWith(clusterNode *sender, uint64_t senderConfigEpoch, unsigned char *slots) { 1284 int j; 1285 clusterNode *curmaster, *newmaster = NULL; 1286 /* The dirty slots list is a list of slots for which we lose the ownership 1287 * while having still keys inside. This usually happens after a failover 1288 * or after a manual cluster reconfiguration operated by the admin. 1289 * 1290 * If the update message is not able to demote a master to slave (in this 1291 * case we'll resync with the master updating the whole key space), we 1292 * need to delete all the keys in the slots we lost ownership. */ 1293 uint16_t dirty_slots[REDIS_CLUSTER_SLOTS]; 1294 int dirty_slots_count = 0; 1295 1296 /* Here we set curmaster to this node or the node this node 1297 * replicates to if it's a slave. In the for loop we are 1298 * interested to check if slots are taken away from curmaster. */ 1299 curmaster = nodeIsMaster(myself) ? myself : myself->slaveof; 1300 1301 if (sender == myself) { 1302 redisLog(REDIS_WARNING,"Discarding UPDATE message about myself."); 1303 return; 1304 } 1305 1306 for (j = 0; j < REDIS_CLUSTER_SLOTS; j++) { 1307 if (bitmapTestBit(slots,j)) { 1308 /* The slot is already bound to the sender of this message. */ 1309 if (server.cluster->slots[j] == sender) continue; 1310 1311 /* The slot is in importing state, it should be modified only 1312 * manually via redis-trib (example: a resharding is in progress 1313 * and the migrating side slot was already closed and is advertising 1314 * a new config. We still want the slot to be closed manually). */ 1315 if (server.cluster->importing_slots_from[j]) continue; 1316 1317 /* We rebind the slot to the new node claiming it if: 1318 * 1) The slot was unassigned or the new node claims it with a 1319 * greater configEpoch. 1320 * 2) We are not currently importing the slot. */ 1321 if (server.cluster->slots[j] == NULL || 1322 server.cluster->slots[j]->configEpoch < senderConfigEpoch) 1323 { 1324 /* Was this slot mine, and still contains keys? Mark it as 1325 * a dirty slot. */ 1326 if (server.cluster->slots[j] == myself && 1327 countKeysInSlot(j) && 1328 sender != myself) 1329 { 1330 dirty_slots[dirty_slots_count] = j; 1331 dirty_slots_count++; 1332 } 1333 1334 if (server.cluster->slots[j] == curmaster) 1335 newmaster = sender; 1336 clusterDelSlot(j); 1337 clusterAddSlot(sender,j); 1338 clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG| 1339 CLUSTER_TODO_UPDATE_STATE| 1340 CLUSTER_TODO_FSYNC_CONFIG); 1341 } 1342 } 1343 } 1344 1345 /* If at least one slot was reassigned from a node to another node 1346 * with a greater configEpoch, it is possible that: 1347 * 1) We are a master left without slots. This means that we were 1348 * failed over and we should turn into a replica of the new 1349 * master. 1350 * 2) We are a slave and our master is left without slots. We need 1351 * to replicate to the new slots owner. */ 1352 if (newmaster && curmaster->numslots == 0) { 1353 redisLog(REDIS_WARNING, 1354 "Configuration change detected. Reconfiguring myself " 1355 "as a replica of %.40s", sender->name); 1356 clusterSetMaster(sender); 1357 clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG| 1358 CLUSTER_TODO_UPDATE_STATE| 1359 CLUSTER_TODO_FSYNC_CONFIG); 1360 } else if (dirty_slots_count) { 1361 /* If we are here, we received an update message which removed 1362 * ownership for certain slots we still have keys about, but still 1363 * we are serving some slots, so this master node was not demoted to 1364 * a slave. 1365 * 1366 * In order to maintain a consistent state between keys and slots 1367 * we need to remove all the keys from the slots we lost. */ 1368 for (j = 0; j < dirty_slots_count; j++) 1369 delKeysInSlot(dirty_slots[j]); 1370 } 1371 } 1372 1373 /* This function is called when this node is a master, and we receive from 1374 * another master a configuration epoch that is equal to our configuration 1375 * epoch. 1376 * 1377 * BACKGROUND 1378 * 1379 * It is not possible that different slaves get the same config 1380 * epoch during a failover election, because the slaves need to get voted 1381 * by a majority. However when we perform a manual resharding of the cluster 1382 * the node will assign a configuration epoch to itself without to ask 1383 * for agreement. Usually resharding happens when the cluster is working well 1384 * and is supervised by the sysadmin, however it is possible for a failover 1385 * to happen exactly while the node we are resharding a slot to assigns itself 1386 * a new configuration epoch, but before it is able to propagate it. 1387 * 1388 * So technically it is possible in this condition that two nodes end with 1389 * the same configuration epoch. 1390 * 1391 * Another possibility is that there are bugs in the implementation causing 1392 * this to happen. 1393 * 1394 * Moreover when a new cluster is created, all the nodes start with the same 1395 * configEpoch. This collision resolution code allows nodes to automatically 1396 * end with a different configEpoch at startup automatically. 1397 * 1398 * In all the cases, we want a mechanism that resolves this issue automatically 1399 * as a safeguard. The same configuration epoch for masters serving different 1400 * set of slots is not harmful, but it is if the nodes end serving the same 1401 * slots for some reason (manual errors or software bugs) without a proper 1402 * failover procedure. 1403 * 1404 * In general we want a system that eventually always ends with different 1405 * masters having different configuration epochs whatever happened, since 1406 * nothign is worse than a split-brain condition in a distributed system. 1407 * 1408 * BEHAVIOR 1409 * 1410 * When this function gets called, what happens is that if this node 1411 * has the lexicographically smaller Node ID compared to the other node 1412 * with the conflicting epoch (the 'sender' node), it will assign itself 1413 * the greatest configuration epoch currently detected among nodes plus 1. 1414 * 1415 * This means that even if there are multiple nodes colliding, the node 1416 * with the greatest Node ID never moves forward, so eventually all the nodes 1417 * end with a different configuration epoch. 1418 */ 1419 void clusterHandleConfigEpochCollision(clusterNode *sender) { 1420 /* Prerequisites: nodes have the same configEpoch and are both masters. */ 1421 if (sender->configEpoch != myself->configEpoch || 1422 !nodeIsMaster(sender) || !nodeIsMaster(myself)) return; 1423 /* Don't act if the colliding node has a smaller Node ID. */ 1424 if (memcmp(sender->name,myself->name,REDIS_CLUSTER_NAMELEN) <= 0) return; 1425 /* Get the next ID available at the best of this node knowledge. */ 1426 server.cluster->currentEpoch++; 1427 myself->configEpoch = server.cluster->currentEpoch; 1428 clusterSaveConfigOrDie(1); 1429 redisLog(REDIS_VERBOSE, 1430 "WARNING: configEpoch collision with node %.40s." 1431 " configEpoch set to %llu", 1432 sender->name, 1433 (unsigned long long) myself->configEpoch); 1434 } 1435 1436 /* When this function is called, there is a packet to process starting 1437 * at node->rcvbuf. Releasing the buffer is up to the caller, so this 1438 * function should just handle the higher level stuff of processing the 1439 * packet, modifying the cluster state if needed. 1440 * 1441 * The function returns 1 if the link is still valid after the packet 1442 * was processed, otherwise 0 if the link was freed since the packet 1443 * processing lead to some inconsistency error (for instance a PONG 1444 * received from the wrong sender ID). */ 1445 int clusterProcessPacket(clusterLink *link) { 1446 clusterMsg *hdr = (clusterMsg*) link->rcvbuf; 1447 uint32_t totlen = ntohl(hdr->totlen); 1448 uint16_t type = ntohs(hdr->type); 1449 uint16_t flags = ntohs(hdr->flags); 1450 uint64_t senderCurrentEpoch = 0, senderConfigEpoch = 0; 1451 clusterNode *sender; 1452 1453 server.cluster->stats_bus_messages_received++; 1454 redisLog(REDIS_DEBUG,"--- Processing packet of type %d, %lu bytes", 1455 type, (unsigned long) totlen); 1456 1457 /* Perform sanity checks */ 1458 if (totlen < 16) return 1; /* At least signature, version, totlen, count. */ 1459 if (ntohs(hdr->ver) != 0) return 1; /* Can't handle versions other than 0.*/ 1460 if (totlen > sdslen(link->rcvbuf)) return 1; 1461 if (type == CLUSTERMSG_TYPE_PING || type == CLUSTERMSG_TYPE_PONG || 1462 type == CLUSTERMSG_TYPE_MEET) 1463 { 1464 uint16_t count = ntohs(hdr->count); 1465 uint32_t explen; /* expected length of this packet */ 1466 1467 explen = sizeof(clusterMsg)-sizeof(union clusterMsgData); 1468 explen += (sizeof(clusterMsgDataGossip)*count); 1469 if (totlen != explen) return 1; 1470 } else if (type == CLUSTERMSG_TYPE_FAIL) { 1471 uint32_t explen = sizeof(clusterMsg)-sizeof(union clusterMsgData); 1472 1473 explen += sizeof(clusterMsgDataFail); 1474 if (totlen != explen) return 1; 1475 } else if (type == CLUSTERMSG_TYPE_PUBLISH) { 1476 uint32_t explen = sizeof(clusterMsg)-sizeof(union clusterMsgData); 1477 1478 explen += sizeof(clusterMsgDataPublish) + 1479 ntohl(hdr->data.publish.msg.channel_len) + 1480 ntohl(hdr->data.publish.msg.message_len); 1481 if (totlen != explen) return 1; 1482 } else if (type == CLUSTERMSG_TYPE_FAILOVER_AUTH_REQUEST || 1483 type == CLUSTERMSG_TYPE_FAILOVER_AUTH_ACK || 1484 type == CLUSTERMSG_TYPE_MFSTART) 1485 { 1486 uint32_t explen = sizeof(clusterMsg)-sizeof(union clusterMsgData); 1487 1488 if (totlen != explen) return 1; 1489 } else if (type == CLUSTERMSG_TYPE_UPDATE) { 1490 uint32_t explen = sizeof(clusterMsg)-sizeof(union clusterMsgData); 1491 1492 explen += sizeof(clusterMsgDataUpdate); 1493 if (totlen != explen) return 1; 1494 } 1495 1496 /* Check if the sender is a known node. */ 1497 sender = clusterLookupNode(hdr->sender); 1498 if (sender && !nodeInHandshake(sender)) { 1499 /* Update our curretEpoch if we see a newer epoch in the cluster. */ 1500 senderCurrentEpoch = ntohu64(hdr->currentEpoch); 1501 senderConfigEpoch = ntohu64(hdr->configEpoch); 1502 if (senderCurrentEpoch > server.cluster->currentEpoch) 1503 server.cluster->currentEpoch = senderCurrentEpoch; 1504 /* Update the sender configEpoch if it is publishing a newer one. */ 1505 if (senderConfigEpoch > sender->configEpoch) { 1506 sender->configEpoch = senderConfigEpoch; 1507 clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG| 1508 CLUSTER_TODO_FSYNC_CONFIG); 1509 } 1510 /* Update the replication offset info for this node. */ 1511 sender->repl_offset = ntohu64(hdr->offset); 1512 sender->repl_offset_time = mstime(); 1513 /* If we are a slave performing a manual failover and our master 1514 * sent its offset while already paused, populate the MF state. */ 1515 if (server.cluster->mf_end && 1516 nodeIsSlave(myself) && 1517 myself->slaveof == sender && 1518 hdr->mflags[0] & CLUSTERMSG_FLAG0_PAUSED && 1519 server.cluster->mf_master_offset == 0) 1520 { 1521 server.cluster->mf_master_offset = sender->repl_offset; 1522 redisLog(REDIS_WARNING, 1523 "Received replication offset for paused " 1524 "master manual failover: %lld", 1525 server.cluster->mf_master_offset); 1526 } 1527 } 1528 1529 /* Process packets by type. */ 1530 if (type == CLUSTERMSG_TYPE_PING || type == CLUSTERMSG_TYPE_MEET) { 1531 redisLog(REDIS_DEBUG,"Ping packet received: %p", (void*)link->node); 1532 1533 /* Add this node if it is new for us and the msg type is MEET. 1534 * In this stage we don't try to add the node with the right 1535 * flags, slaveof pointer, and so forth, as this details will be 1536 * resolved when we'll receive PONGs from the node. */ 1537 if (!sender && type == CLUSTERMSG_TYPE_MEET) { 1538 clusterNode *node; 1539 1540 node = createClusterNode(NULL,REDIS_NODE_HANDSHAKE); 1541 nodeIp2String(node->ip,link); 1542 node->port = ntohs(hdr->port); 1543 clusterAddNode(node); 1544 clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG); 1545 } 1546 1547 /* Get info from the gossip section */ 1548 clusterProcessGossipSection(hdr,link); 1549 1550 /* Anyway reply with a PONG */ 1551 clusterSendPing(link,CLUSTERMSG_TYPE_PONG); 1552 } 1553 1554 /* PING or PONG: process config information. */ 1555 if (type == CLUSTERMSG_TYPE_PING || type == CLUSTERMSG_TYPE_PONG || 1556 type == CLUSTERMSG_TYPE_MEET) 1557 { 1558 redisLog(REDIS_DEBUG,"%s packet received: %p", 1559 type == CLUSTERMSG_TYPE_PING ? "ping" : "pong", 1560 (void*)link->node); 1561 if (link->node) { 1562 if (nodeInHandshake(link->node)) { 1563 /* If we already have this node, try to change the 1564 * IP/port of the node with the new one. */ 1565 if (sender) { 1566 redisLog(REDIS_VERBOSE, 1567 "Handshake: we already know node %.40s, " 1568 "updating the address if needed.", sender->name); 1569 if (nodeUpdateAddressIfNeeded(sender,link,ntohs(hdr->port))) 1570 { 1571 clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG| 1572 CLUSTER_TODO_UPDATE_STATE); 1573 } 1574 /* Free this node as we alrady have it. This will 1575 * cause the link to be freed as well. */ 1576 freeClusterNode(link->node); 1577 return 0; 1578 } 1579 1580 /* First thing to do is replacing the random name with the 1581 * right node name if this was a handshake stage. */ 1582 clusterRenameNode(link->node, hdr->sender); 1583 redisLog(REDIS_DEBUG,"Handshake with node %.40s completed.", 1584 link->node->name); 1585 link->node->flags &= ~REDIS_NODE_HANDSHAKE; 1586 link->node->flags |= flags&(REDIS_NODE_MASTER|REDIS_NODE_SLAVE); 1587 clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG); 1588 } else if (memcmp(link->node->name,hdr->sender, 1589 REDIS_CLUSTER_NAMELEN) != 0) 1590 { 1591 /* If the reply has a non matching node ID we 1592 * disconnect this node and set it as not having an associated 1593 * address. */ 1594 redisLog(REDIS_DEBUG,"PONG contains mismatching sender ID"); 1595 link->node->flags |= REDIS_NODE_NOADDR; 1596 link->node->ip[0] = '\0'; 1597 link->node->port = 0; 1598 freeClusterLink(link); 1599 clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG); 1600 return 0; 1601 } 1602 } 1603 1604 /* Update the node address if it changed. */ 1605 if (sender && type == CLUSTERMSG_TYPE_PING && 1606 !nodeInHandshake(sender) && 1607 nodeUpdateAddressIfNeeded(sender,link,ntohs(hdr->port))) 1608 { 1609 clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG| 1610 CLUSTER_TODO_UPDATE_STATE); 1611 } 1612 1613 /* Update our info about the node */ 1614 if (link->node && type == CLUSTERMSG_TYPE_PONG) { 1615 link->node->pong_received = mstime(); 1616 link->node->ping_sent = 0; 1617 1618 /* The PFAIL condition can be reversed without external 1619 * help if it is momentary (that is, if it does not 1620 * turn into a FAIL state). 1621 * 1622 * The FAIL condition is also reversible under specific 1623 * conditions detected by clearNodeFailureIfNeeded(). */ 1624 if (nodeTimedOut(link->node)) { 1625 link->node->flags &= ~REDIS_NODE_PFAIL; 1626 clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG| 1627 CLUSTER_TODO_UPDATE_STATE); 1628 } else if (nodeFailed(link->node)) { 1629 clearNodeFailureIfNeeded(link->node); 1630 } 1631 } 1632 1633 /* Check for role switch: slave -> master or master -> slave. */ 1634 if (sender) { 1635 if (!memcmp(hdr->slaveof,REDIS_NODE_NULL_NAME, 1636 sizeof(hdr->slaveof))) 1637 { 1638 /* Node is a master. */ 1639 clusterSetNodeAsMaster(sender); 1640 } else { 1641 /* Node is a slave. */ 1642 clusterNode *master = clusterLookupNode(hdr->slaveof); 1643 1644 if (nodeIsMaster(sender)) { 1645 /* Master turned into a slave! Reconfigure the node. */ 1646 clusterDelNodeSlots(sender); 1647 sender->flags &= ~REDIS_NODE_MASTER; 1648 sender->flags |= REDIS_NODE_SLAVE; 1649 1650 /* Remove the list of slaves from the node. */ 1651 if (sender->numslaves) clusterNodeResetSlaves(sender); 1652 1653 /* Update config and state. */ 1654 clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG| 1655 CLUSTER_TODO_UPDATE_STATE); 1656 } 1657 1658 /* Master node changed for this slave? */ 1659 if (master && sender->slaveof != master) { 1660 if (sender->slaveof) 1661 clusterNodeRemoveSlave(sender->slaveof,sender); 1662 clusterNodeAddSlave(master,sender); 1663 sender->slaveof = master; 1664 1665 /* Update config. */ 1666 clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG); 1667 } 1668 } 1669 } 1670 1671 /* Update our info about served slots. 1672 * 1673 * Note: this MUST happen after we update the master/slave state 1674 * so that REDIS_NODE_MASTER flag will be set. */ 1675 1676 /* Many checks are only needed if the set of served slots this 1677 * instance claims is different compared to the set of slots we have 1678 * for it. Check this ASAP to avoid other computational expansive 1679 * checks later. */ 1680 clusterNode *sender_master = NULL; /* Sender or its master if slave. */ 1681 int dirty_slots = 0; /* Sender claimed slots don't match my view? */ 1682 1683 if (sender) { 1684 sender_master = nodeIsMaster(sender) ? sender : sender->slaveof; 1685 if (sender_master) { 1686 dirty_slots = memcmp(sender_master->slots, 1687 hdr->myslots,sizeof(hdr->myslots)) != 0; 1688 } 1689 } 1690 1691 /* 1) If the sender of the message is a master, and we detected that 1692 * the set of slots it claims changed, scan the slots to see if we 1693 * need to update our configuration. */ 1694 if (sender && nodeIsMaster(sender) && dirty_slots) 1695 clusterUpdateSlotsConfigWith(sender,senderConfigEpoch,hdr->myslots); 1696 1697 /* 2) We also check for the reverse condition, that is, the sender 1698 * claims to serve slots we know are served by a master with a 1699 * greater configEpoch. If this happens we inform the sender. 1700 * 1701 * This is useful because sometimes after a partition heals, a 1702 * reappearing master may be the last one to claim a given set of 1703 * hash slots, but with a configuration that other instances know to 1704 * be deprecated. Example: 1705 * 1706 * A and B are master and slave for slots 1,2,3. 1707 * A is partitioned away, B gets promoted. 1708 * B is partitioned away, and A returns available. 1709 * 1710 * Usually B would PING A publishing its set of served slots and its 1711 * configEpoch, but because of the partition B can't inform A of the 1712 * new configuration, so other nodes that have an updated table must 1713 * do it. In this way A will stop to act as a master (or can try to 1714 * failover if there are the conditions to win the election). */ 1715 if (sender && dirty_slots) { 1716 int j; 1717 1718 for (j = 0; j < REDIS_CLUSTER_SLOTS; j++) { 1719 if (bitmapTestBit(hdr->myslots,j)) { 1720 if (server.cluster->slots[j] == sender || 1721 server.cluster->slots[j] == NULL) continue; 1722 if (server.cluster->slots[j]->configEpoch > 1723 senderConfigEpoch) 1724 { 1725 redisLog(REDIS_VERBOSE, 1726 "Node %.40s has old slots configuration, sending " 1727 "an UPDATE message about %.40s", 1728 sender->name, server.cluster->slots[j]->name); 1729 clusterSendUpdate(sender->link, 1730 server.cluster->slots[j]); 1731 1732 /* TODO: instead of exiting the loop send every other 1733 * UPDATE packet for other nodes that are the new owner 1734 * of sender's slots. */ 1735 break; 1736 } 1737 } 1738 } 1739 } 1740 1741 /* If our config epoch collides with the sender's try to fix 1742 * the problem. */ 1743 if (sender && 1744 nodeIsMaster(myself) && nodeIsMaster(sender) && 1745 senderConfigEpoch == myself->configEpoch) 1746 { 1747 clusterHandleConfigEpochCollision(sender); 1748 } 1749 1750 /* Get info from the gossip section */ 1751 clusterProcessGossipSection(hdr,link); 1752 } else if (type == CLUSTERMSG_TYPE_FAIL) { 1753 clusterNode *failing; 1754 1755 if (sender) { 1756 failing = clusterLookupNode(hdr->data.fail.about.nodename); 1757 if (failing && 1758 !(failing->flags & (REDIS_NODE_FAIL|REDIS_NODE_MYSELF))) 1759 { 1760 redisLog(REDIS_NOTICE, 1761 "FAIL message received from %.40s about %.40s", 1762 hdr->sender, hdr->data.fail.about.nodename); 1763 failing->flags |= REDIS_NODE_FAIL; 1764 failing->fail_time = mstime(); 1765 failing->flags &= ~REDIS_NODE_PFAIL; 1766 clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG| 1767 CLUSTER_TODO_UPDATE_STATE); 1768 } 1769 } else { 1770 redisLog(REDIS_NOTICE, 1771 "Ignoring FAIL message from unknonw node %.40s about %.40s", 1772 hdr->sender, hdr->data.fail.about.nodename); 1773 } 1774 } else if (type == CLUSTERMSG_TYPE_PUBLISH) { 1775 robj *channel, *message; 1776 uint32_t channel_len, message_len; 1777 1778 /* Don't bother creating useless objects if there are no 1779 * Pub/Sub subscribers. */ 1780 if (dictSize(server.pubsub_channels) || 1781 listLength(server.pubsub_patterns)) 1782 { 1783 channel_len = ntohl(hdr->data.publish.msg.channel_len); 1784 message_len = ntohl(hdr->data.publish.msg.message_len); 1785 channel = createStringObject( 1786 (char*)hdr->data.publish.msg.bulk_data,channel_len); 1787 message = createStringObject( 1788 (char*)hdr->data.publish.msg.bulk_data+channel_len, 1789 message_len); 1790 pubsubPublishMessage(channel,message); 1791 decrRefCount(channel); 1792 decrRefCount(message); 1793 } 1794 } else if (type == CLUSTERMSG_TYPE_FAILOVER_AUTH_REQUEST) { 1795 if (!sender) return 1; /* We don't know that node. */ 1796 clusterSendFailoverAuthIfNeeded(sender,hdr); 1797 } else if (type == CLUSTERMSG_TYPE_FAILOVER_AUTH_ACK) { 1798 if (!sender) return 1; /* We don't know that node. */ 1799 /* We consider this vote only if the sender is a master serving 1800 * a non zero number of slots, and its currentEpoch is greater or 1801 * equal to epoch where this node started the election. */ 1802 if (nodeIsMaster(sender) && sender->numslots > 0 && 1803 senderCurrentEpoch >= server.cluster->failover_auth_epoch) 1804 { 1805 server.cluster->failover_auth_count++; 1806 /* Maybe we reached a quorum here, set a flag to make sure 1807 * we check ASAP. */ 1808 clusterDoBeforeSleep(CLUSTER_TODO_HANDLE_FAILOVER); 1809 } 1810 } else if (type == CLUSTERMSG_TYPE_MFSTART) { 1811 /* This message is acceptable only if I'm a master and the sender 1812 * is one of my slaves. */ 1813 if (!sender || sender->slaveof != myself) return 1; 1814 /* Manual failover requested from slaves. Initialize the state 1815 * accordingly. */ 1816 resetManualFailover(); 1817 server.cluster->mf_end = mstime() + REDIS_CLUSTER_MF_TIMEOUT; 1818 server.cluster->mf_slave = sender; 1819 pauseClients(mstime()+(REDIS_CLUSTER_MF_TIMEOUT*2)); 1820 redisLog(REDIS_WARNING,"Manual failover requested by slave %.40s.", 1821 sender->name); 1822 } else if (type == CLUSTERMSG_TYPE_UPDATE) { 1823 clusterNode *n; /* The node the update is about. */ 1824 uint64_t reportedConfigEpoch = 1825 ntohu64(hdr->data.update.nodecfg.configEpoch); 1826 1827 if (!sender) return 1; /* We don't know the sender. */ 1828 n = clusterLookupNode(hdr->data.update.nodecfg.nodename); 1829 if (!n) return 1; /* We don't know the reported node. */ 1830 if (n->configEpoch >= reportedConfigEpoch) return 1; /* Nothing new. */ 1831 1832 /* If in our current config the node is a slave, set it as a master. */ 1833 if (nodeIsSlave(n)) clusterSetNodeAsMaster(n); 1834 1835 /* Update the node's configEpoch. */ 1836 n->configEpoch = reportedConfigEpoch; 1837 clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG| 1838 CLUSTER_TODO_FSYNC_CONFIG); 1839 1840 /* Check the bitmap of served slots and udpate our 1841 * config accordingly. */ 1842 clusterUpdateSlotsConfigWith(n,reportedConfigEpoch, 1843 hdr->data.update.nodecfg.slots); 1844 } else { 1845 redisLog(REDIS_WARNING,"Received unknown packet type: %d", type); 1846 } 1847 return 1; 1848 } 1849 1850 /* This function is called when we detect the link with this node is lost. 1851 We set the node as no longer connected. The Cluster Cron will detect 1852 this connection and will try to get it connected again. 1853 1854 Instead if the node is a temporary node used to accept a query, we 1855 completely free the node on error. */ 1856 void handleLinkIOError(clusterLink *link) { 1857 freeClusterLink(link); 1858 } 1859 1860 /* Send data. This is handled using a trivial send buffer that gets 1861 * consumed by write(). We don't try to optimize this for speed too much 1862 * as this is a very low traffic channel. */ 1863 void clusterWriteHandler(aeEventLoop *el, int fd, void *privdata, int mask) { 1864 clusterLink *link = (clusterLink*) privdata; 1865 ssize_t nwritten; 1866 REDIS_NOTUSED(el); 1867 REDIS_NOTUSED(mask); 1868 1869 nwritten = write(fd, link->sndbuf, sdslen(link->sndbuf)); 1870 if (nwritten <= 0) { 1871 redisLog(REDIS_DEBUG,"I/O error writing to node link: %s", 1872 strerror(errno)); 1873 handleLinkIOError(link); 1874 return; 1875 } 1876 sdsrange(link->sndbuf,nwritten,-1); 1877 if (sdslen(link->sndbuf) == 0) 1878 aeDeleteFileEvent(server.el, link->fd, AE_WRITABLE); 1879 } 1880 1881 /* Read data. Try to read the first field of the header first to check the 1882 * full length of the packet. When a whole packet is in memory this function 1883 * will call the function to process the packet. And so forth. */ 1884 void clusterReadHandler(aeEventLoop *el, int fd, void *privdata, int mask) { 1885 char buf[sizeof(clusterMsg)]; 1886 ssize_t nread; 1887 clusterMsg *hdr; 1888 clusterLink *link = (clusterLink*) privdata; 1889 int readlen, rcvbuflen; 1890 REDIS_NOTUSED(el); 1891 REDIS_NOTUSED(mask); 1892 1893 while(1) { /* Read as long as there is data to read. */ 1894 rcvbuflen = sdslen(link->rcvbuf); 1895 if (rcvbuflen < 8) { 1896 /* First, obtain the first 8 bytes to get the full message 1897 * length. */ 1898 readlen = 8 - rcvbuflen; 1899 } else { 1900 /* Finally read the full message. */ 1901 hdr = (clusterMsg*) link->rcvbuf; 1902 if (rcvbuflen == 8) { 1903 /* Perform some sanity check on the message signature 1904 * and length. */ 1905 if (memcmp(hdr->sig,"RCmb",4) != 0 || 1906 ntohl(hdr->totlen) < CLUSTERMSG_MIN_LEN) 1907 { 1908 redisLog(REDIS_WARNING, 1909 "Bad message length or signature received " 1910 "from Cluster bus."); 1911 handleLinkIOError(link); 1912 return; 1913 } 1914 } 1915 readlen = ntohl(hdr->totlen) - rcvbuflen; 1916 if (readlen > sizeof(buf)) readlen = sizeof(buf); 1917 } 1918 1919 nread = read(fd,buf,readlen); 1920 if (nread == -1 && errno == EAGAIN) return; /* No more data ready. */ 1921 1922 if (nread <= 0) { 1923 /* I/O error... */ 1924 redisLog(REDIS_DEBUG,"I/O error reading from node link: %s", 1925 (nread == 0) ? "connection closed" : strerror(errno)); 1926 handleLinkIOError(link); 1927 return; 1928 } else { 1929 /* Read data and recast the pointer to the new buffer. */ 1930 link->rcvbuf = sdscatlen(link->rcvbuf,buf,nread); 1931 hdr = (clusterMsg*) link->rcvbuf; 1932 rcvbuflen += nread; 1933 } 1934 1935 /* Total length obtained? Process this packet. */ 1936 if (rcvbuflen >= 8 && rcvbuflen == ntohl(hdr->totlen)) { 1937 if (clusterProcessPacket(link)) { 1938 sdsfree(link->rcvbuf); 1939 link->rcvbuf = sdsempty(); 1940 } else { 1941 return; /* Link no longer valid. */ 1942 } 1943 } 1944 } 1945 } 1946 1947 /* Put stuff into the send buffer. 1948 * 1949 * It is guaranteed that this function will never have as a side effect 1950 * the link to be invalidated, so it is safe to call this function 1951 * from event handlers that will do stuff with the same link later. */ 1952 void clusterSendMessage(clusterLink *link, unsigned char *msg, size_t msglen) { 1953 if (sdslen(link->sndbuf) == 0 && msglen != 0) 1954 aeCreateFileEvent(server.el,link->fd,AE_WRITABLE, 1955 clusterWriteHandler,link); 1956 1957 link->sndbuf = sdscatlen(link->sndbuf, msg, msglen); 1958 server.cluster->stats_bus_messages_sent++; 1959 } 1960 1961 /* Send a message to all the nodes that are part of the cluster having 1962 * a connected link. 1963 * 1964 * It is guaranteed that this function will never have as a side effect 1965 * some node->link to be invalidated, so it is safe to call this function 1966 * from event handlers that will do stuff with node links later. */ 1967 void clusterBroadcastMessage(void *buf, size_t len) { 1968 dictIterator *di; 1969 dictEntry *de; 1970 1971 di = dictGetSafeIterator(server.cluster->nodes); 1972 while((de = dictNext(di)) != NULL) { 1973 clusterNode *node = dictGetVal(de); 1974 1975 if (!node->link) continue; 1976 if (node->flags & (REDIS_NODE_MYSELF|REDIS_NODE_HANDSHAKE)) 1977 continue; 1978 clusterSendMessage(node->link,buf,len); 1979 } 1980 dictReleaseIterator(di); 1981 } 1982 1983 /* Build the message header */ 1984 void clusterBuildMessageHdr(clusterMsg *hdr, int type) { 1985 int totlen = 0; 1986 uint64_t offset; 1987 clusterNode *master; 1988 1989 /* If this node is a master, we send its slots bitmap and configEpoch. 1990 * If this node is a slave we send the master's information instead (the 1991 * node is flagged as slave so the receiver knows that it is NOT really 1992 * in charge for this slots. */ 1993 master = (nodeIsSlave(myself) && myself->slaveof) ? 1994 myself->slaveof : myself; 1995 1996 memset(hdr,0,sizeof(*hdr)); 1997 hdr->sig[0] = 'R'; 1998 hdr->sig[1] = 'C'; 1999 hdr->sig[2] = 'm'; 2000 hdr->sig[3] = 'b'; 2001 hdr->type = htons(type); 2002 memcpy(hdr->sender,myself->name,REDIS_CLUSTER_NAMELEN); 2003 2004 memcpy(hdr->myslots,master->slots,sizeof(hdr->myslots)); 2005 memset(hdr->slaveof,0,REDIS_CLUSTER_NAMELEN); 2006 if (myself->slaveof != NULL) 2007 memcpy(hdr->slaveof,myself->slaveof->name, REDIS_CLUSTER_NAMELEN); 2008 hdr->port = htons(server.port); 2009 hdr->flags = htons(myself->flags); 2010 hdr->state = server.cluster->state; 2011 2012 /* Set the currentEpoch and configEpochs. */ 2013 hdr->currentEpoch = htonu64(server.cluster->currentEpoch); 2014 hdr->configEpoch = htonu64(master->configEpoch); 2015 2016 /* Set the replication offset. */ 2017 if (nodeIsSlave(myself)) 2018 offset = replicationGetSlaveOffset(); 2019 else 2020 offset = server.master_repl_offset; 2021 hdr->offset = htonu64(offset); 2022 2023 /* Set the message flags. */ 2024 if (nodeIsMaster(myself) && server.cluster->mf_end) 2025 hdr->mflags[0] |= CLUSTERMSG_FLAG0_PAUSED; 2026 2027 /* Compute the message length for certain messages. For other messages 2028 * this is up to the caller. */ 2029 if (type == CLUSTERMSG_TYPE_FAIL) { 2030 totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData); 2031 totlen += sizeof(clusterMsgDataFail); 2032 } else if (type == CLUSTERMSG_TYPE_UPDATE) { 2033 totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData); 2034 totlen += sizeof(clusterMsgDataUpdate); 2035 } 2036 hdr->totlen = htonl(totlen); 2037 /* For PING, PONG, and MEET, fixing the totlen field is up to the caller. */ 2038 } 2039 2040 /* Send a PING or PONG packet to the specified node, making sure to add enough 2041 * gossip informations. */ 2042 void clusterSendPing(clusterLink *link, int type) { 2043 unsigned char buf[sizeof(clusterMsg)]; 2044 clusterMsg *hdr = (clusterMsg*) buf; 2045 int gossipcount = 0, totlen; 2046 /* freshnodes is the number of nodes we can still use to populate the 2047 * gossip section of the ping packet. Basically we start with the nodes 2048 * we have in memory minus two (ourself and the node we are sending the 2049 * message to). Every time we add a node we decrement the counter, so when 2050 * it will drop to <= zero we know there is no more gossip info we can 2051 * send. */ 2052 int freshnodes = dictSize(server.cluster->nodes)-2; 2053 2054 if (link->node && type == CLUSTERMSG_TYPE_PING) 2055 link->node->ping_sent = mstime(); 2056 clusterBuildMessageHdr(hdr,type); 2057 2058 /* Populate the gossip fields */ 2059 while(freshnodes > 0 && gossipcount < 3) { 2060 dictEntry *de = dictGetRandomKey(server.cluster->nodes); 2061 clusterNode *this = dictGetVal(de); 2062 clusterMsgDataGossip *gossip; 2063 int j; 2064 2065 /* In the gossip section don't include: 2066 * 1) Myself. 2067 * 2) Nodes in HANDSHAKE state. 2068 * 3) Nodes with the NOADDR flag set. 2069 * 4) Disconnected nodes if they don't have configured slots. 2070 */ 2071 if (this == myself || 2072 this->flags & (REDIS_NODE_HANDSHAKE|REDIS_NODE_NOADDR) || 2073 (this->link == NULL && this->numslots == 0)) 2074 { 2075 freshnodes--; /* otherwise we may loop forever. */ 2076 continue; 2077 } 2078 2079 /* Check if we already added this node */ 2080 for (j = 0; j < gossipcount; j++) { 2081 if (memcmp(hdr->data.ping.gossip[j].nodename,this->name, 2082 REDIS_CLUSTER_NAMELEN) == 0) break; 2083 } 2084 if (j != gossipcount) continue; 2085 2086 /* Add it */ 2087 freshnodes--; 2088 gossip = &(hdr->data.ping.gossip[gossipcount]); 2089 memcpy(gossip->nodename,this->name,REDIS_CLUSTER_NAMELEN); 2090 gossip->ping_sent = htonl(this->ping_sent); 2091 gossip->pong_received = htonl(this->pong_received); 2092 memcpy(gossip->ip,this->ip,sizeof(this->ip)); 2093 gossip->port = htons(this->port); 2094 gossip->flags = htons(this->flags); 2095 gossipcount++; 2096 } 2097 totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData); 2098 totlen += (sizeof(clusterMsgDataGossip)*gossipcount); 2099 hdr->count = htons(gossipcount); 2100 hdr->totlen = htonl(totlen); 2101 clusterSendMessage(link,buf,totlen); 2102 } 2103 2104 /* Send a PONG packet to every connected node that's not in handshake state 2105 * and for which we have a valid link. 2106 * 2107 * In Redis Cluster pongs are not used just for failure detection, but also 2108 * to carry important configuration information. So broadcasting a pong is 2109 * useful when something changes in the configuration and we want to make 2110 * the cluster aware ASAP (for instance after a slave promotion). 2111 * 2112 * The 'target' argument specifies the receiving instances using the 2113 * defines below: 2114 * 2115 * CLUSTER_BROADCAST_ALL -> All known instances. 2116 * CLUSTER_BROADCAST_LOCAL_SLAVES -> All slaves in my master-slaves ring. 2117 */ 2118 #define CLUSTER_BROADCAST_ALL 0 2119 #define CLUSTER_BROADCAST_LOCAL_SLAVES 1 2120 void clusterBroadcastPong(int target) { 2121 dictIterator *di; 2122 dictEntry *de; 2123 2124 di = dictGetSafeIterator(server.cluster->nodes); 2125 while((de = dictNext(di)) != NULL) { 2126 clusterNode *node = dictGetVal(de); 2127 2128 if (!node->link) continue; 2129 if (node == myself || nodeInHandshake(node)) continue; 2130 if (target == CLUSTER_BROADCAST_LOCAL_SLAVES) { 2131 int local_slave = 2132 nodeIsSlave(node) && node->slaveof && 2133 (node->slaveof == myself || node->slaveof == myself->slaveof); 2134 if (!local_slave) continue; 2135 } 2136 clusterSendPing(node->link,CLUSTERMSG_TYPE_PONG); 2137 } 2138 dictReleaseIterator(di); 2139 } 2140 2141 /* Send a PUBLISH message. 2142 * 2143 * If link is NULL, then the message is broadcasted to the whole cluster. */ 2144 void clusterSendPublish(clusterLink *link, robj *channel, robj *message) { 2145 unsigned char buf[sizeof(clusterMsg)], *payload; 2146 clusterMsg *hdr = (clusterMsg*) buf; 2147 uint32_t totlen; 2148 uint32_t channel_len, message_len; 2149 2150 channel = getDecodedObject(channel); 2151 message = getDecodedObject(message); 2152 channel_len = sdslen(channel->ptr); 2153 message_len = sdslen(message->ptr); 2154 2155 clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_PUBLISH); 2156 totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData); 2157 totlen += sizeof(clusterMsgDataPublish) + channel_len + message_len; 2158 2159 hdr->data.publish.msg.channel_len = htonl(channel_len); 2160 hdr->data.publish.msg.message_len = htonl(message_len); 2161 hdr->totlen = htonl(totlen); 2162 2163 /* Try to use the local buffer if possible */ 2164 if (totlen < sizeof(buf)) { 2165 payload = buf; 2166 } else { 2167 payload = zmalloc(totlen); 2168 memcpy(payload,hdr,sizeof(*hdr)); 2169 hdr = (clusterMsg*) payload; 2170 } 2171 memcpy(hdr->data.publish.msg.bulk_data,channel->ptr,sdslen(channel->ptr)); 2172 memcpy(hdr->data.publish.msg.bulk_data+sdslen(channel->ptr), 2173 message->ptr,sdslen(message->ptr)); 2174 2175 if (link) 2176 clusterSendMessage(link,payload,totlen); 2177 else 2178 clusterBroadcastMessage(payload,totlen); 2179 2180 decrRefCount(channel); 2181 decrRefCount(message); 2182 if (payload != buf) zfree(payload); 2183 } 2184 2185 /* Send a FAIL message to all the nodes we are able to contact. 2186 * The FAIL message is sent when we detect that a node is failing 2187 * (REDIS_NODE_PFAIL) and we also receive a gossip confirmation of this: 2188 * we switch the node state to REDIS_NODE_FAIL and ask all the other 2189 * nodes to do the same ASAP. */ 2190 void clusterSendFail(char *nodename) { 2191 unsigned char buf[sizeof(clusterMsg)]; 2192 clusterMsg *hdr = (clusterMsg*) buf; 2193 2194 clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_FAIL); 2195 memcpy(hdr->data.fail.about.nodename,nodename,REDIS_CLUSTER_NAMELEN); 2196 clusterBroadcastMessage(buf,ntohl(hdr->totlen)); 2197 } 2198 2199 /* Send an UPDATE message to the specified link carrying the specified 'node' 2200 * slots configuration. The node name, slots bitmap, and configEpoch info 2201 * are included. */ 2202 void clusterSendUpdate(clusterLink *link, clusterNode *node) { 2203 unsigned char buf[sizeof(clusterMsg)]; 2204 clusterMsg *hdr = (clusterMsg*) buf; 2205 2206 if (link == NULL) return; 2207 clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_UPDATE); 2208 memcpy(hdr->data.update.nodecfg.nodename,node->name,REDIS_CLUSTER_NAMELEN); 2209 hdr->data.update.nodecfg.configEpoch = htonu64(node->configEpoch); 2210 memcpy(hdr->data.update.nodecfg.slots,node->slots,sizeof(node->slots)); 2211 clusterSendMessage(link,buf,ntohl(hdr->totlen)); 2212 } 2213 2214 /* ----------------------------------------------------------------------------- 2215 * CLUSTER Pub/Sub support 2216 * 2217 * For now we do very little, just propagating PUBLISH messages across the whole 2218 * cluster. In the future we'll try to get smarter and avoiding propagating those 2219 * messages to hosts without receives for a given channel. 2220 * -------------------------------------------------------------------------- */ 2221 void clusterPropagatePublish(robj *channel, robj *message) { 2222 clusterSendPublish(NULL, channel, message); 2223 } 2224 2225 /* ----------------------------------------------------------------------------- 2226 * SLAVE node specific functions 2227 * -------------------------------------------------------------------------- */ 2228 2229 /* This function sends a FAILOVE_AUTH_REQUEST message to every node in order to 2230 * see if there is the quorum for this slave instance to failover its failing 2231 * master. 2232 * 2233 * Note that we send the failover request to everybody, master and slave nodes, 2234 * but only the masters are supposed to reply to our query. */ 2235 void clusterRequestFailoverAuth(void) { 2236 unsigned char buf[sizeof(clusterMsg)]; 2237 clusterMsg *hdr = (clusterMsg*) buf; 2238 uint32_t totlen; 2239 2240 clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_FAILOVER_AUTH_REQUEST); 2241 /* If this is a manual failover, set the CLUSTERMSG_FLAG0_FORCEACK bit 2242 * in the header to communicate the nodes receiving the message that 2243 * they should authorized the failover even if the master is working. */ 2244 if (server.cluster->mf_end) hdr->mflags[0] |= CLUSTERMSG_FLAG0_FORCEACK; 2245 totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData); 2246 hdr->totlen = htonl(totlen); 2247 clusterBroadcastMessage(buf,totlen); 2248 } 2249 2250 /* Send a FAILOVER_AUTH_ACK message to the specified node. */ 2251 void clusterSendFailoverAuth(clusterNode *node) { 2252 unsigned char buf[sizeof(clusterMsg)]; 2253 clusterMsg *hdr = (clusterMsg*) buf; 2254 uint32_t totlen; 2255 2256 if (!node->link) return; 2257 clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_FAILOVER_AUTH_ACK); 2258 totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData); 2259 hdr->totlen = htonl(totlen); 2260 clusterSendMessage(node->link,buf,totlen); 2261 } 2262 2263 /* Send a MFSTART message to the specified node. */ 2264 void clusterSendMFStart(clusterNode *node) { 2265 unsigned char buf[sizeof(clusterMsg)]; 2266 clusterMsg *hdr = (clusterMsg*) buf; 2267 uint32_t totlen; 2268 2269 if (!node->link) return; 2270 clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_MFSTART); 2271 totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData); 2272 hdr->totlen = htonl(totlen); 2273 clusterSendMessage(node->link,buf,totlen); 2274 } 2275 2276 /* Vote for the node asking for our vote if there are the conditions. */ 2277 void clusterSendFailoverAuthIfNeeded(clusterNode *node, clusterMsg *request) { 2278 clusterNode *master = node->slaveof; 2279 uint64_t requestCurrentEpoch = ntohu64(request->currentEpoch); 2280 uint64_t requestConfigEpoch = ntohu64(request->configEpoch); 2281 unsigned char *claimed_slots = request->myslots; 2282 int force_ack = request->mflags[0] & CLUSTERMSG_FLAG0_FORCEACK; 2283 int j; 2284 2285 /* IF we are not a master serving at least 1 slot, we don't have the 2286 * right to vote, as the cluster size in Redis Cluster is the number 2287 * of masters serving at least one slot, and quorum is the cluster 2288 * size + 1 */ 2289 if (nodeIsSlave(myself) || myself->numslots == 0) return; 2290 2291 /* Request epoch must be >= our currentEpoch. 2292 * Note that it is impossible for it to actually be greater since 2293 * our currentEpoch was updated as a side effect of receiving this 2294 * request, if the request epoch was greater. */ 2295 if (requestCurrentEpoch < server.cluster->currentEpoch) { 2296 redisLog(REDIS_WARNING, 2297 "Failover auth denied to %.40s: reqEpoch (%llu) < curEpoch(%llu)", 2298 node->name, 2299 (unsigned long long) requestCurrentEpoch, 2300 (unsigned long long) server.cluster->currentEpoch); 2301 return; 2302 } 2303 2304 /* I already voted for this epoch? Return ASAP. */ 2305 if (server.cluster->lastVoteEpoch == server.cluster->currentEpoch) { 2306 redisLog(REDIS_WARNING, 2307 "Failover auth denied to %.40s: already voted for epoch %llu", 2308 node->name, 2309 (unsigned long long) server.cluster->currentEpoch); 2310 return; 2311 } 2312 2313 /* Node must be a slave and its master down. 2314 * The master can be non failing if the request is flagged 2315 * with CLUSTERMSG_FLAG0_FORCEACK (manual failover). */ 2316 if (nodeIsMaster(node) || master == NULL || 2317 (!nodeFailed(master) && !force_ack)) 2318 { 2319 if (nodeIsMaster(node)) { 2320 redisLog(REDIS_WARNING, 2321 "Failover auth denied to %.40s: it is a master node", 2322 node->name); 2323 } else if (master == NULL) { 2324 redisLog(REDIS_WARNING, 2325 "Failover auth denied to %.40s: I don't know its master", 2326 node->name); 2327 } else if (!nodeFailed(master)) { 2328 redisLog(REDIS_WARNING, 2329 "Failover auth denied to %.40s: its master is up", 2330 node->name); 2331 } 2332 return; 2333 } 2334 2335 /* We did not voted for a slave about this master for two 2336 * times the node timeout. This is not strictly needed for correctness 2337 * of the algorithm but makes the base case more linear. */ 2338 if (mstime() - node->slaveof->voted_time < server.cluster_node_timeout * 2) 2339 { 2340 redisLog(REDIS_WARNING, 2341 "Failover auth denied to %.40s: " 2342 "can't vote about this master before %lld milliseconds", 2343 node->name, 2344 (long long) ((server.cluster_node_timeout*2)- 2345 (mstime() - node->slaveof->voted_time))); 2346 return; 2347 } 2348 2349 /* The slave requesting the vote must have a configEpoch for the claimed 2350 * slots that is >= the one of the masters currently serving the same 2351 * slots in the current configuration. */ 2352 for (j = 0; j < REDIS_CLUSTER_SLOTS; j++) { 2353 if (bitmapTestBit(claimed_slots, j) == 0) continue; 2354 if (server.cluster->slots[j] == NULL || 2355 server.cluster->slots[j]->configEpoch <= requestConfigEpoch) 2356 { 2357 continue; 2358 } 2359 /* If we reached this point we found a slot that in our current slots 2360 * is served by a master with a greater configEpoch than the one claimed 2361 * by the slave requesting our vote. Refuse to vote for this slave. */ 2362 redisLog(REDIS_WARNING, 2363 "Failover auth denied to %.40s: " 2364 "slot %d epoch (%llu) > reqEpoch (%llu)", 2365 node->name, j, 2366 (unsigned long long) server.cluster->slots[j]->configEpoch, 2367 (unsigned long long) requestConfigEpoch); 2368 return; 2369 } 2370 2371 /* We can vote for this slave. */ 2372 clusterSendFailoverAuth(node); 2373 server.cluster->lastVoteEpoch = server.cluster->currentEpoch; 2374 node->slaveof->voted_time = mstime(); 2375 redisLog(REDIS_WARNING, "Failover auth granted to %.40s for epoch %llu", 2376 node->name, (unsigned long long) server.cluster->currentEpoch); 2377 } 2378 2379 /* This function returns the "rank" of this instance, a slave, in the context 2380 * of its master-slaves ring. The rank of the slave is given by the number of 2381 * other slaves for the same master that have a better replication offset 2382 * compared to the local one (better means, greater, so they claim more data). 2383 * 2384 * A slave with rank 0 is the one with the greatest (most up to date) 2385 * replication offset, and so forth. Note that because how the rank is computed 2386 * multiple slaves may have the same rank, in case they have the same offset. 2387 * 2388 * The slave rank is used to add a delay to start an election in order to 2389 * get voted and replace a failing master. Slaves with better replication 2390 * offsets are more likely to win. */ 2391 int clusterGetSlaveRank(void) { 2392 long long myoffset; 2393 int j, rank = 0; 2394 clusterNode *master; 2395 2396 redisAssert(nodeIsSlave(myself)); 2397 master = myself->slaveof; 2398 if (master == NULL) return 0; /* Never called by slaves without master. */ 2399 2400 myoffset = replicationGetSlaveOffset(); 2401 for (j = 0; j < master->numslaves; j++) 2402 if (master->slaves[j] != myself && 2403 master->slaves[j]->repl_offset > myoffset) rank++; 2404 return rank; 2405 } 2406 2407 /* This function is called if we are a slave node and our master serving 2408 * a non-zero amount of hash slots is in FAIL state. 2409 * 2410 * The gaol of this function is: 2411 * 1) To check if we are able to perform a failover, is our data updated? 2412 * 2) Try to get elected by masters. 2413 * 3) Perform the failover informing all the other nodes. 2414 */ 2415 void clusterHandleSlaveFailover(void) { 2416 mstime_t data_age; 2417 mstime_t auth_age = mstime() - server.cluster->failover_auth_time; 2418 int needed_quorum = (server.cluster->size / 2) + 1; 2419 int manual_failover = server.cluster->mf_end != 0 && 2420 server.cluster->mf_can_start; 2421 int j; 2422 mstime_t auth_timeout, auth_retry_time; 2423 2424 server.cluster->todo_before_sleep &= ~CLUSTER_TODO_HANDLE_FAILOVER; 2425 2426 /* Compute the failover timeout (the max time we have to send votes 2427 * and wait for replies), and the failover retry time (the time to wait 2428 * before waiting again. 2429 * 2430 * Timeout is MIN(NODE_TIMEOUT*2,2000) milliseconds. 2431 * Retry is two times the Timeout. 2432 */ 2433 auth_timeout = server.cluster_node_timeout*2; 2434 if (auth_timeout < 2000) auth_timeout = 2000; 2435 auth_retry_time = auth_timeout*2; 2436 2437 /* Pre conditions to run the function, that must be met both in case 2438 * of an automatic or manual failover: 2439 * 1) We are a slave. 2440 * 2) Our master is flagged as FAIL, or this is a manual failover. 2441 * 3) It is serving slots. */ 2442 if (nodeIsMaster(myself) || 2443 myself->slaveof == NULL || 2444 (!nodeFailed(myself->slaveof) && !manual_failover) || 2445 myself->slaveof->numslots == 0) return; 2446 2447 /* Set data_age to the number of seconds we are disconnected from 2448 * the master. */ 2449 if (server.repl_state == REDIS_REPL_CONNECTED) { 2450 data_age = (mstime_t)(server.unixtime - server.master->lastinteraction) 2451 * 1000; 2452 } else { 2453 data_age = (mstime_t)(server.unixtime - server.repl_down_since) * 1000; 2454 } 2455 2456 /* Remove the node timeout from the data age as it is fine that we are 2457 * disconnected from our master at least for the time it was down to be 2458 * flagged as FAIL, that's the baseline. */ 2459 if (data_age > server.cluster_node_timeout) 2460 data_age -= server.cluster_node_timeout; 2461 2462 /* Check if our data is recent enough according to the slave validity 2463 * factor configured by the user. 2464 * 2465 * Check bypassed for manual failovers. */ 2466 if (server.cluster_slave_validity_factor && 2467 data_age > 2468 (((mstime_t)server.repl_ping_slave_period * 1000) + 2469 (server.cluster_node_timeout * server.cluster_slave_validity_factor))) 2470 { 2471 if (!manual_failover) return; 2472 } 2473 2474 /* If the previous failover attempt timedout and the retry time has 2475 * elapsed, we can setup a new one. */ 2476 if (auth_age > auth_retry_time) { 2477 server.cluster->failover_auth_time = mstime() + 2478 500 + /* Fixed delay of 500 milliseconds, let FAIL msg propagate. */ 2479 random() % 500; /* Random delay between 0 and 500 milliseconds. */ 2480 server.cluster->failover_auth_count = 0; 2481 server.cluster->failover_auth_sent = 0; 2482 server.cluster->failover_auth_rank = clusterGetSlaveRank(); 2483 /* We add another delay that is proportional to the slave rank. 2484 * Specifically 1 second * rank. This way slaves that have a probably 2485 * less updated replication offset, are penalized. */ 2486 server.cluster->failover_auth_time += 2487 server.cluster->failover_auth_rank * 1000; 2488 /* However if this is a manual failover, no delay is needed. */ 2489 if (server.cluster->mf_end) { 2490 server.cluster->failover_auth_time = mstime(); 2491 server.cluster->failover_auth_rank = 0; 2492 } 2493 redisLog(REDIS_WARNING, 2494 "Start of election delayed for %lld milliseconds " 2495 "(rank #%d, offset %lld).", 2496 server.cluster->failover_auth_time - mstime(), 2497 server.cluster->failover_auth_rank, 2498 replicationGetSlaveOffset()); 2499 /* Now that we have a scheduled election, broadcast our offset 2500 * to all the other slaves so that they'll updated their offsets 2501 * if our offset is better. */ 2502 clusterBroadcastPong(CLUSTER_BROADCAST_LOCAL_SLAVES); 2503 return; 2504 } 2505 2506 /* It is possible that we received more updated offsets from other 2507 * slaves for the same master since we computed our election delay. 2508 * Update the delay if our rank changed. 2509 * 2510 * Not performed if this is a manual failover. */ 2511 if (server.cluster->failover_auth_sent == 0 && 2512 server.cluster->mf_end == 0) 2513 { 2514 int newrank = clusterGetSlaveRank(); 2515 if (newrank > server.cluster->failover_auth_rank) { 2516 long long added_delay = 2517 (newrank - server.cluster->failover_auth_rank) * 1000; 2518 server.cluster->failover_auth_time += added_delay; 2519 server.cluster->failover_auth_rank = newrank; 2520 redisLog(REDIS_WARNING, 2521 "Slave rank updated to #%d, added %lld milliseconds of delay.", 2522 newrank, added_delay); 2523 } 2524 } 2525 2526 /* Return ASAP if we can't still start the election. */ 2527 if (mstime() < server.cluster->failover_auth_time) return; 2528 2529 /* Return ASAP if the election is too old to be valid. */ 2530 if (auth_age > auth_timeout) return; 2531 2532 /* Ask for votes if needed. */ 2533 if (server.cluster->failover_auth_sent == 0) { 2534 server.cluster->currentEpoch++; 2535 server.cluster->failover_auth_epoch = server.cluster->currentEpoch; 2536 redisLog(REDIS_WARNING,"Starting a failover election for epoch %llu.", 2537 (unsigned long long) server.cluster->currentEpoch); 2538 clusterRequestFailoverAuth(); 2539 server.cluster->failover_auth_sent = 1; 2540 clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG| 2541 CLUSTER_TODO_UPDATE_STATE| 2542 CLUSTER_TODO_FSYNC_CONFIG); 2543 return; /* Wait for replies. */ 2544 } 2545 2546 /* Check if we reached the quorum. */ 2547 if (server.cluster->failover_auth_count >= needed_quorum) { 2548 clusterNode *oldmaster = myself->slaveof; 2549 2550 redisLog(REDIS_WARNING, 2551 "Failover election won: I'm the new master."); 2552 /* We have the quorum, perform all the steps to correctly promote 2553 * this slave to a master. 2554 * 2555 * 1) Turn this node into a master. */ 2556 clusterSetNodeAsMaster(myself); 2557 replicationUnsetMaster(); 2558 2559 /* 2) Claim all the slots assigned to our master. */ 2560 for (j = 0; j < REDIS_CLUSTER_SLOTS; j++) { 2561 if (clusterNodeGetSlotBit(oldmaster,j)) { 2562 clusterDelSlot(j); 2563 clusterAddSlot(myself,j); 2564 } 2565 } 2566 2567 /* 3) Update my configEpoch to the epoch of the election. */ 2568 if (myself->configEpoch < server.cluster->failover_auth_epoch) { 2569 myself->configEpoch = server.cluster->failover_auth_epoch; 2570 redisLog(REDIS_WARNING, 2571 "configEpoch set to %llu after successful failover", 2572 (unsigned long long) myself->configEpoch); 2573 } 2574 2575 /* 4) Update state and save config. */ 2576 clusterUpdateState(); 2577 clusterSaveConfigOrDie(1); 2578 2579 /* 5) Pong all the other nodes so that they can update the state 2580 * accordingly and detect that we switched to master role. */ 2581 clusterBroadcastPong(CLUSTER_BROADCAST_ALL); 2582 2583 /* 6) If there was a manual failover in progress, clear the state. */ 2584 resetManualFailover(); 2585 } 2586 } 2587 2588 /* ----------------------------------------------------------------------------- 2589 * CLUSTER slave migration 2590 * 2591 * Slave migration is the process that allows a slave of a master that is 2592 * already covered by at least another slave, to "migrate" to a master that 2593 * is orpaned, that is, left with no working slaves. 2594 * -------------------------------------------------------------------------- */ 2595 2596 /* This function is responsible to decide if this replica should be migrated 2597 * to a different (orphaned) master. It is called by the clusterCron() function 2598 * only if: 2599 * 2600 * 1) We are a slave node. 2601 * 2) It was detected that there is at least one orphaned master in 2602 * the cluster. 2603 * 3) We are a slave of one of the masters with the greatest number of 2604 * slaves. 2605 * 2606 * This checks are performed by the caller since it requires to iterate 2607 * the nodes anyway, so we spend time into clusterHandleSlaveMigration() 2608 * if definitely needed. 2609 * 2610 * The fuction is called with a pre-computed max_slaves, that is the max 2611 * number of working (not in FAIL state) slaves for a single master. 2612 * 2613 * Additional conditions for migration are examined inside the function. 2614 */ 2615 void clusterHandleSlaveMigration(int max_slaves) { 2616 int j, okslaves = 0; 2617 clusterNode *mymaster = myself->slaveof, *target = NULL, *candidate = NULL; 2618 dictIterator *di; 2619 dictEntry *de; 2620 2621 /* Step 1: Don't migrate if the cluster state is not ok. */ 2622 if (server.cluster->state != REDIS_CLUSTER_OK) return; 2623 2624 /* Step 2: Don't migrate if my master will not be left with at least 2625 * 'migration-barrier' slaves after my migration. */ 2626 if (mymaster == NULL) return; 2627 for (j = 0; j < mymaster->numslaves; j++) 2628 if (!nodeFailed(mymaster->slaves[j]) && 2629 !nodeTimedOut(mymaster->slaves[j])) okslaves++; 2630 if (okslaves <= server.cluster_migration_barrier) return; 2631 2632 /* Step 3: Idenitfy a candidate for migration, and check if among the 2633 * masters with the greatest number of ok slaves, I'm the one with the 2634 * smaller node ID. 2635 * 2636 * Note that this means that eventually a replica migration will occurr 2637 * since slaves that are reachable again always have their FAIL flag 2638 * cleared. At the same time this does not mean that there are no 2639 * race conditions possible (two slaves migrating at the same time), but 2640 * this is extremely unlikely to happen, and harmless. */ 2641 candidate = myself; 2642 di = dictGetSafeIterator(server.cluster->nodes); 2643 while((de = dictNext(di)) != NULL) { 2644 clusterNode *node = dictGetVal(de); 2645 int okslaves; 2646 2647 /* Only iterate over working masters. */ 2648 if (nodeIsSlave(node) || nodeFailed(node)) continue; 2649 okslaves = clusterCountNonFailingSlaves(node); 2650 2651 if (okslaves == 0 && target == NULL && node->numslots > 0) 2652 target = node; 2653 2654 if (okslaves == max_slaves) { 2655 for (j = 0; j < node->numslaves; j++) { 2656 if (memcmp(node->slaves[j]->name, 2657 candidate->name, 2658 REDIS_CLUSTER_NAMELEN) < 0) 2659 { 2660 candidate = node->slaves[j]; 2661 } 2662 } 2663 } 2664 } 2665 2666 /* Step 4: perform the migration if there is a target, and if I'm the 2667 * candidate. */ 2668 if (target && candidate == myself) { 2669 redisLog(REDIS_WARNING,"Migrating to orphaned master %.40s", 2670 target->name); 2671 clusterSetMaster(target); 2672 } 2673 } 2674 2675 /* ----------------------------------------------------------------------------- 2676 * CLUSTER manual failover 2677 * 2678 * This are the important steps performed by slaves during a manual failover: 2679 * 1) User send CLUSTER FAILOVER command. The failover state is initialized 2680 * setting mf_end to the millisecond unix time at which we'll abort the 2681 * attempt. 2682 * 2) Slave sends a MFSTART message to the master requesting to pause clients 2683 * for two times the manual failover timeout REDIS_CLUSTER_MF_TIMEOUT. 2684 * When master is paused for manual failover, it also starts to flag 2685 * packets with CLUSTERMSG_FLAG0_PAUSED. 2686 * 3) Slave waits for master to send its replication offset flagged as PAUSED. 2687 * 4) If slave received the offset from the master, and its offset matches, 2688 * mf_can_start is set to 1, and clusterHandleSlaveFailover() will perform 2689 * the failover as usually, with the difference that the vote request 2690 * will be modified to force masters to vote for a slave that has a 2691 * working master. 2692 * 2693 * From the point of view of the master things are simpler: when a 2694 * PAUSE_CLIENTS packet is received the master sets mf_end as well and 2695 * the sender in mf_slave. During the time limit for the manual failover 2696 * the master will just send PINGs more often to this slave, flagged with 2697 * the PAUSED flag, so that the slave will set mf_master_offset when receiving 2698 * a packet from the master with this flag set. 2699 * 2700 * The gaol of the manual failover is to perform a fast failover without 2701 * data loss due to the asynchronous master-slave replication. 2702 * -------------------------------------------------------------------------- */ 2703 2704 /* Reset the manual failover state. This works for both masters and slavesa 2705 * as all the state about manual failover is cleared. 2706 * 2707 * The function can be used both to initialize the manual failover state at 2708 * startup or to abort a manual failover in progress. */ 2709 void resetManualFailover(void) { 2710 if (server.cluster->mf_end && clientsArePaused()) { 2711 server.clients_pause_end_time = 0; 2712 clientsArePaused(); /* Just use the side effect of the function. */ 2713 } 2714 server.cluster->mf_end = 0; /* No manual failover in progress. */ 2715 server.cluster->mf_can_start = 0; 2716 server.cluster->mf_slave = NULL; 2717 server.cluster->mf_master_offset = 0; 2718 } 2719 2720 /* If a manual failover timed out, abort it. */ 2721 void manualFailoverCheckTimeout(void) { 2722 if (server.cluster->mf_end && server.cluster->mf_end < mstime()) { 2723 redisLog(REDIS_WARNING,"Manual failover timed out."); 2724 resetManualFailover(); 2725 } 2726 } 2727 2728 /* This function is called from the cluster cron function in order to go 2729 * forward with a manual failover state machine. */ 2730 void clusterHandleManualFailover(void) { 2731 /* Return ASAP if no manual failover is in progress. */ 2732 if (server.cluster->mf_end == 0) return; 2733 2734 /* If mf_can_start is non-zero, the failover was alrady triggered so the 2735 * next steps are performed by clusterHandleSlaveFailover(). */ 2736 if (server.cluster->mf_can_start) return; 2737 2738 if (server.cluster->mf_master_offset == 0) return; /* Wait for offset... */ 2739 2740 if (server.cluster->mf_master_offset == replicationGetSlaveOffset()) { 2741 /* Our replication offset matches the master replication offset 2742 * announced after clients were paused. We can start the failover. */ 2743 server.cluster->mf_can_start = 1; 2744 redisLog(REDIS_WARNING, 2745 "All master replication stream processed, " 2746 "manual failover can start."); 2747 } 2748 } 2749 2750 /* ----------------------------------------------------------------------------- 2751 * CLUSTER cron job 2752 * -------------------------------------------------------------------------- */ 2753 2754 /* This is executed 10 times every second */ 2755 void clusterCron(void) { 2756 dictIterator *di; 2757 dictEntry *de; 2758 int update_state = 0; 2759 int orphaned_masters; /* How many masters there are without ok slaves. */ 2760 int max_slaves; /* Max number of ok slaves for a single master. */ 2761 int this_slaves; /* Number of ok slaves for our master (if we are slave). */ 2762 mstime_t min_pong = 0, now = mstime(); 2763 clusterNode *min_pong_node = NULL; 2764 static unsigned long long iteration = 0; 2765 mstime_t handshake_timeout; 2766 2767 iteration++; /* Number of times this function was called so far. */ 2768 2769 /* The handshake timeout is the time after which a handshake node that was 2770 * not turned into a normal node is removed from the nodes. Usually it is 2771 * just the NODE_TIMEOUT value, but when NODE_TIMEOUT is too small we use 2772 * the value of 1 second. */ 2773 handshake_timeout = server.cluster_node_timeout; 2774 if (handshake_timeout < 1000) handshake_timeout = 1000; 2775 2776 /* Check if we have disconnected nodes and re-establish the connection. */ 2777 di = dictGetSafeIterator(server.cluster->nodes); 2778 while((de = dictNext(di)) != NULL) { 2779 clusterNode *node = dictGetVal(de); 2780 2781 if (node->flags & (REDIS_NODE_MYSELF|REDIS_NODE_NOADDR)) continue; 2782 2783 /* A Node in HANDSHAKE state has a limited lifespan equal to the 2784 * configured node timeout. */ 2785 if (nodeInHandshake(node) && now - node->ctime > handshake_timeout) { 2786 freeClusterNode(node); 2787 continue; 2788 } 2789 2790 if (node->link == NULL) { 2791 int fd; 2792 mstime_t old_ping_sent; 2793 clusterLink *link; 2794 2795 fd = anetTcpNonBlockBindConnect(server.neterr, node->ip, 2796 node->port+REDIS_CLUSTER_PORT_INCR, 2797 server.bindaddr_count ? server.bindaddr[0] : NULL); 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