cluster.c 222.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
/* Redis Cluster implementation.
 *
 * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of Redis nor the names of its contributors may be used
 *     to endorse or promote products derived from this software without
 *     specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

31
#include "server.h"
32
#include "cluster.h"
33
#include "endianconv.h"
A
antirez 已提交
34

35 36
#include <sys/types.h>
#include <sys/socket.h>
A
antirez 已提交
37
#include <arpa/inet.h>
A
antirez 已提交
38 39
#include <fcntl.h>
#include <unistd.h>
40
#include <sys/stat.h>
41
#include <sys/file.h>
42
#include <math.h>
A
antirez 已提交
43

44 45 46 47 48
/* A global reference to myself is handy to make code more clear.
 * Myself always points to server.cluster->myself, that is, the clusterNode
 * that represents this node. */
clusterNode *myself = NULL;

49 50
clusterNode *createClusterNode(char *nodename, int flags);
int clusterAddNode(clusterNode *node);
A
antirez 已提交
51 52 53 54
void clusterAcceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
void clusterReadHandler(aeEventLoop *el, int fd, void *privdata, int mask);
void clusterSendPing(clusterLink *link, int type);
void clusterSendFail(char *nodename);
55
void clusterSendFailoverAuthIfNeeded(clusterNode *node, clusterMsg *request);
A
antirez 已提交
56 57
void clusterUpdateState(void);
int clusterNodeGetSlotBit(clusterNode *n, int slot);
58
sds clusterGenNodesDescription(int filter);
59
clusterNode *clusterLookupNode(const 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);
A
antirez 已提交
69
void clusterDoBeforeSleep(int flags);
70
void clusterSendUpdate(clusterLink *link, clusterNode *node);
71
void resetManualFailover(void);
A
antirez 已提交
72
void clusterCloseAllSlots(void);
A
antirez 已提交
73 74
void clusterSetNodeAsMaster(clusterNode *n);
void clusterDelNode(clusterNode *delnode);
75
sds representClusterNodeFlags(sds ci, uint16_t flags);
76 77
uint64_t clusterGetMaxEpoch(void);
int clusterBumpConfigEpochWithoutConsensus(void);
78
void moduleCallClusterReceivers(const char *sender_id, uint64_t module_id, uint8_t type, const unsigned char *payload, uint32_t len);
C
charsyam 已提交
79

A
antirez 已提交
80 81 82 83
/* -----------------------------------------------------------------------------
 * Initialization
 * -------------------------------------------------------------------------- */

84 85 86 87
/* Load the cluster config from 'filename'.
 *
 * If the file does not exist or is zero-length (this may happen because
 * when we lock the nodes.conf file, we create a zero-length one for the
88 89
 * sake of locking if it does not already exist), C_ERR is returned.
 * If the configuration was loaded from the file, C_OK is returned. */
A
antirez 已提交
90 91
int clusterLoadConfig(char *filename) {
    FILE *fp = fopen(filename,"r");
92
    struct stat sb;
A
antirez 已提交
93
    char *line;
94
    int maxline, j;
95

96 97
    if (fp == NULL) {
        if (errno == ENOENT) {
98
            return C_ERR;
99
        } else {
A
antirez 已提交
100
            serverLog(LL_WARNING,
101 102 103 104 105
                "Loading the cluster node config from %s: %s",
                filename, strerror(errno));
            exit(1);
        }
    }
A
antirez 已提交
106

107
    /* Check if the file is zero-length: if so return C_ERR to signal
108 109 110
     * we have to write the config. */
    if (fstat(fileno(fp),&sb) != -1 && sb.st_size == 0) {
        fclose(fp);
111
        return C_ERR;
112 113
    }

114
    /* Parse the file. Note that single lines of the cluster config file can
A
antirez 已提交
115
     * be really long as they include all the hash slots of the node.
116 117 118 119
     * This means in the worst possible case, half of the Redis slots will be
     * present in a single line, possibly in importing or migrating state, so
     * together with the node ID of the sender/receiver.
     *
A
antirez 已提交
120 121
     * To simplify we allocate 1024+CLUSTER_SLOTS*128 bytes per line. */
    maxline = 1024+CLUSTER_SLOTS*128;
A
antirez 已提交
122 123 124
    line = zmalloc(maxline);
    while(fgets(line,maxline,fp) != NULL) {
        int argc;
125
        sds *argv;
126 127 128
        clusterNode *n, *master;
        char *p, *s;

129 130 131
        /* Skip blank lines, they can be created either by users manually
         * editing nodes.conf or by the config writing process if stopped
         * before the truncate() call. */
132
        if (line[0] == '\n' || line[0] == '\0') continue;
133 134 135 136 137

        /* Split the line into arguments for processing. */
        argv = sdssplitargs(line,&argc);
        if (argv == NULL) goto fmterr;

138 139 140 141 142 143 144
        /* Handle the special "vars" line. Don't pretend it is the last
         * line even if it actually is when generated by Redis. */
        if (strcasecmp(argv[0],"vars") == 0) {
            for (j = 1; j < argc; j += 2) {
                if (strcasecmp(argv[j],"currentEpoch") == 0) {
                    server.cluster->currentEpoch =
                            strtoull(argv[j+1],NULL,10);
145 146
                } else if (strcasecmp(argv[j],"lastVoteEpoch") == 0) {
                    server.cluster->lastVoteEpoch =
147 148
                            strtoull(argv[j+1],NULL,10);
                } else {
A
antirez 已提交
149
                    serverLog(LL_WARNING,
150 151 152 153
                        "Skipping unknown cluster config variable '%s'",
                        argv[j]);
                }
            }
154
            sdsfreesplitres(argv,argc);
155 156 157
            continue;
        }

158 159 160
        /* Regular config lines have at least eight fields */
        if (argc < 8) goto fmterr;

161 162 163 164 165 166 167
        /* Create this node if it does not exist */
        n = clusterLookupNode(argv[0]);
        if (!n) {
            n = createClusterNode(argv[0],0);
            clusterAddNode(n);
        }
        /* Address and port */
168
        if ((p = strrchr(argv[1],':')) == NULL) goto fmterr;
169 170
        *p = '\0';
        memcpy(n->ip,argv[1],strlen(argv[1])+1);
171 172 173 174 175 176 177 178 179 180 181
        char *port = p+1;
        char *busp = strchr(port,'@');
        if (busp) {
            *busp = '\0';
            busp++;
        }
        n->port = atoi(port);
        /* In older versions of nodes.conf the "@busport" part is missing.
         * In this case we set it to the default offset of 10000 from the
         * base port. */
        n->cport = busp ? atoi(busp) : n->port + CLUSTER_PORT_INCR;
182 183 184 185 186 187 188

        /* Parse flags */
        p = s = argv[2];
        while(p) {
            p = strchr(s,',');
            if (p) *p = '\0';
            if (!strcasecmp(s,"myself")) {
A
antirez 已提交
189
                serverAssert(server.cluster->myself == NULL);
190
                myself = server.cluster->myself = n;
A
antirez 已提交
191
                n->flags |= CLUSTER_NODE_MYSELF;
192
            } else if (!strcasecmp(s,"master")) {
A
antirez 已提交
193
                n->flags |= CLUSTER_NODE_MASTER;
194
            } else if (!strcasecmp(s,"slave")) {
A
antirez 已提交
195
                n->flags |= CLUSTER_NODE_SLAVE;
196
            } else if (!strcasecmp(s,"fail?")) {
A
antirez 已提交
197
                n->flags |= CLUSTER_NODE_PFAIL;
198
            } else if (!strcasecmp(s,"fail")) {
A
antirez 已提交
199
                n->flags |= CLUSTER_NODE_FAIL;
200
                n->fail_time = mstime();
201
            } else if (!strcasecmp(s,"handshake")) {
A
antirez 已提交
202
                n->flags |= CLUSTER_NODE_HANDSHAKE;
203
            } else if (!strcasecmp(s,"noaddr")) {
A
antirez 已提交
204
                n->flags |= CLUSTER_NODE_NOADDR;
205 206
            } else if (!strcasecmp(s,"nofailover")) {
                n->flags |= CLUSTER_NODE_NOFAILOVER;
207 208
            } else if (!strcasecmp(s,"noflags")) {
                /* nothing to do */
209
            } else {
A
antirez 已提交
210
                serverPanic("Unknown flag in redis cluster config file");
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
            }
            if (p) s = p+1;
        }

        /* Get master if any. Set the master and populate master's
         * slave list. */
        if (argv[3][0] != '-') {
            master = clusterLookupNode(argv[3]);
            if (!master) {
                master = createClusterNode(argv[3],0);
                clusterAddNode(master);
            }
            n->slaveof = master;
            clusterNodeAddSlave(master,n);
        }

227
        /* Set ping sent / pong received timestamps */
228 229
        if (atoi(argv[4])) n->ping_sent = mstime();
        if (atoi(argv[5])) n->pong_received = mstime();
230

231 232 233
        /* Set configEpoch for this node. */
        n->configEpoch = strtoull(argv[6],NULL,10);

234
        /* Populate hash slots served by this instance. */
235
        for (j = 8; j < argc; j++) {
236 237
            int start, stop;

A
antirez 已提交
238 239 240 241 242 243 244
            if (argv[j][0] == '[') {
                /* Here we handle migrating / importing slots */
                int slot;
                char direction;
                clusterNode *cn;

                p = strchr(argv[j],'-');
A
antirez 已提交
245
                serverAssert(p != NULL);
A
antirez 已提交
246 247 248
                *p = '\0';
                direction = p[1]; /* Either '>' or '<' */
                slot = atoi(argv[j]+1);
249
                if (slot < 0 || slot >= CLUSTER_SLOTS) goto fmterr;
A
antirez 已提交
250 251 252 253 254 255 256
                p += 3;
                cn = clusterLookupNode(p);
                if (!cn) {
                    cn = createClusterNode(p,0);
                    clusterAddNode(cn);
                }
                if (direction == '>') {
257
                    server.cluster->migrating_slots_to[slot] = cn;
A
antirez 已提交
258
                } else {
259
                    server.cluster->importing_slots_from[slot] = cn;
A
antirez 已提交
260 261 262
                }
                continue;
            } else if ((p = strchr(argv[j],'-')) != NULL) {
263 264 265 266 267 268
                *p = '\0';
                start = atoi(argv[j]);
                stop = atoi(p+1);
            } else {
                start = stop = atoi(argv[j]);
            }
269 270
            if (start < 0 || start >= CLUSTER_SLOTS) goto fmterr;
            if (stop < 0 || stop >= CLUSTER_SLOTS) goto fmterr;
271 272
            while(start <= stop) clusterAddSlot(n, start++);
        }
A
antirez 已提交
273

274
        sdsfreesplitres(argv,argc);
A
antirez 已提交
275
    }
276 277 278
    /* Config sanity check */
    if (server.cluster->myself == NULL) goto fmterr;

A
antirez 已提交
279
    zfree(line);
A
antirez 已提交
280 281
    fclose(fp);

A
antirez 已提交
282
    serverLog(LL_NOTICE,"Node configuration loaded, I'm %.40s", myself->name);
283 284 285 286 287 288 289

    /* Something that should never happen: currentEpoch smaller than
     * the max epoch found in the nodes configuration. However we handle this
     * as some form of protection against manual editing of critical files. */
    if (clusterGetMaxEpoch() > server.cluster->currentEpoch) {
        server.cluster->currentEpoch = clusterGetMaxEpoch();
    }
290
    return C_OK;
A
antirez 已提交
291 292

fmterr:
A
antirez 已提交
293
    serverLog(LL_WARNING,
A
antirez 已提交
294
        "Unrecoverable error: corrupted cluster config file.");
295
    zfree(line);
296
    if (fp) fclose(fp);
A
antirez 已提交
297 298 299
    exit(1);
}

A
antirez 已提交
300 301 302
/* Cluster node configuration is exactly the same as CLUSTER NODES output.
 *
 * This function writes the node config and returns 0, on error -1
303 304 305 306 307 308 309 310 311
 * is returned.
 *
 * Note: we need to write the file in an atomic way from the point of view
 * of the POSIX filesystem semantics, so that if the server is stopped
 * or crashes during the write, we'll end with either the old file or the
 * new one. Since we have the full payload to write available we can use
 * a single write to write the whole file. If the pre-existing file was
 * bigger we pad our payload with newlines that are anyway ignored and truncate
 * the file afterward. */
A
antirez 已提交
312
int clusterSaveConfig(int do_fsync) {
313 314
    sds ci;
    size_t content_size;
315
    struct stat sb;
A
antirez 已提交
316
    int fd;
317

318 319
    server.cluster->todo_before_sleep &= ~CLUSTER_TODO_SAVE_CONFIG;

320
    /* Get the nodes description and concatenate our "vars" directive to
321
     * save currentEpoch and lastVoteEpoch. */
A
antirez 已提交
322
    ci = clusterGenNodesDescription(CLUSTER_NODE_HANDSHAKE);
323
    ci = sdscatprintf(ci,"vars currentEpoch %llu lastVoteEpoch %llu\n",
324
        (unsigned long long) server.cluster->currentEpoch,
325
        (unsigned long long) server.cluster->lastVoteEpoch);
326
    content_size = sdslen(ci);
327

328
    if ((fd = open(server.cluster_configfile,O_WRONLY|O_CREAT,0644))
A
antirez 已提交
329
        == -1) goto err;
330 331 332

    /* Pad the new payload if the existing file length is greater. */
    if (fstat(fd,&sb) != -1) {
333
        if (sb.st_size > (off_t)content_size) {
334 335 336 337
            ci = sdsgrowzero(ci,sb.st_size);
            memset(ci+content_size,'\n',sb.st_size-content_size);
        }
    }
A
antirez 已提交
338
    if (write(fd,ci,sdslen(ci)) != (ssize_t)sdslen(ci)) goto err;
339 340 341 342
    if (do_fsync) {
        server.cluster->todo_before_sleep &= ~CLUSTER_TODO_FSYNC_CONFIG;
        fsync(fd);
    }
343 344 345 346 347 348

    /* Truncate the file if needed to remove the final \n padding that
     * is just garbage. */
    if (content_size != sdslen(ci) && ftruncate(fd,content_size) == -1) {
        /* ftruncate() failing is not a critical error. */
    }
A
antirez 已提交
349 350 351 352 353
    close(fd);
    sdsfree(ci);
    return 0;

err:
354
    if (fd != -1) close(fd);
A
antirez 已提交
355 356 357 358
    sdsfree(ci);
    return -1;
}

A
antirez 已提交
359 360
void clusterSaveConfigOrDie(int do_fsync) {
    if (clusterSaveConfig(do_fsync) == -1) {
A
antirez 已提交
361
        serverLog(LL_WARNING,"Fatal: can't update cluster config file.");
362 363 364 365
        exit(1);
    }
}

366 367 368 369 370 371 372
/* Lock the cluster config using flock(), and leaks the file descritor used to
 * acquire the lock so that the file will be locked forever.
 *
 * This works because we always update nodes.conf with a new version
 * in-place, reopening the file, and writing to it in place (later adjusting
 * the length with ftruncate()).
 *
373 374
 * On success C_OK is returned, otherwise an error is logged and
 * the function returns C_ERR to signal a lock was not acquired. */
375
int clusterLockConfig(char *filename) {
376 377 378 379 380
/* flock() does not exist on Solaris
 * and a fcntl-based solution won't help, as we constantly re-open that file,
 * which will release _all_ locks anyway
 */
#if !defined(__sun)
381 382 383 384 385
    /* To lock it, we need to open the file in a way it is created if
     * it does not exist, otherwise there is a race condition with other
     * processes. */
    int fd = open(filename,O_WRONLY|O_CREAT,0644);
    if (fd == -1) {
A
antirez 已提交
386
        serverLog(LL_WARNING,
387 388
            "Can't open %s in order to acquire a lock: %s",
            filename, strerror(errno));
389
        return C_ERR;
390 391 392 393
    }

    if (flock(fd,LOCK_EX|LOCK_NB) == -1) {
        if (errno == EWOULDBLOCK) {
A
antirez 已提交
394
            serverLog(LL_WARNING,
395 396 397 398 399
                 "Sorry, the cluster configuration file %s is already used "
                 "by a different Redis Cluster node. Please make sure that "
                 "different nodes use different cluster configuration "
                 "files.", filename);
        } else {
A
antirez 已提交
400
            serverLog(LL_WARNING,
401 402 403
                "Impossible to lock %s: %s", filename, strerror(errno));
        }
        close(fd);
404
        return C_ERR;
405 406 407
    }
    /* Lock acquired: leak the 'fd' by not closing it, so that we'll retain the
     * lock to the file as long as the process exists. */
408 409
#endif /* __sun */

410
    return C_OK;
411 412
}

413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
/* Some flags (currently just the NOFAILOVER flag) may need to be updated
 * in the "myself" node based on the current configuration of the node,
 * that may change at runtime via CONFIG SET. This function changes the
 * set of flags in myself->flags accordingly. */
void clusterUpdateMyselfFlags(void) {
    int oldflags = myself->flags;
    int nofailover = server.cluster_slave_no_failover ?
                     CLUSTER_NODE_NOFAILOVER : 0;
    myself->flags &= ~CLUSTER_NODE_NOFAILOVER;
    myself->flags |= nofailover;
    if (myself->flags != oldflags) {
        clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                             CLUSTER_TODO_UPDATE_STATE);
    }
}

A
antirez 已提交
429
void clusterInit(void) {
430
    int saveconf = 0;
431

432 433
    server.cluster = zmalloc(sizeof(clusterState));
    server.cluster->myself = NULL;
434
    server.cluster->currentEpoch = 0;
A
antirez 已提交
435
    server.cluster->state = CLUSTER_FAIL;
436
    server.cluster->size = 1;
437
    server.cluster->todo_before_sleep = 0;
438
    server.cluster->nodes = dictCreate(&clusterNodesDictType,NULL);
439 440
    server.cluster->nodes_black_list =
        dictCreate(&clusterNodesBlackListDictType,NULL);
441 442
    server.cluster->failover_auth_time = 0;
    server.cluster->failover_auth_count = 0;
443
    server.cluster->failover_auth_rank = 0;
444
    server.cluster->failover_auth_epoch = 0;
A
antirez 已提交
445
    server.cluster->cant_failover_reason = CLUSTER_CANT_FAILOVER_NONE;
446
    server.cluster->lastVoteEpoch = 0;
447 448 449 450
    for (int i = 0; i < CLUSTERMSG_TYPE_COUNT; i++) {
        server.cluster->stats_bus_messages_sent[i] = 0;
        server.cluster->stats_bus_messages_received[i] = 0;
    }
451
    server.cluster->stats_pfail_nodes = 0;
A
antirez 已提交
452 453
    memset(server.cluster->slots,0, sizeof(server.cluster->slots));
    clusterCloseAllSlots();
454 455 456

    /* Lock the cluster config file to make sure every node uses
     * its own nodes.conf. */
457
    if (clusterLockConfig(server.cluster_configfile) == C_ERR)
458 459 460
        exit(1);

    /* Load or create a new nodes configuration. */
461
    if (clusterLoadConfig(server.cluster_configfile) == C_ERR) {
A
antirez 已提交
462 463
        /* No configuration found. We will just use the random name provided
         * by the createClusterNode() function. */
464
        myself = server.cluster->myself =
A
antirez 已提交
465
            createClusterNode(NULL,CLUSTER_NODE_MYSELF|CLUSTER_NODE_MASTER);
A
antirez 已提交
466
        serverLog(LL_NOTICE,"No cluster configuration found, I'm %.40s",
467 468
            myself->name);
        clusterAddNode(myself);
469 470
        saveconf = 1;
    }
A
antirez 已提交
471
    if (saveconf) clusterSaveConfigOrDie(1);
472 473

    /* We need a listening TCP port for our cluster messaging needs. */
474
    server.cfd_count = 0;
475 476

    /* Port sanity check II
A
antirez 已提交
477 478
     * The other handshake port check is triggered too late to stop
     * us from trying to use a too-high cluster port number. */
A
antirez 已提交
479
    if (server.port > (65535-CLUSTER_PORT_INCR)) {
A
antirez 已提交
480
        serverLog(LL_WARNING, "Redis port number too high. "
481 482 483 484
                   "Cluster communication port is 10,000 port "
                   "numbers higher than your Redis port. "
                   "Your Redis port number must be "
                   "lower than 55535.");
A
antirez 已提交
485
        exit(1);
486 487
    }

A
antirez 已提交
488
    if (listenToPort(server.port+CLUSTER_PORT_INCR,
489
        server.cfd,&server.cfd_count) == C_ERR)
490 491
    {
        exit(1);
492 493 494 495 496 497
    } else {
        int j;

        for (j = 0; j < server.cfd_count; j++) {
            if (aeCreateFileEvent(server.el, server.cfd[j], AE_READABLE,
                clusterAcceptHandler, NULL) == AE_ERR)
A
antirez 已提交
498
                    serverPanic("Unrecoverable error creating Redis Cluster "
499 500
                                "file event.");
        }
A
antirez 已提交
501
    }
502

503 504 505 506
    /* The slots -> keys map is a radix tree. Initialize it here. */
    server.cluster->slots_to_keys = raxNew();
    memset(server.cluster->slots_keys_count,0,
           sizeof(server.cluster->slots_keys_count));
A
antirez 已提交
507

508 509
    /* Set myself->port / cport to my listening ports, we'll just need to
     * discover the IP address via MEET messages. */
A
antirez 已提交
510
    myself->port = server.port;
511 512 513 514 515
    myself->cport = server.port+CLUSTER_PORT_INCR;
    if (server.cluster_announce_port)
        myself->port = server.cluster_announce_port;
    if (server.cluster_announce_bus_port)
        myself->cport = server.cluster_announce_bus_port;
A
antirez 已提交
516

A
antirez 已提交
517
    server.cluster->mf_end = 0;
518
    resetManualFailover();
519
    clusterUpdateMyselfFlags();
A
antirez 已提交
520 521
}

A
antirez 已提交
522 523 524 525 526 527 528
/* Reset a node performing a soft or hard reset:
 *
 * 1) All other nodes are forget.
 * 2) All the assigned / open slots are released.
 * 3) If the node is a slave, it turns into a master.
 * 5) Only for hard reset: a new Node ID is generated.
 * 6) Only for hard reset: currentEpoch and configEpoch are set to 0.
529 530
 * 7) The new configuration is saved and the cluster state updated.
 * 8) If the node was a slave, the whole data set is flushed away. */
A
antirez 已提交
531 532 533 534 535 536 537 538 539
void clusterReset(int hard) {
    dictIterator *di;
    dictEntry *de;
    int j;

    /* Turn into master. */
    if (nodeIsSlave(myself)) {
        clusterSetNodeAsMaster(myself);
        replicationUnsetMaster();
540
        emptyDb(-1,EMPTYDB_NO_FLAGS,NULL);
A
antirez 已提交
541 542 543 544 545 546 547
    }

    /* Close slots, reset manual failover state. */
    clusterCloseAllSlots();
    resetManualFailover();

    /* Unassign all the slots. */
A
antirez 已提交
548
    for (j = 0; j < CLUSTER_SLOTS; j++) clusterDelSlot(j);
A
antirez 已提交
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566

    /* Forget all the nodes, but myself. */
    di = dictGetSafeIterator(server.cluster->nodes);
    while((de = dictNext(di)) != NULL) {
        clusterNode *node = dictGetVal(de);

        if (node == myself) continue;
        clusterDelNode(node);
    }
    dictReleaseIterator(di);

    /* Hard reset only: set epochs to 0, change node ID. */
    if (hard) {
        sds oldname;

        server.cluster->currentEpoch = 0;
        server.cluster->lastVoteEpoch = 0;
        myself->configEpoch = 0;
A
antirez 已提交
567
        serverLog(LL_WARNING, "configEpoch set to 0 via CLUSTER RESET HARD");
A
antirez 已提交
568 569 570

        /* To change the Node ID we need to remove the old name from the
         * nodes table, change the ID, and re-add back with new name. */
A
antirez 已提交
571
        oldname = sdsnewlen(myself->name, CLUSTER_NAMELEN);
A
antirez 已提交
572 573
        dictDelete(server.cluster->nodes,oldname);
        sdsfree(oldname);
A
antirez 已提交
574
        getRandomHexChars(myself->name, CLUSTER_NAMELEN);
A
antirez 已提交
575
        clusterAddNode(myself);
576
        serverLog(LL_NOTICE,"Node hard reset, now I'm %.40s", myself->name);
A
antirez 已提交
577 578 579 580 581 582 583 584
    }

    /* Make sure to persist the new config and update the state. */
    clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                         CLUSTER_TODO_UPDATE_STATE|
                         CLUSTER_TODO_FSYNC_CONFIG);
}

A
antirez 已提交
585 586 587 588 589 590
/* -----------------------------------------------------------------------------
 * CLUSTER communication link
 * -------------------------------------------------------------------------- */

clusterLink *createClusterLink(clusterNode *node) {
    clusterLink *link = zmalloc(sizeof(*link));
591
    link->ctime = mstime();
A
antirez 已提交
592 593 594 595 596 597 598 599
    link->sndbuf = sdsempty();
    link->rcvbuf = sdsempty();
    link->node = node;
    link->fd = -1;
    return link;
}

/* Free a cluster link, but does not free the associated node of course.
600
 * This function will just make sure that the original node associated
A
antirez 已提交
601 602 603
 * with this link will have the 'link' field set to NULL. */
void freeClusterLink(clusterLink *link) {
    if (link->fd != -1) {
604
        aeDeleteFileEvent(server.el, link->fd, AE_READABLE|AE_WRITABLE);
A
antirez 已提交
605 606 607 608 609 610 611 612 613
    }
    sdsfree(link->sndbuf);
    sdsfree(link->rcvbuf);
    if (link->node)
        link->node->link = NULL;
    close(link->fd);
    zfree(link);
}

614
#define MAX_CLUSTER_ACCEPTS_PER_CALL 1000
A
antirez 已提交
615 616
void clusterAcceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
    int cport, cfd;
617
    int max = MAX_CLUSTER_ACCEPTS_PER_CALL;
A
antirez 已提交
618
    char cip[NET_IP_STR_LEN];
A
antirez 已提交
619
    clusterLink *link;
A
antirez 已提交
620 621 622
    UNUSED(el);
    UNUSED(mask);
    UNUSED(privdata);
A
antirez 已提交
623

624 625 626 627
    /* If the server is starting up, don't accept cluster connections:
     * UPDATE messages may interact with the database content. */
    if (server.masterhost == NULL && server.loading) return;

628 629 630 631
    while(max--) {
        cfd = anetTcpAccept(server.neterr, fd, cip, sizeof(cip), &cport);
        if (cfd == ANET_ERR) {
            if (errno != EWOULDBLOCK)
A
antirez 已提交
632
                serverLog(LL_VERBOSE,
633
                    "Error accepting cluster node: %s", server.neterr);
634 635 636 637 638 639
            return;
        }
        anetNonBlock(NULL,cfd);
        anetEnableTcpNoDelay(NULL,cfd);

        /* Use non-blocking I/O for cluster messages. */
A
antirez 已提交
640
        serverLog(LL_VERBOSE,"Accepted cluster node %s:%d", cip, cport);
641 642 643 644 645 646 647 648
        /* Create a link object we use to handle the connection.
         * It gets passed to the readable handler when data is available.
         * Initiallly the link->node pointer is set to NULL as we don't know
         * which node is, but the right node is references once we know the
         * node identity. */
        link = createClusterLink(NULL);
        link->fd = cfd;
        aeCreateFileEvent(server.el,cfd,AE_READABLE,clusterReadHandler,link);
A
antirez 已提交
649 650 651 652 653 654 655
    }
}

/* -----------------------------------------------------------------------------
 * Key space handling
 * -------------------------------------------------------------------------- */

656
/* We have 16384 hash slots. The hash slot of a given key is obtained
657 658 659 660 661
 * as the least significant 14 bits of the crc16 of the key.
 *
 * However if the key contains the {...} pattern, only the part between
 * { and } is hashed. This may be useful in the future to force certain
 * keys to be in the same node (assuming no resharding is in progress). */
A
antirez 已提交
662
unsigned int keyHashSlot(char *key, int keylen) {
663 664 665 666 667 668 669 670 671 672 673 674
    int s, e; /* start-end indexes of { and } */

    for (s = 0; s < keylen; s++)
        if (key[s] == '{') break;

    /* No '{' ? Hash the whole key. This is the base case. */
    if (s == keylen) return crc16(key,keylen) & 0x3FFF;

    /* '{' found? Check if we have the corresponding '}'. */
    for (e = s+1; e < keylen; e++)
        if (key[e] == '}') break;

S
Shaun Webb 已提交
675
    /* No '}' or nothing between {} ? Hash the whole key. */
676 677 678 679 680
    if (e == keylen || e == s+1) return crc16(key,keylen) & 0x3FFF;

    /* If we are here there is both a { and a } on its right. Hash
     * what is in the middle between { and }. */
    return crc16(key+s+1,e-s-1) & 0x3FFF;
A
antirez 已提交
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
}

/* -----------------------------------------------------------------------------
 * CLUSTER node API
 * -------------------------------------------------------------------------- */

/* Create a new cluster node, with the specified flags.
 * If "nodename" is NULL this is considered a first handshake and a random
 * node name is assigned to this node (it will be fixed later when we'll
 * receive the first pong).
 *
 * The node is created and returned to the user, but it is not automatically
 * added to the nodes hash table. */
clusterNode *createClusterNode(char *nodename, int flags) {
    clusterNode *node = zmalloc(sizeof(*node));

    if (nodename)
A
antirez 已提交
698
        memcpy(node->name, nodename, CLUSTER_NAMELEN);
A
antirez 已提交
699
    else
A
antirez 已提交
700
        getRandomHexChars(node->name, CLUSTER_NAMELEN);
701
    node->ctime = mstime();
702
    node->configEpoch = 0;
A
antirez 已提交
703 704
    node->flags = flags;
    memset(node->slots,0,sizeof(node->slots));
705
    node->numslots = 0;
A
antirez 已提交
706 707 708 709
    node->numslaves = 0;
    node->slaves = NULL;
    node->slaveof = NULL;
    node->ping_sent = node->pong_received = 0;
A
antirez 已提交
710
    node->fail_time = 0;
A
antirez 已提交
711
    node->link = NULL;
712
    memset(node->ip,0,sizeof(node->ip));
713
    node->port = 0;
714
    node->cport = 0;
715
    node->fail_reports = listCreate();
716
    node->voted_time = 0;
A
antirez 已提交
717
    node->orphaned_time = 0;
718 719
    node->repl_offset_time = 0;
    node->repl_offset = 0;
720
    listSetFreeMethod(node->fail_reports,zfree);
A
antirez 已提交
721 722 723
    return node;
}

724 725 726 727 728
/* This function is called every time we get a failure report from a node.
 * The side effect is to populate the fail_reports list (or to update
 * the timestamp of an existing report).
 *
 * 'failing' is the node that is in failure state according to the
729 730 731 732 733 734
 * 'sender' node.
 *
 * The function returns 0 if it just updates a timestamp of an existing
 * failure report from the same sender. 1 is returned if a new failure
 * report is created. */
int clusterNodeAddFailureReport(clusterNode *failing, clusterNode *sender) {
735 736 737 738 739 740 741 742 743 744 745
    list *l = failing->fail_reports;
    listNode *ln;
    listIter li;
    clusterNodeFailReport *fr;

    /* If a failure report from the same sender already exists, just update
     * the timestamp. */
    listRewind(l,&li);
    while ((ln = listNext(&li)) != NULL) {
        fr = ln->value;
        if (fr->node == sender) {
746
            fr->time = mstime();
747
            return 0;
748 749 750 751 752 753
        }
    }

    /* Otherwise create a new report. */
    fr = zmalloc(sizeof(*fr));
    fr->node = sender;
754
    fr->time = mstime();
755
    listAddNodeTail(l,fr);
756
    return 1;
757 758
}

759 760 761 762 763 764 765 766 767 768
/* Remove failure reports that are too old, where too old means reasonably
 * older than the global node timeout. Note that anyway for a node to be
 * flagged as FAIL we need to have a local PFAIL state that is at least
 * older than the global node timeout, so we don't just trust the number
 * of failure reports from other nodes. */
void clusterNodeCleanupFailureReports(clusterNode *node) {
    list *l = node->fail_reports;
    listNode *ln;
    listIter li;
    clusterNodeFailReport *fr;
769
    mstime_t maxtime = server.cluster_node_timeout *
A
antirez 已提交
770
                     CLUSTER_FAIL_REPORT_VALIDITY_MULT;
771
    mstime_t now = mstime();
772 773 774 775 776 777 778 779

    listRewind(l,&li);
    while ((ln = listNext(&li)) != NULL) {
        fr = ln->value;
        if (now - fr->time > maxtime) listDelNode(l,ln);
    }
}

780 781 782 783 784 785 786
/* Remove the failing report for 'node' if it was previously considered
 * failing by 'sender'. This function is called when a node informs us via
 * gossip that a node is OK from its point of view (no FAIL or PFAIL flags).
 *
 * Note that this function is called relatively often as it gets called even
 * when there are no nodes failing, and is O(N), however when the cluster is
 * fine the failure reports list is empty so the function runs in constant
787 788 789 790 791
 * time.
 *
 * The function returns 1 if the failure report was found and removed.
 * Otherwise 0 is returned. */
int clusterNodeDelFailureReport(clusterNode *node, clusterNode *sender) {
792 793 794 795 796 797 798 799 800 801 802
    list *l = node->fail_reports;
    listNode *ln;
    listIter li;
    clusterNodeFailReport *fr;

    /* Search for a failure report from this sender. */
    listRewind(l,&li);
    while ((ln = listNext(&li)) != NULL) {
        fr = ln->value;
        if (fr->node == sender) break;
    }
803
    if (!ln) return 0; /* No failure report from this sender. */
804 805 806

    /* Remove the failure report. */
    listDelNode(l,ln);
807
    clusterNodeCleanupFailureReports(node);
808
    return 1;
809 810
}

811 812 813 814 815 816 817 818
/* Return the number of external nodes that believe 'node' is failing,
 * not including this node, that may have a PFAIL or FAIL state for this
 * node as well. */
int clusterNodeFailureReportsCount(clusterNode *node) {
    clusterNodeCleanupFailureReports(node);
    return listLength(node->fail_reports);
}

A
antirez 已提交
819 820 821 822 823
int clusterNodeRemoveSlave(clusterNode *master, clusterNode *slave) {
    int j;

    for (j = 0; j < master->numslaves; j++) {
        if (master->slaves[j] == slave) {
824 825 826 827 828
            if ((j+1) < master->numslaves) {
                int remaining_slaves = (master->numslaves - j) - 1;
                memmove(master->slaves+j,master->slaves+(j+1),
                        (sizeof(*master->slaves) * remaining_slaves));
            }
A
antirez 已提交
829
            master->numslaves--;
830 831
            if (master->numslaves == 0)
                master->flags &= ~CLUSTER_NODE_MIGRATE_TO;
832
            return C_OK;
A
antirez 已提交
833 834
        }
    }
835
    return C_ERR;
A
antirez 已提交
836 837 838 839 840 841 842
}

int clusterNodeAddSlave(clusterNode *master, clusterNode *slave) {
    int j;

    /* If it's already a slave, don't add it again. */
    for (j = 0; j < master->numslaves; j++)
843
        if (master->slaves[j] == slave) return C_ERR;
A
antirez 已提交
844 845 846 847
    master->slaves = zrealloc(master->slaves,
        sizeof(clusterNode*)*(master->numslaves+1));
    master->slaves[master->numslaves] = slave;
    master->numslaves++;
848
    master->flags |= CLUSTER_NODE_MIGRATE_TO;
849
    return C_OK;
A
antirez 已提交
850 851
}

852 853 854 855 856 857 858 859
int clusterCountNonFailingSlaves(clusterNode *n) {
    int j, okslaves = 0;

    for (j = 0; j < n->numslaves; j++)
        if (!nodeFailed(n->slaves[j])) okslaves++;
    return okslaves;
}

860
/* Low level cleanup of the node structure. Only called by clusterDelNode(). */
A
antirez 已提交
861 862
void freeClusterNode(clusterNode *n) {
    sds nodename;
863 864
    int j;

865
    /* If the node has associated slaves, we have to set
866
     * all the slaves->slaveof fields to NULL (unknown). */
867 868
    for (j = 0; j < n->numslaves; j++)
        n->slaves[j]->slaveof = NULL;
869

870 871 872 873
    /* Remove this node from the list of slaves of its master. */
    if (nodeIsSlave(n) && n->slaveof) clusterNodeRemoveSlave(n->slaveof,n);

    /* Unlink from the set of nodes. */
A
antirez 已提交
874
    nodename = sdsnewlen(n->name, CLUSTER_NAMELEN);
A
antirez 已提交
875
    serverAssert(dictDelete(server.cluster->nodes,nodename) == DICT_OK);
A
antirez 已提交
876
    sdsfree(nodename);
877 878

    /* Release link and associated data structures. */
A
antirez 已提交
879
    if (n->link) freeClusterLink(n->link);
880
    listRelease(n->fail_reports);
M
Matt Stancliff 已提交
881
    zfree(n->slaves);
A
antirez 已提交
882 883 884 885 886 887
    zfree(n);
}

/* Add a node to the nodes hash table */
int clusterAddNode(clusterNode *node) {
    int retval;
888

889
    retval = dictAdd(server.cluster->nodes,
A
antirez 已提交
890
            sdsnewlen(node->name,CLUSTER_NAMELEN), node);
891
    return (retval == DICT_OK) ? C_OK : C_ERR;
A
antirez 已提交
892 893
}

894 895 896 897 898 899 900 901 902 903
/* Remove a node from the cluster. The functio performs the high level
 * cleanup, calling freeClusterNode() for the low level cleanup.
 * Here we do the following:
 *
 * 1) Mark all the slots handled by it as unassigned.
 * 2) Remove all the failure reports sent by this node and referenced by
 *    other nodes.
 * 3) Free the node with freeClusterNode() that will in turn remove it
 *    from the hash table and from the list of slaves of its master, if
 *    it is a slave node.
A
antirez 已提交
904 905 906 907 908 909 910
 */
void clusterDelNode(clusterNode *delnode) {
    int j;
    dictIterator *di;
    dictEntry *de;

    /* 1) Mark slots as unassigned. */
A
antirez 已提交
911
    for (j = 0; j < CLUSTER_SLOTS; j++) {
A
antirez 已提交
912 913 914 915 916 917 918 919 920
        if (server.cluster->importing_slots_from[j] == delnode)
            server.cluster->importing_slots_from[j] = NULL;
        if (server.cluster->migrating_slots_to[j] == delnode)
            server.cluster->migrating_slots_to[j] = NULL;
        if (server.cluster->slots[j] == delnode)
            clusterDelSlot(j);
    }

    /* 2) Remove failure reports. */
921
    di = dictGetSafeIterator(server.cluster->nodes);
A
antirez 已提交
922 923 924 925 926 927 928 929
    while((de = dictNext(di)) != NULL) {
        clusterNode *node = dictGetVal(de);

        if (node == delnode) continue;
        clusterNodeDelFailureReport(node,delnode);
    }
    dictReleaseIterator(di);

930
    /* 3) Free the node, unlinking it from the cluster. */
A
antirez 已提交
931 932 933
    freeClusterNode(delnode);
}

A
antirez 已提交
934
/* Node lookup by name */
935
clusterNode *clusterLookupNode(const char *name) {
A
antirez 已提交
936
    sds s = sdsnewlen(name, CLUSTER_NAMELEN);
A
antirez 已提交
937
    dictEntry *de;
A
antirez 已提交
938

939
    de = dictFind(server.cluster->nodes,s);
A
antirez 已提交
940 941
    sdsfree(s);
    if (de == NULL) return NULL;
942
    return dictGetVal(de);
A
antirez 已提交
943 944 945 946 947 948 949 950
}

/* This is only used after the handshake. When we connect a given IP/PORT
 * as a result of CLUSTER MEET we don't have the node name yet, so we
 * pick a random one, and will fix it when we receive the PONG request using
 * this function. */
void clusterRenameNode(clusterNode *node, char *newname) {
    int retval;
A
antirez 已提交
951
    sds s = sdsnewlen(node->name, CLUSTER_NAMELEN);
952

A
antirez 已提交
953
    serverLog(LL_DEBUG,"Renaming node %.40s into %.40s",
A
antirez 已提交
954
        node->name, newname);
955
    retval = dictDelete(server.cluster->nodes, s);
A
antirez 已提交
956
    sdsfree(s);
A
antirez 已提交
957
    serverAssert(retval == DICT_OK);
A
antirez 已提交
958
    memcpy(node->name, newname, CLUSTER_NAMELEN);
A
antirez 已提交
959 960 961
    clusterAddNode(node);
}

962 963 964 965
/* -----------------------------------------------------------------------------
 * CLUSTER config epoch handling
 * -------------------------------------------------------------------------- */

A
antirez 已提交
966 967
/* Return the greatest configEpoch found in the cluster, or the current
 * epoch if greater than any node configEpoch. */
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
uint64_t clusterGetMaxEpoch(void) {
    uint64_t max = 0;
    dictIterator *di;
    dictEntry *de;

    di = dictGetSafeIterator(server.cluster->nodes);
    while((de = dictNext(di)) != NULL) {
        clusterNode *node = dictGetVal(de);
        if (node->configEpoch > max) max = node->configEpoch;
    }
    dictReleaseIterator(di);
    if (max < server.cluster->currentEpoch) max = server.cluster->currentEpoch;
    return max;
}

/* If this node epoch is zero or is not already the greatest across the
 * cluster (from the POV of the local configuration), this function will:
 *
986
 * 1) Generate a new config epoch, incrementing the current epoch.
987 988 989 990
 * 2) Assign the new epoch to this node, WITHOUT any consensus.
 * 3) Persist the configuration on disk before sending packets with the
 *    new configuration.
 *
991 992
 * If the new config epoch is generated and assigend, C_OK is returned,
 * otherwise C_ERR is returned (since the node has already the greatest
993 994 995 996 997 998 999 1000
 * configuration around) and no operation is performed.
 *
 * Important note: this function violates the principle that config epochs
 * should be generated with consensus and should be unique across the cluster.
 * However Redis Cluster uses this auto-generated new config epochs in two
 * cases:
 *
 * 1) When slots are closed after importing. Otherwise resharding would be
I
Itamar Haber 已提交
1001
 *    too expensive.
1002 1003 1004 1005
 * 2) When CLUSTER FAILOVER is called with options that force a slave to
 *    failover its master even if there is not master majority able to
 *    create a new configuration epoch.
 *
1006
 * Redis Cluster will not explode using this function, even in the case of
1007 1008 1009
 * a collision between this node and another node, generating the same
 * configuration epoch unilaterally, because the config epoch conflict
 * resolution algorithm will eventually move colliding nodes to different
1010
 * config epochs. However using this function may violate the "last failover
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
 * wins" rule, so should only be used with care. */
int clusterBumpConfigEpochWithoutConsensus(void) {
    uint64_t maxEpoch = clusterGetMaxEpoch();

    if (myself->configEpoch == 0 ||
        myself->configEpoch != maxEpoch)
    {
        server.cluster->currentEpoch++;
        myself->configEpoch = server.cluster->currentEpoch;
        clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                             CLUSTER_TODO_FSYNC_CONFIG);
A
antirez 已提交
1022
        serverLog(LL_WARNING,
1023 1024
            "New configEpoch set to %llu",
            (unsigned long long) myself->configEpoch);
1025
        return C_OK;
1026
    } else {
1027
        return C_ERR;
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
    }
}

/* This function is called when this node is a master, and we receive from
 * another master a configuration epoch that is equal to our configuration
 * epoch.
 *
 * BACKGROUND
 *
 * It is not possible that different slaves get the same config
 * epoch during a failover election, because the slaves need to get voted
 * by a majority. However when we perform a manual resharding of the cluster
 * the node will assign a configuration epoch to itself without to ask
 * for agreement. Usually resharding happens when the cluster is working well
 * and is supervised by the sysadmin, however it is possible for a failover
 * to happen exactly while the node we are resharding a slot to assigns itself
 * a new configuration epoch, but before it is able to propagate it.
 *
 * So technically it is possible in this condition that two nodes end with
 * the same configuration epoch.
 *
 * Another possibility is that there are bugs in the implementation causing
 * this to happen.
 *
 * Moreover when a new cluster is created, all the nodes start with the same
 * configEpoch. This collision resolution code allows nodes to automatically
 * end with a different configEpoch at startup automatically.
 *
 * In all the cases, we want a mechanism that resolves this issue automatically
 * as a safeguard. The same configuration epoch for masters serving different
 * set of slots is not harmful, but it is if the nodes end serving the same
 * slots for some reason (manual errors or software bugs) without a proper
 * failover procedure.
 *
 * In general we want a system that eventually always ends with different
 * masters having different configuration epochs whatever happened, since
 * nothign is worse than a split-brain condition in a distributed system.
 *
 * BEHAVIOR
 *
 * When this function gets called, what happens is that if this node
 * has the lexicographically smaller Node ID compared to the other node
 * with the conflicting epoch (the 'sender' node), it will assign itself
 * the greatest configuration epoch currently detected among nodes plus 1.
 *
 * This means that even if there are multiple nodes colliding, the node
 * with the greatest Node ID never moves forward, so eventually all the nodes
 * end with a different configuration epoch.
 */
void clusterHandleConfigEpochCollision(clusterNode *sender) {
    /* Prerequisites: nodes have the same configEpoch and are both masters. */
    if (sender->configEpoch != myself->configEpoch ||
        !nodeIsMaster(sender) || !nodeIsMaster(myself)) return;
    /* Don't act if the colliding node has a smaller Node ID. */
A
antirez 已提交
1082
    if (memcmp(sender->name,myself->name,CLUSTER_NAMELEN) <= 0) return;
1083 1084 1085 1086
    /* Get the next ID available at the best of this node knowledge. */
    server.cluster->currentEpoch++;
    myself->configEpoch = server.cluster->currentEpoch;
    clusterSaveConfigOrDie(1);
A
antirez 已提交
1087
    serverLog(LL_VERBOSE,
1088 1089 1090 1091 1092 1093
        "WARNING: configEpoch collision with node %.40s."
        " configEpoch set to %llu",
        sender->name,
        (unsigned long long) myself->configEpoch);
}

1094 1095 1096 1097 1098
/* -----------------------------------------------------------------------------
 * CLUSTER nodes blacklist
 *
 * The nodes blacklist is just a way to ensure that a given node with a given
 * Node ID is not readded before some time elapsed (this time is specified
A
antirez 已提交
1099
 * in seconds in CLUSTER_BLACKLIST_TTL).
1100 1101 1102 1103 1104 1105
 *
 * This is useful when we want to remove a node from the cluster completely:
 * when CLUSTER FORGET is called, it also puts the node into the blacklist so
 * that even if we receive gossip messages from other nodes that still remember
 * about the node we want to remove, we don't re-add it before some time.
 *
A
antirez 已提交
1106
 * Currently the CLUSTER_BLACKLIST_TTL is set to 1 minute, this means
1107
 * that redis-trib has 60 seconds to send CLUSTER FORGET messages to nodes
1108
 * in the cluster without dealing with the problem of other nodes re-adding
1109 1110
 * back the node to nodes we already sent the FORGET command to.
 *
1111
 * The data structure used is a hash table with an sds string representing
1112 1113 1114 1115
 * the node ID as key, and the time when it is ok to re-add the node as
 * value.
 * -------------------------------------------------------------------------- */

A
antirez 已提交
1116
#define CLUSTER_BLACKLIST_TTL 60      /* 1 minute. */
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141


/* Before of the addNode() or Exists() operations we always remove expired
 * entries from the black list. This is an O(N) operation but it is not a
 * problem since add / exists operations are called very infrequently and
 * the hash table is supposed to contain very little elements at max.
 * However without the cleanup during long uptimes and with some automated
 * node add/removal procedures, entries could accumulate. */
void clusterBlacklistCleanup(void) {
    dictIterator *di;
    dictEntry *de;

    di = dictGetSafeIterator(server.cluster->nodes_black_list);
    while((de = dictNext(di)) != NULL) {
        int64_t expire = dictGetUnsignedIntegerVal(de);

        if (expire < server.unixtime)
            dictDelete(server.cluster->nodes_black_list,dictGetKey(de));
    }
    dictReleaseIterator(di);
}

/* Cleanup the blacklist and add a new node ID to the black list. */
void clusterBlacklistAddNode(clusterNode *node) {
    dictEntry *de;
A
antirez 已提交
1142
    sds id = sdsnewlen(node->name,CLUSTER_NAMELEN);
1143 1144

    clusterBlacklistCleanup();
1145 1146 1147 1148 1149 1150
    if (dictAdd(server.cluster->nodes_black_list,id,NULL) == DICT_OK) {
        /* If the key was added, duplicate the sds string representation of
         * the key for the next lookup. We'll free it at the end. */
        id = sdsdup(id);
    }
    de = dictFind(server.cluster->nodes_black_list,id);
A
antirez 已提交
1151
    dictSetUnsignedIntegerVal(de,time(NULL)+CLUSTER_BLACKLIST_TTL);
1152
    sdsfree(id);
1153 1154 1155 1156 1157 1158
}

/* Return non-zero if the specified node ID exists in the blacklist.
 * You don't need to pass an sds string here, any pointer to 40 bytes
 * will work. */
int clusterBlacklistExists(char *nodeid) {
A
antirez 已提交
1159
    sds id = sdsnewlen(nodeid,CLUSTER_NAMELEN);
1160 1161
    int retval;

1162
    clusterBlacklistCleanup();
1163 1164 1165 1166 1167
    retval = dictFind(server.cluster->nodes_black_list,id) != NULL;
    sdsfree(id);
    return retval;
}

A
antirez 已提交
1168 1169 1170 1171
/* -----------------------------------------------------------------------------
 * CLUSTER messages exchange - PING/PONG and gossip
 * -------------------------------------------------------------------------- */

1172 1173 1174
/* This function checks if a given node should be marked as FAIL.
 * It happens if the following conditions are met:
 *
1175 1176 1177 1178
 * 1) We received enough failure reports from other master nodes via gossip.
 *    Enough means that the majority of the masters signaled the node is
 *    down recently.
 * 2) We believe this node is in PFAIL state.
1179 1180 1181
 *
 * If a failure is detected we also inform the whole cluster about this
 * event trying to force every other node to set the FAIL flag for the node.
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
 *
 * Note that the form of agreement used here is weak, as we collect the majority
 * of masters state during some time, and even if we force agreement by
 * propagating the FAIL message, because of partitions we may not reach every
 * node. However:
 *
 * 1) Either we reach the majority and eventually the FAIL state will propagate
 *    to all the cluster.
 * 2) Or there is no majority so no slave promotion will be authorized and the
 *    FAIL flag will be cleared after some time.
1192 1193 1194 1195 1196
 */
void markNodeAsFailingIfNeeded(clusterNode *node) {
    int failures;
    int needed_quorum = (server.cluster->size / 2) + 1;

1197 1198
    if (!nodeTimedOut(node)) return; /* We can reach it. */
    if (nodeFailed(node)) return; /* Already FAILing. */
1199

1200 1201
    failures = clusterNodeFailureReportsCount(node);
    /* Also count myself as a voter if I'm a master. */
1202
    if (nodeIsMaster(myself)) failures++;
1203
    if (failures < needed_quorum) return; /* No weak agreement from masters. */
1204

A
antirez 已提交
1205
    serverLog(LL_NOTICE,
1206 1207 1208
        "Marking node %.40s as failing (quorum reached).", node->name);

    /* Mark the node as failing. */
A
antirez 已提交
1209 1210
    node->flags &= ~CLUSTER_NODE_PFAIL;
    node->flags |= CLUSTER_NODE_FAIL;
1211
    node->fail_time = mstime();
1212

1213 1214
    /* Broadcast the failing node name to everybody, forcing all the other
     * reachable nodes to flag the node as FAIL. */
1215
    if (nodeIsMaster(myself)) clusterSendFail(node->name);
A
antirez 已提交
1216
    clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
1217 1218 1219 1220
}

/* This function is called only if a node is marked as FAIL, but we are able
 * to reach it again. It checks if there are the conditions to undo the FAIL
1221
 * state. */
1222
void clearNodeFailureIfNeeded(clusterNode *node) {
1223
    mstime_t now = mstime();
A
antirez 已提交
1224

A
antirez 已提交
1225
    serverAssert(nodeFailed(node));
A
antirez 已提交
1226 1227 1228

    /* For slaves we always clear the FAIL flag if we can contact the
     * node again. */
1229
    if (nodeIsSlave(node) || node->numslots == 0) {
A
antirez 已提交
1230
        serverLog(LL_NOTICE,
1231
            "Clear FAIL state for node %.40s: %s is reachable again.",
1232
                node->name,
1233
                nodeIsSlave(node) ? "replica" : "master without slots");
A
antirez 已提交
1234
        node->flags &= ~CLUSTER_NODE_FAIL;
A
antirez 已提交
1235
        clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
A
antirez 已提交
1236 1237 1238
    }

    /* If it is a master and...
1239
     * 1) The FAIL state is old enough.
A
antirez 已提交
1240 1241
     * 2) It is yet serving slots from our point of view (not failed over).
     * Apparently no one is going to fix these slots, clear the FAIL flag. */
1242
    if (nodeIsMaster(node) && node->numslots > 0 &&
1243
        (now - node->fail_time) >
A
antirez 已提交
1244
        (server.cluster_node_timeout * CLUSTER_FAIL_UNDO_TIME_MULT))
A
antirez 已提交
1245
    {
A
antirez 已提交
1246
        serverLog(LL_NOTICE,
A
antirez 已提交
1247
            "Clear FAIL state for node %.40s: is reachable again and nobody is serving its slots after some time.",
1248
                node->name);
A
antirez 已提交
1249
        node->flags &= ~CLUSTER_NODE_FAIL;
A
antirez 已提交
1250
        clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
1251 1252 1253
    }
}

1254 1255 1256
/* Return true if we already have a node in HANDSHAKE state matching the
 * specified ip address and port number. This function is used in order to
 * avoid adding a new handshake node for the same address multiple times. */
1257
int clusterHandshakeInProgress(char *ip, int port, int cport) {
1258 1259 1260 1261 1262 1263 1264
    dictIterator *di;
    dictEntry *de;

    di = dictGetSafeIterator(server.cluster->nodes);
    while((de = dictNext(di)) != NULL) {
        clusterNode *node = dictGetVal(de);

1265
        if (!nodeInHandshake(node)) continue;
1266 1267 1268
        if (!strcasecmp(node->ip,ip) &&
            node->port == port &&
            node->cport == cport) break;
1269 1270 1271 1272 1273
    }
    dictReleaseIterator(di);
    return de != NULL;
}

1274 1275 1276 1277 1278 1279 1280
/* Start an handshake with the specified address if there is not one
 * already in progress. Returns non-zero if the handshake was actually
 * started. On error zero is returned and errno is set to one of the
 * following values:
 *
 * EAGAIN - There is already an handshake in progress for this address.
 * EINVAL - IP or port are not valid. */
1281
int clusterStartHandshake(char *ip, int port, int cport) {
1282
    clusterNode *n;
A
antirez 已提交
1283
    char norm_ip[NET_IP_STR_LEN];
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
    struct sockaddr_storage sa;

    /* IP sanity check */
    if (inet_pton(AF_INET,ip,
            &(((struct sockaddr_in *)&sa)->sin_addr)))
    {
        sa.ss_family = AF_INET;
    } else if (inet_pton(AF_INET6,ip,
            &(((struct sockaddr_in6 *)&sa)->sin6_addr)))
    {
        sa.ss_family = AF_INET6;
    } else {
        errno = EINVAL;
        return 0;
    }

    /* Port sanity check */
1301
    if (port <= 0 || port > 65535 || cport <= 0 || cport > 65535) {
1302 1303 1304 1305 1306 1307
        errno = EINVAL;
        return 0;
    }

    /* Set norm_ip as the normalized string representation of the node
     * IP address. */
A
antirez 已提交
1308
    memset(norm_ip,0,NET_IP_STR_LEN);
1309 1310 1311
    if (sa.ss_family == AF_INET)
        inet_ntop(AF_INET,
            (void*)&(((struct sockaddr_in *)&sa)->sin_addr),
A
antirez 已提交
1312
            norm_ip,NET_IP_STR_LEN);
1313 1314 1315
    else
        inet_ntop(AF_INET6,
            (void*)&(((struct sockaddr_in6 *)&sa)->sin6_addr),
A
antirez 已提交
1316
            norm_ip,NET_IP_STR_LEN);
1317

1318
    if (clusterHandshakeInProgress(norm_ip,port,cport)) {
1319 1320 1321 1322 1323 1324
        errno = EAGAIN;
        return 0;
    }

    /* Add the node with a random address (NULL as first argument to
     * createClusterNode()). Everything will be fixed during the
1325
     * handshake. */
A
antirez 已提交
1326
    n = createClusterNode(NULL,CLUSTER_NODE_HANDSHAKE|CLUSTER_NODE_MEET);
1327 1328
    memcpy(n->ip,norm_ip,sizeof(n->ip));
    n->port = port;
1329
    n->cport = cport;
1330 1331 1332 1333
    clusterAddNode(n);
    return 1;
}

A
antirez 已提交
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
/* Process the gossip section of PING or PONG packets.
 * Note that this function assumes that the packet is already sanity-checked
 * by the caller, not in the content of the gossip section, but in the
 * length. */
void clusterProcessGossipSection(clusterMsg *hdr, clusterLink *link) {
    uint16_t count = ntohs(hdr->count);
    clusterMsgDataGossip *g = (clusterMsgDataGossip*) hdr->data.ping.gossip;
    clusterNode *sender = link->node ? link->node : clusterLookupNode(hdr->sender);

    while(count--) {
        uint16_t flags = ntohs(g->flags);
        clusterNode *node;
1346
        sds ci;
A
antirez 已提交
1347

1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
        if (server.verbosity == LL_DEBUG) {
            ci = representClusterNodeFlags(sdsempty(), flags);
            serverLog(LL_DEBUG,"GOSSIP %.40s %s:%d@%d %s",
                g->nodename,
                g->ip,
                ntohs(g->port),
                ntohs(g->cport),
                ci);
            sdsfree(ci);
        }
A
antirez 已提交
1358 1359 1360

        /* Update our state accordingly to the gossip sections */
        node = clusterLookupNode(g->nodename);
1361
        if (node) {
1362 1363
            /* We already know this node.
               Handle failure reports, only when the sender is a master. */
1364
            if (sender && nodeIsMaster(sender) && node != myself) {
A
antirez 已提交
1365
                if (flags & (CLUSTER_NODE_FAIL|CLUSTER_NODE_PFAIL)) {
1366
                    if (clusterNodeAddFailureReport(node,sender)) {
A
antirez 已提交
1367
                        serverLog(LL_VERBOSE,
1368 1369 1370 1371 1372 1373
                            "Node %.40s reported node %.40s as not reachable.",
                            sender->name, node->name);
                    }
                    markNodeAsFailingIfNeeded(node);
                } else {
                    if (clusterNodeDelFailureReport(node,sender)) {
A
antirez 已提交
1374
                        serverLog(LL_VERBOSE,
1375 1376 1377 1378
                            "Node %.40s reported node %.40s is back online.",
                            sender->name, node->name);
                    }
                }
A
antirez 已提交
1379
            }
1380

1381 1382 1383 1384 1385 1386 1387 1388
            /* If from our POV the node is up (no failure flags are set),
             * we have no pending ping for the node, nor we have failure
             * reports for this node, update the last pong time with the
             * one we see from the other nodes. */
            if (!(flags & (CLUSTER_NODE_FAIL|CLUSTER_NODE_PFAIL)) &&
                node->ping_sent == 0 &&
                clusterNodeFailureReportsCount(node) == 0)
            {
1389 1390
                mstime_t pongtime = ntohl(g->pong_received);
                pongtime *= 1000; /* Convert back to milliseconds. */
1391 1392 1393 1394 1395 1396 1397 1398

                /* Replace the pong time with the received one only if
                 * it's greater than our view but is not in the future
                 * (with 500 milliseconds tolerance) from the POV of our
                 * clock. */
                if (pongtime <= (server.mstime+500) &&
                    pongtime > node->pong_received)
                {
1399
                    node->pong_received = pongtime;
1400
                }
1401 1402
            }

1403
            /* If we already know this node, but it is not reachable, and
1404 1405 1406 1407
             * we see a different address in the gossip section of a node that
             * can talk with this other node, update the address, disconnect
             * the old link if any, so that we'll attempt to connect with the
             * new address. */
A
antirez 已提交
1408
            if (node->flags & (CLUSTER_NODE_FAIL|CLUSTER_NODE_PFAIL) &&
1409 1410
                !(flags & CLUSTER_NODE_NOADDR) &&
                !(flags & (CLUSTER_NODE_FAIL|CLUSTER_NODE_PFAIL)) &&
1411 1412 1413
                (strcasecmp(node->ip,g->ip) ||
                 node->port != ntohs(g->port) ||
                 node->cport != ntohs(g->cport)))
1414
            {
1415 1416
                if (node->link) freeClusterLink(node->link);
                memcpy(node->ip,g->ip,NET_IP_STR_LEN);
1417
                node->port = ntohs(g->port);
1418
                node->cport = ntohs(g->cport);
1419
                node->flags &= ~CLUSTER_NODE_NOADDR;
1420
            }
A
antirez 已提交
1421 1422
        } else {
            /* If it's not in NOADDR state and we don't have it, we
1423
             * start a handshake process against this IP/PORT pairs.
A
antirez 已提交
1424 1425 1426 1427
             *
             * Note that we require that the sender of this gossip message
             * is a well known node in our cluster, otherwise we risk
             * joining another cluster. */
1428
            if (sender &&
A
antirez 已提交
1429
                !(flags & CLUSTER_NODE_NOADDR) &&
1430 1431
                !clusterBlacklistExists(g->nodename))
            {
1432
                clusterStartHandshake(g->ip,ntohs(g->port),ntohs(g->cport));
1433
            }
A
antirez 已提交
1434 1435 1436 1437 1438 1439 1440
        }

        /* Next node */
        g++;
    }
}

1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
/* IP -> string conversion. 'buf' is supposed to at least be 46 bytes.
 * If 'announced_ip' length is non-zero, it is used instead of extracting
 * the IP from the socket peer address. */
void nodeIp2String(char *buf, clusterLink *link, char *announced_ip) {
    if (announced_ip[0] != '\0') {
        memcpy(buf,announced_ip,NET_IP_STR_LEN);
        buf[NET_IP_STR_LEN-1] = '\0'; /* We are not sure the input is sane. */
    } else {
        anetPeerToString(link->fd, buf, NET_IP_STR_LEN, NULL);
    }
A
antirez 已提交
1451 1452 1453
}

/* Update the node address to the IP address that can be extracted
1454 1455 1456 1457 1458
 * from link->fd, or if hdr->myip is non empty, to the address the node
 * is announcing us. The port is taken from the packet header as well.
 *
 * If the address or port changed, disconnect the node link so that we'll
 * connect again to the new address.
A
antirez 已提交
1459 1460 1461 1462 1463 1464
 *
 * If the ip/port pair are already correct no operation is performed at
 * all.
 *
 * The function returns 0 if the node address is still the same,
 * otherwise 1 is returned. */
1465 1466 1467
int nodeUpdateAddressIfNeeded(clusterNode *node, clusterLink *link,
                              clusterMsg *hdr)
{
A
antirez 已提交
1468
    char ip[NET_IP_STR_LEN] = {0};
1469 1470
    int port = ntohs(hdr->port);
    int cport = ntohs(hdr->cport);
A
antirez 已提交
1471 1472 1473 1474 1475 1476 1477 1478 1479

    /* We don't proceed if the link is the same as the sender link, as this
     * function is designed to see if the node link is consistent with the
     * symmetric link that is used to receive PINGs from the node.
     *
     * As a side effect this function never frees the passed 'link', so
     * it is safe to call during packet processing. */
    if (link == node->link) return 0;

1480 1481 1482
    nodeIp2String(ip,link,hdr->myip);
    if (node->port == port && node->cport == cport &&
        strcmp(ip,node->ip) == 0) return 0;
A
antirez 已提交
1483 1484 1485 1486

    /* IP / port is different, update it. */
    memcpy(node->ip,ip,sizeof(ip));
    node->port = port;
1487
    node->cport = cport;
A
antirez 已提交
1488
    if (node->link) freeClusterLink(node->link);
A
antirez 已提交
1489
    node->flags &= ~CLUSTER_NODE_NOADDR;
A
antirez 已提交
1490
    serverLog(LL_WARNING,"Address updated for node %.40s, now %s:%d",
A
antirez 已提交
1491
        node->name, node->ip, node->port);
1492 1493 1494

    /* Check if this is our master and we have to change the
     * replication target as well. */
1495
    if (nodeIsSlave(myself) && myself->slaveof == node)
1496
        replicationSetMaster(node->ip, node->port);
A
antirez 已提交
1497
    return 1;
A
antirez 已提交
1498 1499
}

1500 1501 1502 1503
/* Reconfigure the specified node 'n' as a master. This function is called when
 * a node that we believed to be a slave is now acting as master in order to
 * update the state of the node. */
void clusterSetNodeAsMaster(clusterNode *n) {
1504
    if (nodeIsMaster(n)) return;
1505

1506 1507 1508 1509
    if (n->slaveof) {
        clusterNodeRemoveSlave(n->slaveof,n);
        if (n != myself) n->flags |= CLUSTER_NODE_MIGRATE_TO;
    }
A
antirez 已提交
1510 1511
    n->flags &= ~CLUSTER_NODE_SLAVE;
    n->flags |= CLUSTER_NODE_MASTER;
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
    n->slaveof = NULL;

    /* Update config and state. */
    clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                         CLUSTER_TODO_UPDATE_STATE);
}

/* This function is called when we receive a master configuration via a
 * PING, PONG or UPDATE packet. What we receive is a node, a configEpoch of the
 * node, and the set of slots claimed under this configEpoch.
 *
 * What we do is to rebind the slots with newer configuration compared to our
 * local configuration, and if needed, we turn ourself into a replica of the
 * node (see the function comments for more info).
 *
 * The 'sender' is the node for which we received a configuration update.
1528 1529
 * Sometimes it is not actually the "Sender" of the information, like in the
 * case we receive the info via an UPDATE packet. */
1530
void clusterUpdateSlotsConfigWith(clusterNode *sender, uint64_t senderConfigEpoch, unsigned char *slots) {
1531 1532
    int j;
    clusterNode *curmaster, *newmaster = NULL;
1533 1534 1535 1536 1537 1538 1539
    /* The dirty slots list is a list of slots for which we lose the ownership
     * while having still keys inside. This usually happens after a failover
     * or after a manual cluster reconfiguration operated by the admin.
     *
     * If the update message is not able to demote a master to slave (in this
     * case we'll resync with the master updating the whole key space), we
     * need to delete all the keys in the slots we lost ownership. */
A
antirez 已提交
1540
    uint16_t dirty_slots[CLUSTER_SLOTS];
1541
    int dirty_slots_count = 0;
1542 1543 1544 1545

    /* Here we set curmaster to this node or the node this node
     * replicates to if it's a slave. In the for loop we are
     * interested to check if slots are taken away from curmaster. */
1546
    curmaster = nodeIsMaster(myself) ? myself : myself->slaveof;
1547

1548
    if (sender == myself) {
A
antirez 已提交
1549
        serverLog(LL_WARNING,"Discarding UPDATE message about myself.");
1550 1551 1552
        return;
    }

A
antirez 已提交
1553
    for (j = 0; j < CLUSTER_SLOTS; j++) {
1554
        if (bitmapTestBit(slots,j)) {
1555 1556 1557 1558 1559 1560 1561 1562 1563
            /* The slot is already bound to the sender of this message. */
            if (server.cluster->slots[j] == sender) continue;

            /* The slot is in importing state, it should be modified only
             * manually via redis-trib (example: a resharding is in progress
             * and the migrating side slot was already closed and is advertising
             * a new config. We still want the slot to be closed manually). */
            if (server.cluster->importing_slots_from[j]) continue;

1564
            /* We rebind the slot to the new node claiming it if:
1565 1566 1567
             * 1) The slot was unassigned or the new node claims it with a
             *    greater configEpoch.
             * 2) We are not currently importing the slot. */
1568
            if (server.cluster->slots[j] == NULL ||
1569
                server.cluster->slots[j]->configEpoch < senderConfigEpoch)
1570
            {
1571 1572
                /* Was this slot mine, and still contains keys? Mark it as
                 * a dirty slot. */
1573 1574 1575 1576
                if (server.cluster->slots[j] == myself &&
                    countKeysInSlot(j) &&
                    sender != myself)
                {
1577 1578
                    dirty_slots[dirty_slots_count] = j;
                    dirty_slots_count++;
1579 1580
                }

1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
                if (server.cluster->slots[j] == curmaster)
                    newmaster = sender;
                clusterDelSlot(j);
                clusterAddSlot(sender,j);
                clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                                     CLUSTER_TODO_UPDATE_STATE|
                                     CLUSTER_TODO_FSYNC_CONFIG);
            }
        }
    }

1592 1593 1594 1595 1596 1597
    /* After updating the slots configuration, don't do any actual change
     * in the state of the server if a module disabled Redis Cluster
     * keys redirections. */
    if (server.cluster_module_flags & CLUSTER_MODULE_FLAG_NO_REDIRECTION)
        return;

1598 1599 1600 1601 1602 1603 1604 1605
    /* If at least one slot was reassigned from a node to another node
     * with a greater configEpoch, it is possible that:
     * 1) We are a master left without slots. This means that we were
     *    failed over and we should turn into a replica of the new
     *    master.
     * 2) We are a slave and our master is left without slots. We need
     *    to replicate to the new slots owner. */
    if (newmaster && curmaster->numslots == 0) {
A
antirez 已提交
1606
        serverLog(LL_WARNING,
A
antirez 已提交
1607 1608
            "Configuration change detected. Reconfiguring myself "
            "as a replica of %.40s", sender->name);
1609 1610 1611 1612
        clusterSetMaster(sender);
        clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                             CLUSTER_TODO_UPDATE_STATE|
                             CLUSTER_TODO_FSYNC_CONFIG);
1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
    } else if (dirty_slots_count) {
        /* If we are here, we received an update message which removed
         * ownership for certain slots we still have keys about, but still
         * we are serving some slots, so this master node was not demoted to
         * a slave.
         *
         * In order to maintain a consistent state between keys and slots
         * we need to remove all the keys from the slots we lost. */
        for (j = 0; j < dirty_slots_count; j++)
            delKeysInSlot(dirty_slots[j]);
1623 1624 1625
    }
}

A
antirez 已提交
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
/* When this function is called, there is a packet to process starting
 * at node->rcvbuf. Releasing the buffer is up to the caller, so this
 * function should just handle the higher level stuff of processing the
 * packet, modifying the cluster state if needed.
 *
 * The function returns 1 if the link is still valid after the packet
 * was processed, otherwise 0 if the link was freed since the packet
 * processing lead to some inconsistency error (for instance a PONG
 * received from the wrong sender ID). */
int clusterProcessPacket(clusterLink *link) {
    clusterMsg *hdr = (clusterMsg*) link->rcvbuf;
    uint32_t totlen = ntohl(hdr->totlen);
    uint16_t type = ntohs(hdr->type);

1640 1641
    if (type < CLUSTERMSG_TYPE_COUNT)
        server.cluster->stats_bus_messages_received[type]++;
A
antirez 已提交
1642
    serverLog(LL_DEBUG,"--- Processing packet of type %d, %lu bytes",
1643
        type, (unsigned long) totlen);
1644 1645

    /* Perform sanity checks */
1646
    if (totlen < 16) return 1; /* At least signature, version, totlen, count. */
A
antirez 已提交
1647
    if (totlen > sdslen(link->rcvbuf)) return 1;
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657

    if (ntohs(hdr->ver) != CLUSTER_PROTO_VER) {
        /* Can't handle messages of different versions. */
        return 1;
    }

    uint16_t flags = ntohs(hdr->flags);
    uint64_t senderCurrentEpoch = 0, senderConfigEpoch = 0;
    clusterNode *sender;

A
antirez 已提交
1658 1659 1660 1661 1662 1663 1664 1665 1666
    if (type == CLUSTERMSG_TYPE_PING || type == CLUSTERMSG_TYPE_PONG ||
        type == CLUSTERMSG_TYPE_MEET)
    {
        uint16_t count = ntohs(hdr->count);
        uint32_t explen; /* expected length of this packet */

        explen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
        explen += (sizeof(clusterMsgDataGossip)*count);
        if (totlen != explen) return 1;
1667
    } else if (type == CLUSTERMSG_TYPE_FAIL) {
A
antirez 已提交
1668 1669 1670 1671
        uint32_t explen = sizeof(clusterMsg)-sizeof(union clusterMsgData);

        explen += sizeof(clusterMsgDataFail);
        if (totlen != explen) return 1;
1672
    } else if (type == CLUSTERMSG_TYPE_PUBLISH) {
1673 1674
        uint32_t explen = sizeof(clusterMsg)-sizeof(union clusterMsgData);

1675 1676
        explen += sizeof(clusterMsgDataPublish) -
                8 +
1677 1678 1679
                ntohl(hdr->data.publish.msg.channel_len) +
                ntohl(hdr->data.publish.msg.message_len);
        if (totlen != explen) return 1;
1680
    } else if (type == CLUSTERMSG_TYPE_FAILOVER_AUTH_REQUEST ||
1681 1682 1683
               type == CLUSTERMSG_TYPE_FAILOVER_AUTH_ACK ||
               type == CLUSTERMSG_TYPE_MFSTART)
    {
1684 1685
        uint32_t explen = sizeof(clusterMsg)-sizeof(union clusterMsgData);

1686 1687 1688 1689 1690
        if (totlen != explen) return 1;
    } else if (type == CLUSTERMSG_TYPE_UPDATE) {
        uint32_t explen = sizeof(clusterMsg)-sizeof(union clusterMsgData);

        explen += sizeof(clusterMsgDataUpdate);
1691
        if (totlen != explen) return 1;
1692 1693 1694 1695 1696 1697
    } else if (type == CLUSTERMSG_TYPE_MODULE) {
        uint32_t explen = sizeof(clusterMsg)-sizeof(union clusterMsgData);

        explen += sizeof(clusterMsgDataPublish) -
                3 + ntohl(hdr->data.module.msg.len);
        if (totlen != explen) return 1;
1698
    }
A
antirez 已提交
1699

1700
    /* Check if the sender is a known node. */
A
antirez 已提交
1701
    sender = clusterLookupNode(hdr->sender);
1702
    if (sender && !nodeInHandshake(sender)) {
1703
        /* Update our curretEpoch if we see a newer epoch in the cluster. */
1704 1705 1706 1707
        senderCurrentEpoch = ntohu64(hdr->currentEpoch);
        senderConfigEpoch = ntohu64(hdr->configEpoch);
        if (senderCurrentEpoch > server.cluster->currentEpoch)
            server.cluster->currentEpoch = senderCurrentEpoch;
1708
        /* Update the sender configEpoch if it is publishing a newer one. */
1709
        if (senderConfigEpoch > sender->configEpoch) {
1710
            sender->configEpoch = senderConfigEpoch;
A
antirez 已提交
1711 1712
            clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                                 CLUSTER_TODO_FSYNC_CONFIG);
1713
        }
1714 1715 1716
        /* Update the replication offset info for this node. */
        sender->repl_offset = ntohu64(hdr->offset);
        sender->repl_offset_time = mstime();
1717 1718 1719 1720 1721 1722 1723 1724 1725
        /* If we are a slave performing a manual failover and our master
         * sent its offset while already paused, populate the MF state. */
        if (server.cluster->mf_end &&
            nodeIsSlave(myself) &&
            myself->slaveof == sender &&
            hdr->mflags[0] & CLUSTERMSG_FLAG0_PAUSED &&
            server.cluster->mf_master_offset == 0)
        {
            server.cluster->mf_master_offset = sender->repl_offset;
A
antirez 已提交
1726
            serverLog(LL_WARNING,
A
antirez 已提交
1727 1728 1729
                "Received replication offset for paused "
                "master manual failover: %lld",
                server.cluster->mf_master_offset);
1730
        }
1731
    }
1732

1733
    /* Initial processing of PING and MEET requests replying with a PONG. */
A
antirez 已提交
1734
    if (type == CLUSTERMSG_TYPE_PING || type == CLUSTERMSG_TYPE_MEET) {
A
antirez 已提交
1735
        serverLog(LL_DEBUG,"Ping packet received: %p", (void*)link->node);
A
antirez 已提交
1736

A
antirez 已提交
1737 1738
        /* We use incoming MEET messages in order to set the address
         * for 'myself', since only other cluster nodes will send us
1739
         * MEET messages on handshakes, when the cluster joins, or
A
antirez 已提交
1740 1741 1742
         * later if we changed address, and those nodes will use our
         * official address to connect to us. So by obtaining this address
         * from the socket is a simple way to discover / update our own
1743 1744 1745 1746 1747
         * address in the cluster without it being hardcoded in the config.
         *
         * However if we don't have an address at all, we update the address
         * even with a normal PING packet. If it's wrong it will be fixed
         * by MEET later. */
1748 1749 1750
        if ((type == CLUSTERMSG_TYPE_MEET || myself->ip[0] == '\0') &&
            server.cluster_announce_ip == NULL)
        {
A
antirez 已提交
1751
            char ip[NET_IP_STR_LEN];
A
antirez 已提交
1752 1753 1754 1755

            if (anetSockName(link->fd,ip,sizeof(ip),NULL) != -1 &&
                strcmp(ip,myself->ip))
            {
A
antirez 已提交
1756 1757
                memcpy(myself->ip,ip,NET_IP_STR_LEN);
                serverLog(LL_WARNING,"IP address for this node updated to %s",
1758
                    myself->ip);
A
antirez 已提交
1759 1760 1761 1762
                clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG);
            }
        }

A
antirez 已提交
1763 1764 1765
        /* Add this node if it is new for us and the msg type is MEET.
         * In this stage we don't try to add the node with the right
         * flags, slaveof pointer, and so forth, as this details will be
1766
         * resolved when we'll receive PONGs from the node. */
A
antirez 已提交
1767 1768 1769
        if (!sender && type == CLUSTERMSG_TYPE_MEET) {
            clusterNode *node;

A
antirez 已提交
1770
            node = createClusterNode(NULL,CLUSTER_NODE_HANDSHAKE);
1771
            nodeIp2String(node->ip,link,hdr->myip);
A
antirez 已提交
1772
            node->port = ntohs(hdr->port);
1773
            node->cport = ntohs(hdr->cport);
A
antirez 已提交
1774
            clusterAddNode(node);
A
antirez 已提交
1775
            clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG);
A
antirez 已提交
1776 1777
        }

1778 1779 1780 1781 1782
        /* If this is a MEET packet from an unknown node, we still process
         * the gossip section here since we have to trust the sender because
         * of the message type. */
        if (!sender && type == CLUSTERMSG_TYPE_MEET)
            clusterProcessGossipSection(hdr,link);
A
antirez 已提交
1783 1784 1785

        /* Anyway reply with a PONG */
        clusterSendPing(link,CLUSTERMSG_TYPE_PONG);
1786 1787
    }

1788
    /* PING, PONG, MEET: process config information. */
1789 1790 1791
    if (type == CLUSTERMSG_TYPE_PING || type == CLUSTERMSG_TYPE_PONG ||
        type == CLUSTERMSG_TYPE_MEET)
    {
A
antirez 已提交
1792
        serverLog(LL_DEBUG,"%s packet received: %p",
1793 1794
            type == CLUSTERMSG_TYPE_PING ? "ping" : "pong",
            (void*)link->node);
A
antirez 已提交
1795
        if (link->node) {
1796
            if (nodeInHandshake(link->node)) {
A
antirez 已提交
1797 1798 1799
                /* If we already have this node, try to change the
                 * IP/port of the node with the new one. */
                if (sender) {
A
antirez 已提交
1800
                    serverLog(LL_VERBOSE,
A
antirez 已提交
1801 1802
                        "Handshake: we already know node %.40s, "
                        "updating the address if needed.", sender->name);
1803
                    if (nodeUpdateAddressIfNeeded(sender,link,hdr))
A
antirez 已提交
1804
                    {
A
antirez 已提交
1805 1806
                        clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                                             CLUSTER_TODO_UPDATE_STATE);
A
antirez 已提交
1807
                    }
1808
                    /* Free this node as we already have it. This will
A
antirez 已提交
1809
                     * cause the link to be freed as well. */
1810
                    clusterDelNode(link->node);
A
antirez 已提交
1811 1812 1813 1814
                    return 0;
                }

                /* First thing to do is replacing the random name with the
1815
                 * right node name if this was a handshake stage. */
A
antirez 已提交
1816
                clusterRenameNode(link->node, hdr->sender);
A
antirez 已提交
1817
                serverLog(LL_DEBUG,"Handshake with node %.40s completed.",
A
antirez 已提交
1818
                    link->node->name);
A
antirez 已提交
1819 1820
                link->node->flags &= ~CLUSTER_NODE_HANDSHAKE;
                link->node->flags |= flags&(CLUSTER_NODE_MASTER|CLUSTER_NODE_SLAVE);
A
antirez 已提交
1821
                clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG);
A
antirez 已提交
1822
            } else if (memcmp(link->node->name,hdr->sender,
A
antirez 已提交
1823
                        CLUSTER_NAMELEN) != 0)
A
antirez 已提交
1824 1825 1826 1827
            {
                /* If the reply has a non matching node ID we
                 * disconnect this node and set it as not having an associated
                 * address. */
1828
                serverLog(LL_DEBUG,"PONG contains mismatching sender ID. About node %.40s added %d ms ago, having flags %d",
1829 1830 1831
                    link->node->name,
                    (int)(mstime()-(link->node->ctime)),
                    link->node->flags);
A
antirez 已提交
1832
                link->node->flags |= CLUSTER_NODE_NOADDR;
1833 1834
                link->node->ip[0] = '\0';
                link->node->port = 0;
1835
                link->node->cport = 0;
A
antirez 已提交
1836
                freeClusterLink(link);
A
antirez 已提交
1837
                clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG);
A
antirez 已提交
1838 1839 1840
                return 0;
            }
        }
1841

1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
        /* Copy the CLUSTER_NODE_NOFAILOVER flag from what the sender
         * announced. This is a dynamic flag that we receive from the
         * sender, and the latest status must be trusted. We need it to
         * be propagated because the slave ranking used to understand the
         * delay of each slave in the voting process, needs to know
         * what are the instances really competing. */
        if (sender) {
            int nofailover = flags & CLUSTER_NODE_NOFAILOVER;
            sender->flags &= ~CLUSTER_NODE_NOFAILOVER;
            sender->flags |= nofailover;
        }

A
antirez 已提交
1854 1855
        /* Update the node address if it changed. */
        if (sender && type == CLUSTERMSG_TYPE_PING &&
1856
            !nodeInHandshake(sender) &&
1857
            nodeUpdateAddressIfNeeded(sender,link,hdr))
A
antirez 已提交
1858
        {
A
antirez 已提交
1859 1860
            clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                                 CLUSTER_TODO_UPDATE_STATE);
A
antirez 已提交
1861 1862
        }

A
antirez 已提交
1863
        /* Update our info about the node */
1864
        if (link->node && type == CLUSTERMSG_TYPE_PONG) {
1865
            link->node->pong_received = mstime();
1866 1867 1868
            link->node->ping_sent = 0;

            /* The PFAIL condition can be reversed without external
1869
             * help if it is momentary (that is, if it does not
1870 1871 1872 1873
             * turn into a FAIL state).
             *
             * The FAIL condition is also reversible under specific
             * conditions detected by clearNodeFailureIfNeeded(). */
1874
            if (nodeTimedOut(link->node)) {
A
antirez 已提交
1875
                link->node->flags &= ~CLUSTER_NODE_PFAIL;
A
antirez 已提交
1876 1877
                clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                                     CLUSTER_TODO_UPDATE_STATE);
1878
            } else if (nodeFailed(link->node)) {
1879 1880 1881
                clearNodeFailureIfNeeded(link->node);
            }
        }
A
antirez 已提交
1882

1883
        /* Check for role switch: slave -> master or master -> slave. */
A
antirez 已提交
1884
        if (sender) {
A
antirez 已提交
1885
            if (!memcmp(hdr->slaveof,CLUSTER_NODE_NULL_NAME,
A
antirez 已提交
1886 1887
                sizeof(hdr->slaveof)))
            {
1888
                /* Node is a master. */
1889
                clusterSetNodeAsMaster(sender);
A
antirez 已提交
1890
            } else {
1891
                /* Node is a slave. */
A
antirez 已提交
1892 1893
                clusterNode *master = clusterLookupNode(hdr->slaveof);

1894
                if (nodeIsMaster(sender)) {
1895
                    /* Master turned into a slave! Reconfigure the node. */
1896
                    clusterDelNodeSlots(sender);
1897 1898
                    sender->flags &= ~(CLUSTER_NODE_MASTER|
                                       CLUSTER_NODE_MIGRATE_TO);
A
antirez 已提交
1899
                    sender->flags |= CLUSTER_NODE_SLAVE;
1900 1901

                    /* Update config and state. */
A
antirez 已提交
1902 1903
                    clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                                         CLUSTER_TODO_UPDATE_STATE);
1904 1905
                }

1906
                /* Master node changed for this slave? */
1907
                if (master && sender->slaveof != master) {
1908 1909
                    if (sender->slaveof)
                        clusterNodeRemoveSlave(sender->slaveof,sender);
1910 1911
                    clusterNodeAddSlave(master,sender);
                    sender->slaveof = master;
1912 1913

                    /* Update config. */
A
antirez 已提交
1914
                    clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG);
1915
                }
A
antirez 已提交
1916 1917 1918
            }
        }

1919
        /* Update our info about served slots.
1920
         *
1921
         * Note: this MUST happen after we update the master/slave state
A
antirez 已提交
1922
         * so that CLUSTER_NODE_MASTER flag will be set. */
1923 1924

        /* Many checks are only needed if the set of served slots this
1925 1926 1927 1928
         * instance claims is different compared to the set of slots we have
         * for it. Check this ASAP to avoid other computational expansive
         * checks later. */
        clusterNode *sender_master = NULL; /* Sender or its master if slave. */
1929 1930 1931
        int dirty_slots = 0; /* Sender claimed slots don't match my view? */

        if (sender) {
1932
            sender_master = nodeIsMaster(sender) ? sender : sender->slaveof;
1933 1934 1935 1936 1937 1938
            if (sender_master) {
                dirty_slots = memcmp(sender_master->slots,
                        hdr->myslots,sizeof(hdr->myslots)) != 0;
            }
        }

1939 1940 1941
        /* 1) If the sender of the message is a master, and we detected that
         *    the set of slots it claims changed, scan the slots to see if we
         *    need to update our configuration. */
1942
        if (sender && nodeIsMaster(sender) && dirty_slots)
1943
            clusterUpdateSlotsConfigWith(sender,senderConfigEpoch,hdr->myslots);
1944

1945 1946 1947
        /* 2) We also check for the reverse condition, that is, the sender
         *    claims to serve slots we know are served by a master with a
         *    greater configEpoch. If this happens we inform the sender.
1948
         *
1949 1950 1951 1952
         * This is useful because sometimes after a partition heals, a
         * reappearing master may be the last one to claim a given set of
         * hash slots, but with a configuration that other instances know to
         * be deprecated. Example:
1953 1954 1955 1956 1957 1958
         *
         * A and B are master and slave for slots 1,2,3.
         * A is partitioned away, B gets promoted.
         * B is partitioned away, and A returns available.
         *
         * Usually B would PING A publishing its set of served slots and its
1959 1960 1961 1962
         * configEpoch, but because of the partition B can't inform A of the
         * new configuration, so other nodes that have an updated table must
         * do it. In this way A will stop to act as a master (or can try to
         * failover if there are the conditions to win the election). */
1963 1964 1965
        if (sender && dirty_slots) {
            int j;

A
antirez 已提交
1966
            for (j = 0; j < CLUSTER_SLOTS; j++) {
1967 1968 1969 1970 1971 1972
                if (bitmapTestBit(hdr->myslots,j)) {
                    if (server.cluster->slots[j] == sender ||
                        server.cluster->slots[j] == NULL) continue;
                    if (server.cluster->slots[j]->configEpoch >
                        senderConfigEpoch)
                    {
A
antirez 已提交
1973
                        serverLog(LL_VERBOSE,
1974
                            "Node %.40s has old slots configuration, sending "
1975
                            "an UPDATE message about %.40s",
1976
                                sender->name, server.cluster->slots[j]->name);
A
antirez 已提交
1977 1978
                        clusterSendUpdate(sender->link,
                            server.cluster->slots[j]);
1979 1980 1981 1982 1983

                        /* TODO: instead of exiting the loop send every other
                         * UPDATE packet for other nodes that are the new owner
                         * of sender's slots. */
                        break;
1984
                    }
1985
                }
A
antirez 已提交
1986 1987 1988
            }
        }

1989 1990 1991 1992 1993 1994 1995 1996 1997
        /* If our config epoch collides with the sender's try to fix
         * the problem. */
        if (sender &&
            nodeIsMaster(myself) && nodeIsMaster(sender) &&
            senderConfigEpoch == myself->configEpoch)
        {
            clusterHandleConfigEpochCollision(sender);
        }

A
antirez 已提交
1998
        /* Get info from the gossip section */
1999
        if (sender) clusterProcessGossipSection(hdr,link);
2000
    } else if (type == CLUSTERMSG_TYPE_FAIL) {
A
antirez 已提交
2001 2002
        clusterNode *failing;

2003 2004
        if (sender) {
            failing = clusterLookupNode(hdr->data.fail.about.nodename);
2005
            if (failing &&
A
antirez 已提交
2006
                !(failing->flags & (CLUSTER_NODE_FAIL|CLUSTER_NODE_MYSELF)))
2007
            {
A
antirez 已提交
2008
                serverLog(LL_NOTICE,
2009 2010
                    "FAIL message received from %.40s about %.40s",
                    hdr->sender, hdr->data.fail.about.nodename);
A
antirez 已提交
2011
                failing->flags |= CLUSTER_NODE_FAIL;
2012
                failing->fail_time = mstime();
A
antirez 已提交
2013
                failing->flags &= ~CLUSTER_NODE_PFAIL;
A
antirez 已提交
2014 2015
                clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                                     CLUSTER_TODO_UPDATE_STATE);
2016 2017
            }
        } else {
A
antirez 已提交
2018
            serverLog(LL_NOTICE,
2019
                "Ignoring FAIL message from unknown node %.40s about %.40s",
A
antirez 已提交
2020 2021
                hdr->sender, hdr->data.fail.about.nodename);
        }
2022 2023 2024 2025
    } else if (type == CLUSTERMSG_TYPE_PUBLISH) {
        robj *channel, *message;
        uint32_t channel_len, message_len;

A
antirez 已提交
2026 2027
        /* Don't bother creating useless objects if there are no
         * Pub/Sub subscribers. */
2028 2029 2030
        if (dictSize(server.pubsub_channels) ||
           listLength(server.pubsub_patterns))
        {
2031 2032 2033 2034 2035
            channel_len = ntohl(hdr->data.publish.msg.channel_len);
            message_len = ntohl(hdr->data.publish.msg.message_len);
            channel = createStringObject(
                        (char*)hdr->data.publish.msg.bulk_data,channel_len);
            message = createStringObject(
2036 2037
                        (char*)hdr->data.publish.msg.bulk_data+channel_len,
                        message_len);
2038 2039 2040 2041
            pubsubPublishMessage(channel,message);
            decrRefCount(channel);
            decrRefCount(message);
        }
2042
    } else if (type == CLUSTERMSG_TYPE_FAILOVER_AUTH_REQUEST) {
A
antirez 已提交
2043
        if (!sender) return 1;  /* We don't know that node. */
2044
        clusterSendFailoverAuthIfNeeded(sender,hdr);
2045
    } else if (type == CLUSTERMSG_TYPE_FAILOVER_AUTH_ACK) {
A
antirez 已提交
2046
        if (!sender) return 1;  /* We don't know that node. */
2047
        /* We consider this vote only if the sender is a master serving
2048 2049
         * a non zero number of slots, and its currentEpoch is greater or
         * equal to epoch where this node started the election. */
2050
        if (nodeIsMaster(sender) && sender->numslots > 0 &&
2051
            senderCurrentEpoch >= server.cluster->failover_auth_epoch)
2052
        {
2053
            server.cluster->failover_auth_count++;
2054 2055
            /* Maybe we reached a quorum here, set a flag to make sure
             * we check ASAP. */
A
antirez 已提交
2056
            clusterDoBeforeSleep(CLUSTER_TODO_HANDLE_FAILOVER);
2057
        }
2058 2059 2060 2061 2062 2063 2064
    } else if (type == CLUSTERMSG_TYPE_MFSTART) {
        /* This message is acceptable only if I'm a master and the sender
         * is one of my slaves. */
        if (!sender || sender->slaveof != myself) return 1;
        /* Manual failover requested from slaves. Initialize the state
         * accordingly. */
        resetManualFailover();
A
antirez 已提交
2065
        server.cluster->mf_end = mstime() + CLUSTER_MF_TIMEOUT;
2066
        server.cluster->mf_slave = sender;
A
antirez 已提交
2067
        pauseClients(mstime()+(CLUSTER_MF_TIMEOUT*2));
2068
        serverLog(LL_WARNING,"Manual failover requested by replica %.40s.",
2069
            sender->name);
2070 2071
    } else if (type == CLUSTERMSG_TYPE_UPDATE) {
        clusterNode *n; /* The node the update is about. */
A
antirez 已提交
2072 2073
        uint64_t reportedConfigEpoch =
                    ntohu64(hdr->data.update.nodecfg.configEpoch);
2074 2075 2076 2077 2078 2079 2080

        if (!sender) return 1;  /* We don't know the sender. */
        n = clusterLookupNode(hdr->data.update.nodecfg.nodename);
        if (!n) return 1;   /* We don't know the reported node. */
        if (n->configEpoch >= reportedConfigEpoch) return 1; /* Nothing new. */

        /* If in our current config the node is a slave, set it as a master. */
2081
        if (nodeIsSlave(n)) clusterSetNodeAsMaster(n);
2082

2083 2084
        /* Update the node's configEpoch. */
        n->configEpoch = reportedConfigEpoch;
A
antirez 已提交
2085 2086
        clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                             CLUSTER_TODO_FSYNC_CONFIG);
2087

2088
        /* Check the bitmap of served slots and update our
2089
         * config accordingly. */
2090 2091
        clusterUpdateSlotsConfigWith(n,reportedConfigEpoch,
            hdr->data.update.nodecfg.slots);
2092 2093 2094 2095 2096 2097 2098 2099 2100
    } else if (type == CLUSTERMSG_TYPE_MODULE) {
        if (!sender) return 1;  /* Protect the module from unknown nodes. */
        /* We need to route this message back to the right module subscribed
         * for the right message type. */
        uint64_t module_id = hdr->data.module.msg.module_id; /* Endian-safe ID */
        uint32_t len = ntohl(hdr->data.module.msg.len);
        uint8_t type = hdr->data.module.msg.type;
        unsigned char *payload = hdr->data.module.msg.bulk_data;
        moduleCallClusterReceivers(sender->name,module_id,type,payload,len);
A
antirez 已提交
2101
    } else {
A
antirez 已提交
2102
        serverLog(LL_WARNING,"Received unknown packet type: %d", type);
A
antirez 已提交
2103 2104 2105 2106 2107 2108 2109
    }
    return 1;
}

/* This function is called when we detect the link with this node is lost.
   We set the node as no longer connected. The Cluster Cron will detect
   this connection and will try to get it connected again.
2110

A
antirez 已提交
2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122
   Instead if the node is a temporary node used to accept a query, we
   completely free the node on error. */
void handleLinkIOError(clusterLink *link) {
    freeClusterLink(link);
}

/* Send data. This is handled using a trivial send buffer that gets
 * consumed by write(). We don't try to optimize this for speed too much
 * as this is a very low traffic channel. */
void clusterWriteHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
    clusterLink *link = (clusterLink*) privdata;
    ssize_t nwritten;
A
antirez 已提交
2123 2124
    UNUSED(el);
    UNUSED(mask);
A
antirez 已提交
2125 2126 2127

    nwritten = write(fd, link->sndbuf, sdslen(link->sndbuf));
    if (nwritten <= 0) {
A
antirez 已提交
2128
        serverLog(LL_DEBUG,"I/O error writing to node link: %s",
S
shenlongxing 已提交
2129
            (nwritten == -1) ? strerror(errno) : "short write");
A
antirez 已提交
2130 2131 2132
        handleLinkIOError(link);
        return;
    }
2133
    sdsrange(link->sndbuf,nwritten,-1);
A
antirez 已提交
2134 2135 2136 2137 2138 2139 2140 2141
    if (sdslen(link->sndbuf) == 0)
        aeDeleteFileEvent(server.el, link->fd, AE_WRITABLE);
}

/* Read data. Try to read the first field of the header first to check the
 * full length of the packet. When a whole packet is in memory this function
 * will call the function to process the packet. And so forth. */
void clusterReadHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
2142
    char buf[sizeof(clusterMsg)];
A
antirez 已提交
2143 2144 2145
    ssize_t nread;
    clusterMsg *hdr;
    clusterLink *link = (clusterLink*) privdata;
2146
    unsigned int readlen, rcvbuflen;
A
antirez 已提交
2147 2148
    UNUSED(el);
    UNUSED(mask);
A
antirez 已提交
2149

2150 2151
    while(1) { /* Read as long as there is data to read. */
        rcvbuflen = sdslen(link->rcvbuf);
2152 2153
        if (rcvbuflen < 8) {
            /* First, obtain the first 8 bytes to get the full message
2154
             * length. */
2155
            readlen = 8 - rcvbuflen;
2156 2157 2158
        } else {
            /* Finally read the full message. */
            hdr = (clusterMsg*) link->rcvbuf;
2159 2160 2161 2162 2163 2164
            if (rcvbuflen == 8) {
                /* Perform some sanity check on the message signature
                 * and length. */
                if (memcmp(hdr->sig,"RCmb",4) != 0 ||
                    ntohl(hdr->totlen) < CLUSTERMSG_MIN_LEN)
                {
A
antirez 已提交
2165
                    serverLog(LL_WARNING,
2166 2167
                        "Bad message length or signature received "
                        "from Cluster bus.");
2168 2169 2170
                    handleLinkIOError(link);
                    return;
                }
2171
            }
2172 2173
            readlen = ntohl(hdr->totlen) - rcvbuflen;
            if (readlen > sizeof(buf)) readlen = sizeof(buf);
2174
        }
A
antirez 已提交
2175

2176 2177
        nread = read(fd,buf,readlen);
        if (nread == -1 && errno == EAGAIN) return; /* No more data ready. */
A
antirez 已提交
2178

2179 2180
        if (nread <= 0) {
            /* I/O error... */
A
antirez 已提交
2181
            serverLog(LL_DEBUG,"I/O error reading from node link: %s",
2182 2183 2184 2185 2186 2187 2188 2189 2190
                (nread == 0) ? "connection closed" : strerror(errno));
            handleLinkIOError(link);
            return;
        } else {
            /* Read data and recast the pointer to the new buffer. */
            link->rcvbuf = sdscatlen(link->rcvbuf,buf,nread);
            hdr = (clusterMsg*) link->rcvbuf;
            rcvbuflen += nread;
        }
A
antirez 已提交
2191

2192
        /* Total length obtained? Process this packet. */
2193
        if (rcvbuflen >= 8 && rcvbuflen == ntohl(hdr->totlen)) {
2194 2195 2196 2197 2198 2199
            if (clusterProcessPacket(link)) {
                sdsfree(link->rcvbuf);
                link->rcvbuf = sdsempty();
            } else {
                return; /* Link no longer valid. */
            }
A
antirez 已提交
2200 2201 2202 2203
        }
    }
}

2204 2205 2206 2207 2208
/* Put stuff into the send buffer.
 *
 * It is guaranteed that this function will never have as a side effect
 * the link to be invalidated, so it is safe to call this function
 * from event handlers that will do stuff with the same link later. */
A
antirez 已提交
2209 2210
void clusterSendMessage(clusterLink *link, unsigned char *msg, size_t msglen) {
    if (sdslen(link->sndbuf) == 0 && msglen != 0)
2211
        aeCreateFileEvent(server.el,link->fd,AE_WRITABLE|AE_BARRIER,
A
antirez 已提交
2212 2213 2214
                    clusterWriteHandler,link);

    link->sndbuf = sdscatlen(link->sndbuf, msg, msglen);
2215 2216 2217 2218 2219 2220

    /* Populate sent messages stats. */
    clusterMsg *hdr = (clusterMsg*) msg;
    uint16_t type = ntohs(hdr->type);
    if (type < CLUSTERMSG_TYPE_COUNT)
        server.cluster->stats_bus_messages_sent[type]++;
A
antirez 已提交
2221 2222
}

2223
/* Send a message to all the nodes that are part of the cluster having
2224
 * a connected link.
2225
 *
2226 2227 2228
 * It is guaranteed that this function will never have as a side effect
 * some node->link to be invalidated, so it is safe to call this function
 * from event handlers that will do stuff with node links later. */
2229 2230 2231 2232
void clusterBroadcastMessage(void *buf, size_t len) {
    dictIterator *di;
    dictEntry *de;

2233
    di = dictGetSafeIterator(server.cluster->nodes);
2234
    while((de = dictNext(di)) != NULL) {
2235
        clusterNode *node = dictGetVal(de);
2236 2237

        if (!node->link) continue;
A
antirez 已提交
2238
        if (node->flags & (CLUSTER_NODE_MYSELF|CLUSTER_NODE_HANDSHAKE))
2239
            continue;
2240 2241 2242 2243 2244
        clusterSendMessage(node->link,buf,len);
    }
    dictReleaseIterator(di);
}

2245 2246
/* Build the message header. hdr must point to a buffer at least
 * sizeof(clusterMsg) in bytes. */
A
antirez 已提交
2247
void clusterBuildMessageHdr(clusterMsg *hdr, int type) {
2248
    int totlen = 0;
2249
    uint64_t offset;
2250
    clusterNode *master;
2251 2252 2253 2254 2255

    /* If this node is a master, we send its slots bitmap and configEpoch.
     * If this node is a slave we send the master's information instead (the
     * node is flagged as slave so the receiver knows that it is NOT really
     * in charge for this slots. */
2256
    master = (nodeIsSlave(myself) && myself->slaveof) ?
2257
              myself->slaveof : myself;
A
antirez 已提交
2258 2259

    memset(hdr,0,sizeof(*hdr));
2260
    hdr->ver = htons(CLUSTER_PROTO_VER);
2261 2262
    hdr->sig[0] = 'R';
    hdr->sig[1] = 'C';
2263
    hdr->sig[2] = 'm';
2264
    hdr->sig[3] = 'b';
A
antirez 已提交
2265
    hdr->type = htons(type);
A
antirez 已提交
2266
    memcpy(hdr->sender,myself->name,CLUSTER_NAMELEN);
2267

2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283
    /* If cluster-announce-ip option is enabled, force the receivers of our
     * packets to use the specified address for this node. Otherwise if the
     * first byte is zero, they'll do auto discovery. */
    memset(hdr->myip,0,NET_IP_STR_LEN);
    if (server.cluster_announce_ip) {
        strncpy(hdr->myip,server.cluster_announce_ip,NET_IP_STR_LEN);
        hdr->myip[NET_IP_STR_LEN-1] = '\0';
    }

    /* Handle cluster-announce-port as well. */
    int announced_port = server.cluster_announce_port ?
                         server.cluster_announce_port : server.port;
    int announced_cport = server.cluster_announce_bus_port ?
                          server.cluster_announce_bus_port :
                          (server.port + CLUSTER_PORT_INCR);

2284
    memcpy(hdr->myslots,master->slots,sizeof(hdr->myslots));
A
antirez 已提交
2285
    memset(hdr->slaveof,0,CLUSTER_NAMELEN);
2286
    if (myself->slaveof != NULL)
A
antirez 已提交
2287
        memcpy(hdr->slaveof,myself->slaveof->name, CLUSTER_NAMELEN);
2288 2289
    hdr->port = htons(announced_port);
    hdr->cport = htons(announced_cport);
2290
    hdr->flags = htons(myself->flags);
2291
    hdr->state = server.cluster->state;
A
antirez 已提交
2292

2293
    /* Set the currentEpoch and configEpochs. */
2294
    hdr->currentEpoch = htonu64(server.cluster->currentEpoch);
2295
    hdr->configEpoch = htonu64(master->configEpoch);
2296

2297
    /* Set the replication offset. */
2298 2299 2300
    if (nodeIsSlave(myself))
        offset = replicationGetSlaveOffset();
    else
2301 2302 2303
        offset = server.master_repl_offset;
    hdr->offset = htonu64(offset);

2304 2305 2306 2307
    /* Set the message flags. */
    if (nodeIsMaster(myself) && server.cluster->mf_end)
        hdr->mflags[0] |= CLUSTERMSG_FLAG0_PAUSED;

2308 2309
    /* Compute the message length for certain messages. For other messages
     * this is up to the caller. */
A
antirez 已提交
2310 2311 2312
    if (type == CLUSTERMSG_TYPE_FAIL) {
        totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
        totlen += sizeof(clusterMsgDataFail);
2313 2314 2315
    } else if (type == CLUSTERMSG_TYPE_UPDATE) {
        totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
        totlen += sizeof(clusterMsgDataUpdate);
A
antirez 已提交
2316 2317
    }
    hdr->totlen = htonl(totlen);
2318
    /* For PING, PONG, and MEET, fixing the totlen field is up to the caller. */
A
antirez 已提交
2319 2320
}

2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347
/* Return non zero if the node is already present in the gossip section of the
 * message pointed by 'hdr' and having 'count' gossip entries. Otherwise
 * zero is returned. Helper for clusterSendPing(). */
int clusterNodeIsInGossipSection(clusterMsg *hdr, int count, clusterNode *n) {
    int j;
    for (j = 0; j < count; j++) {
        if (memcmp(hdr->data.ping.gossip[j].nodename,n->name,
                CLUSTER_NAMELEN) == 0) break;
    }
    return j != count;
}

/* Set the i-th entry of the gossip section in the message pointed by 'hdr'
 * to the info of the specified node 'n'. */
void clusterSetGossipEntry(clusterMsg *hdr, int i, clusterNode *n) {
    clusterMsgDataGossip *gossip;
    gossip = &(hdr->data.ping.gossip[i]);
    memcpy(gossip->nodename,n->name,CLUSTER_NAMELEN);
    gossip->ping_sent = htonl(n->ping_sent/1000);
    gossip->pong_received = htonl(n->pong_received/1000);
    memcpy(gossip->ip,n->ip,sizeof(n->ip));
    gossip->port = htons(n->port);
    gossip->cport = htons(n->cport);
    gossip->flags = htons(n->flags);
    gossip->notused1 = 0;
}

A
antirez 已提交
2348 2349 2350
/* Send a PING or PONG packet to the specified node, making sure to add enough
 * gossip informations. */
void clusterSendPing(clusterLink *link, int type) {
2351 2352 2353 2354 2355 2356 2357 2358 2359
    unsigned char *buf;
    clusterMsg *hdr;
    int gossipcount = 0; /* Number of gossip sections added so far. */
    int wanted; /* Number of gossip sections we want to append if possible. */
    int totlen; /* Total packet length. */
    /* freshnodes is the max number of nodes we can hope to append at all:
     * nodes available minus two (ourself and the node we are sending the
     * message to). However practically there may be less valid nodes since
     * nodes in handshake state, disconnected, are not considered. */
2360
    int freshnodes = dictSize(server.cluster->nodes)-2;
A
antirez 已提交
2361

2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385
    /* How many gossip sections we want to add? 1/10 of the number of nodes
     * and anyway at least 3. Why 1/10?
     *
     * If we have N masters, with N/10 entries, and we consider that in
     * node_timeout we exchange with each other node at least 4 packets
     * (we ping in the worst case in node_timeout/2 time, and we also
     * receive two pings from the host), we have a total of 8 packets
     * in the node_timeout*2 falure reports validity time. So we have
     * that, for a single PFAIL node, we can expect to receive the following
     * number of failure reports (in the specified window of time):
     *
     * PROB * GOSSIP_ENTRIES_PER_PACKET * TOTAL_PACKETS:
     *
     * PROB = probability of being featured in a single gossip entry,
     *        which is 1 / NUM_OF_NODES.
     * ENTRIES = 10.
     * TOTAL_PACKETS = 2 * 4 * NUM_OF_MASTERS.
     *
     * If we assume we have just masters (so num of nodes and num of masters
     * is the same), with 1/10 we always get over the majority, and specifically
     * 80% of the number of nodes, to account for many masters failing at the
     * same time.
     *
     * Since we have non-voting slaves that lower the probability of an entry
2386
     * to feature our node, we set the number of entries per packet as
2387
     * 10% of the total nodes we have. */
2388
    wanted = floor(dictSize(server.cluster->nodes)/10);
2389
    if (wanted < 3) wanted = 3;
2390
    if (wanted > freshnodes) wanted = freshnodes;
2391

2392 2393 2394 2395
    /* Include all the nodes in PFAIL state, so that failure reports are
     * faster to propagate to go from PFAIL to FAIL state. */
    int pfail_wanted = server.cluster->stats_pfail_nodes;

2396 2397 2398 2399
    /* Compute the maxium totlen to allocate our buffer. We'll fix the totlen
     * later according to the number of gossip sections we really were able
     * to put inside the packet. */
    totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
2400
    totlen += (sizeof(clusterMsgDataGossip)*(wanted+pfail_wanted));
2401 2402 2403 2404 2405 2406 2407
    /* Note: clusterBuildMessageHdr() expects the buffer to be always at least
     * sizeof(clusterMsg) or more. */
    if (totlen < (int)sizeof(clusterMsg)) totlen = sizeof(clusterMsg);
    buf = zcalloc(totlen);
    hdr = (clusterMsg*) buf;

    /* Populate the header. */
A
antirez 已提交
2408
    if (link->node && type == CLUSTERMSG_TYPE_PING)
2409
        link->node->ping_sent = mstime();
A
antirez 已提交
2410
    clusterBuildMessageHdr(hdr,type);
2411

A
antirez 已提交
2412
    /* Populate the gossip fields */
2413
    int maxiterations = wanted*3;
2414
    while(freshnodes > 0 && gossipcount < wanted && maxiterations--) {
A
antirez 已提交
2415
        dictEntry *de = dictGetRandomKey(server.cluster->nodes);
2416
        clusterNode *this = dictGetVal(de);
A
antirez 已提交
2417

2418 2419 2420 2421
        /* Don't include this node: the whole packet header is about us
         * already, so we just gossip about other nodes. */
        if (this == myself) continue;

2422 2423
        /* PFAIL nodes will be added later. */
        if (this->flags & CLUSTER_NODE_PFAIL) continue;
2424

2425
        /* In the gossip section don't include:
2426
         * 1) Nodes in HANDSHAKE state.
2427 2428 2429
         * 3) Nodes with the NOADDR flag set.
         * 4) Disconnected nodes if they don't have configured slots.
         */
A
antirez 已提交
2430
        if (this->flags & (CLUSTER_NODE_HANDSHAKE|CLUSTER_NODE_NOADDR) ||
2431
            (this->link == NULL && this->numslots == 0))
2432
        {
2433 2434
            freshnodes--; /* Tecnically not correct, but saves CPU. */
            continue;
A
antirez 已提交
2435 2436
        }

2437 2438
        /* Do not add a node we already have. */
        if (clusterNodeIsInGossipSection(hdr,gossipcount,this)) continue;
A
antirez 已提交
2439 2440

        /* Add it */
2441
        clusterSetGossipEntry(hdr,gossipcount,this);
A
antirez 已提交
2442 2443 2444
        freshnodes--;
        gossipcount++;
    }
2445

2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467
    /* If there are PFAIL nodes, add them at the end. */
    if (pfail_wanted) {
        dictIterator *di;
        dictEntry *de;

        di = dictGetSafeIterator(server.cluster->nodes);
        while((de = dictNext(di)) != NULL && pfail_wanted > 0) {
            clusterNode *node = dictGetVal(de);
            if (node->flags & CLUSTER_NODE_HANDSHAKE) continue;
            if (node->flags & CLUSTER_NODE_NOADDR) continue;
            if (!(node->flags & CLUSTER_NODE_PFAIL)) continue;
            clusterSetGossipEntry(hdr,gossipcount,node);
            freshnodes--;
            gossipcount++;
            /* We take the count of the slots we allocated, since the
             * PFAIL stats may not match perfectly with the current number
             * of PFAIL nodes. */
            pfail_wanted--;
        }
        dictReleaseIterator(di);
    }

2468 2469
    /* Ready to send... fix the totlen fiend and queue the message in the
     * output buffer. */
A
antirez 已提交
2470 2471 2472 2473 2474
    totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
    totlen += (sizeof(clusterMsgDataGossip)*gossipcount);
    hdr->count = htons(gossipcount);
    hdr->totlen = htonl(totlen);
    clusterSendMessage(link,buf,totlen);
2475
    zfree(buf);
A
antirez 已提交
2476 2477
}

2478 2479
/* Send a PONG packet to every connected node that's not in handshake state
 * and for which we have a valid link.
2480
 *
2481 2482
 * In Redis Cluster pongs are not used just for failure detection, but also
 * to carry important configuration information. So broadcasting a pong is
2483
 * useful when something changes in the configuration and we want to make
2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494
 * the cluster aware ASAP (for instance after a slave promotion).
 *
 * The 'target' argument specifies the receiving instances using the
 * defines below:
 *
 * CLUSTER_BROADCAST_ALL -> All known instances.
 * CLUSTER_BROADCAST_LOCAL_SLAVES -> All slaves in my master-slaves ring.
 */
#define CLUSTER_BROADCAST_ALL 0
#define CLUSTER_BROADCAST_LOCAL_SLAVES 1
void clusterBroadcastPong(int target) {
2495 2496 2497
    dictIterator *di;
    dictEntry *de;

2498
    di = dictGetSafeIterator(server.cluster->nodes);
2499 2500 2501
    while((de = dictNext(di)) != NULL) {
        clusterNode *node = dictGetVal(de);

2502
        if (!node->link) continue;
2503
        if (node == myself || nodeInHandshake(node)) continue;
2504 2505
        if (target == CLUSTER_BROADCAST_LOCAL_SLAVES) {
            int local_slave =
2506
                nodeIsSlave(node) && node->slaveof &&
2507 2508 2509
                (node->slaveof == myself || node->slaveof == myself->slaveof);
            if (!local_slave) continue;
        }
2510 2511 2512 2513 2514
        clusterSendPing(node->link,CLUSTERMSG_TYPE_PONG);
    }
    dictReleaseIterator(di);
}

2515 2516 2517 2518
/* Send a PUBLISH message.
 *
 * If link is NULL, then the message is broadcasted to the whole cluster. */
void clusterSendPublish(clusterLink *link, robj *channel, robj *message) {
2519
    unsigned char buf[sizeof(clusterMsg)], *payload;
2520 2521 2522
    clusterMsg *hdr = (clusterMsg*) buf;
    uint32_t totlen;
    uint32_t channel_len, message_len;
A
antirez 已提交
2523

2524 2525 2526 2527
    channel = getDecodedObject(channel);
    message = getDecodedObject(message);
    channel_len = sdslen(channel->ptr);
    message_len = sdslen(message->ptr);
A
antirez 已提交
2528

2529 2530
    clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_PUBLISH);
    totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
2531
    totlen += sizeof(clusterMsgDataPublish) - 8 + channel_len + message_len;
2532 2533 2534 2535 2536 2537 2538 2539 2540 2541

    hdr->data.publish.msg.channel_len = htonl(channel_len);
    hdr->data.publish.msg.message_len = htonl(message_len);
    hdr->totlen = htonl(totlen);

    /* Try to use the local buffer if possible */
    if (totlen < sizeof(buf)) {
        payload = buf;
    } else {
        payload = zmalloc(totlen);
2542
        memcpy(payload,hdr,sizeof(*hdr));
2543
        hdr = (clusterMsg*) payload;
A
antirez 已提交
2544
    }
2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556
    memcpy(hdr->data.publish.msg.bulk_data,channel->ptr,sdslen(channel->ptr));
    memcpy(hdr->data.publish.msg.bulk_data+sdslen(channel->ptr),
        message->ptr,sdslen(message->ptr));

    if (link)
        clusterSendMessage(link,payload,totlen);
    else
        clusterBroadcastMessage(payload,totlen);

    decrRefCount(channel);
    decrRefCount(message);
    if (payload != buf) zfree(payload);
A
antirez 已提交
2557 2558 2559 2560
}

/* Send a FAIL message to all the nodes we are able to contact.
 * The FAIL message is sent when we detect that a node is failing
A
antirez 已提交
2561 2562
 * (CLUSTER_NODE_PFAIL) and we also receive a gossip confirmation of this:
 * we switch the node state to CLUSTER_NODE_FAIL and ask all the other
A
antirez 已提交
2563 2564
 * nodes to do the same ASAP. */
void clusterSendFail(char *nodename) {
2565
    unsigned char buf[sizeof(clusterMsg)];
A
antirez 已提交
2566 2567 2568
    clusterMsg *hdr = (clusterMsg*) buf;

    clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_FAIL);
A
antirez 已提交
2569
    memcpy(hdr->data.fail.about.nodename,nodename,CLUSTER_NAMELEN);
A
antirez 已提交
2570 2571 2572
    clusterBroadcastMessage(buf,ntohl(hdr->totlen));
}

2573 2574 2575 2576
/* Send an UPDATE message to the specified link carrying the specified 'node'
 * slots configuration. The node name, slots bitmap, and configEpoch info
 * are included. */
void clusterSendUpdate(clusterLink *link, clusterNode *node) {
2577
    unsigned char buf[sizeof(clusterMsg)];
2578 2579
    clusterMsg *hdr = (clusterMsg*) buf;

2580
    if (link == NULL) return;
2581
    clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_UPDATE);
A
antirez 已提交
2582
    memcpy(hdr->data.update.nodecfg.nodename,node->name,CLUSTER_NAMELEN);
2583 2584 2585 2586 2587
    hdr->data.update.nodecfg.configEpoch = htonu64(node->configEpoch);
    memcpy(hdr->data.update.nodecfg.slots,node->slots,sizeof(node->slots));
    clusterSendMessage(link,buf,ntohl(hdr->totlen));
}

2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629
/* Send a MODULE message.
 *
 * If link is NULL, then the message is broadcasted to the whole cluster. */
void clusterSendModule(clusterLink *link, uint64_t module_id, uint8_t type,
                       unsigned char *payload, uint32_t len) {
    unsigned char buf[sizeof(clusterMsg)], *heapbuf;
    clusterMsg *hdr = (clusterMsg*) buf;
    uint32_t totlen;

    clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_MODULE);
    totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
    totlen += sizeof(clusterMsgModule) - 3 + len;

    hdr->data.module.msg.module_id = module_id; /* Already endian adjusted. */
    hdr->data.module.msg.type = type;
    hdr->data.module.msg.len = htonl(len);
    hdr->totlen = htonl(totlen);

    /* Try to use the local buffer if possible */
    if (totlen < sizeof(buf)) {
        heapbuf = buf;
    } else {
        heapbuf = zmalloc(totlen);
        memcpy(heapbuf,hdr,sizeof(*hdr));
        hdr = (clusterMsg*) heapbuf;
    }
    memcpy(hdr->data.module.msg.bulk_data,payload,len);

    if (link)
        clusterSendMessage(link,heapbuf,totlen);
    else
        clusterBroadcastMessage(heapbuf,totlen);

    if (heapbuf != buf) zfree(heapbuf);
}

/* This function gets a cluster node ID string as target, the same way the nodes
 * addresses are represented in the modules side, resolves the node, and sends
 * the message. If the target is NULL the message is broadcasted.
 *
 * The function returns C_OK if the target is valid, otherwise C_ERR is
 * returned. */
2630
int clusterSendModuleMessageToTarget(const char *target, uint64_t module_id, uint8_t type, unsigned char *payload, uint32_t len) {
2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642
    clusterNode *node = NULL;

    if (target != NULL) {
        node = clusterLookupNode(target);
        if (node == NULL || node->link == NULL) return C_ERR;
    }

    clusterSendModule(target ? node->link : NULL,
                      module_id, type, payload, len);
    return C_OK;
}

2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653
/* -----------------------------------------------------------------------------
 * CLUSTER Pub/Sub support
 *
 * For now we do very little, just propagating PUBLISH messages across the whole
 * cluster. In the future we'll try to get smarter and avoiding propagating those
 * messages to hosts without receives for a given channel.
 * -------------------------------------------------------------------------- */
void clusterPropagatePublish(robj *channel, robj *message) {
    clusterSendPublish(NULL, channel, message);
}

2654 2655 2656 2657
/* -----------------------------------------------------------------------------
 * SLAVE node specific functions
 * -------------------------------------------------------------------------- */

2658 2659 2660 2661 2662 2663 2664
/* This function sends a FAILOVE_AUTH_REQUEST message to every node in order to
 * see if there is the quorum for this slave instance to failover its failing
 * master.
 *
 * Note that we send the failover request to everybody, master and slave nodes,
 * but only the masters are supposed to reply to our query. */
void clusterRequestFailoverAuth(void) {
2665
    unsigned char buf[sizeof(clusterMsg)];
2666 2667 2668 2669
    clusterMsg *hdr = (clusterMsg*) buf;
    uint32_t totlen;

    clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_FAILOVER_AUTH_REQUEST);
2670 2671 2672 2673
    /* If this is a manual failover, set the CLUSTERMSG_FLAG0_FORCEACK bit
     * in the header to communicate the nodes receiving the message that
     * they should authorized the failover even if the master is working. */
    if (server.cluster->mf_end) hdr->mflags[0] |= CLUSTERMSG_FLAG0_FORCEACK;
2674 2675
    totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
    hdr->totlen = htonl(totlen);
2676
    clusterBroadcastMessage(buf,totlen);
2677 2678
}

2679 2680
/* Send a FAILOVER_AUTH_ACK message to the specified node. */
void clusterSendFailoverAuth(clusterNode *node) {
2681
    unsigned char buf[sizeof(clusterMsg)];
2682 2683 2684 2685 2686 2687 2688
    clusterMsg *hdr = (clusterMsg*) buf;
    uint32_t totlen;

    if (!node->link) return;
    clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_FAILOVER_AUTH_ACK);
    totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
    hdr->totlen = htonl(totlen);
2689
    clusterSendMessage(node->link,buf,totlen);
2690 2691
}

2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704
/* Send a MFSTART message to the specified node. */
void clusterSendMFStart(clusterNode *node) {
    unsigned char buf[sizeof(clusterMsg)];
    clusterMsg *hdr = (clusterMsg*) buf;
    uint32_t totlen;

    if (!node->link) return;
    clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_MFSTART);
    totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
    hdr->totlen = htonl(totlen);
    clusterSendMessage(node->link,buf,totlen);
}

2705
/* Vote for the node asking for our vote if there are the conditions. */
2706
void clusterSendFailoverAuthIfNeeded(clusterNode *node, clusterMsg *request) {
2707
    clusterNode *master = node->slaveof;
2708 2709 2710
    uint64_t requestCurrentEpoch = ntohu64(request->currentEpoch);
    uint64_t requestConfigEpoch = ntohu64(request->configEpoch);
    unsigned char *claimed_slots = request->myslots;
2711
    int force_ack = request->mflags[0] & CLUSTERMSG_FLAG0_FORCEACK;
2712
    int j;
2713 2714 2715

    /* IF we are not a master serving at least 1 slot, we don't have the
     * right to vote, as the cluster size in Redis Cluster is the number
2716 2717
     * of masters serving at least one slot, and quorum is the cluster
     * size + 1 */
2718
    if (nodeIsSlave(myself) || myself->numslots == 0) return;
2719

2720 2721 2722 2723
    /* Request epoch must be >= our currentEpoch.
     * Note that it is impossible for it to actually be greater since
     * our currentEpoch was updated as a side effect of receiving this
     * request, if the request epoch was greater. */
2724
    if (requestCurrentEpoch < server.cluster->currentEpoch) {
A
antirez 已提交
2725
        serverLog(LL_WARNING,
2726 2727 2728 2729 2730 2731
            "Failover auth denied to %.40s: reqEpoch (%llu) < curEpoch(%llu)",
            node->name,
            (unsigned long long) requestCurrentEpoch,
            (unsigned long long) server.cluster->currentEpoch);
        return;
    }
2732

2733
    /* I already voted for this epoch? Return ASAP. */
2734
    if (server.cluster->lastVoteEpoch == server.cluster->currentEpoch) {
A
antirez 已提交
2735
        serverLog(LL_WARNING,
2736 2737 2738 2739 2740
                "Failover auth denied to %.40s: already voted for epoch %llu",
                node->name,
                (unsigned long long) server.cluster->currentEpoch);
        return;
    }
2741

2742 2743 2744 2745
    /* Node must be a slave and its master down.
     * The master can be non failing if the request is flagged
     * with CLUSTERMSG_FLAG0_FORCEACK (manual failover). */
    if (nodeIsMaster(node) || master == NULL ||
2746 2747 2748
        (!nodeFailed(master) && !force_ack))
    {
        if (nodeIsMaster(node)) {
A
antirez 已提交
2749
            serverLog(LL_WARNING,
2750 2751 2752
                    "Failover auth denied to %.40s: it is a master node",
                    node->name);
        } else if (master == NULL) {
A
antirez 已提交
2753
            serverLog(LL_WARNING,
2754 2755 2756
                    "Failover auth denied to %.40s: I don't know its master",
                    node->name);
        } else if (!nodeFailed(master)) {
A
antirez 已提交
2757
            serverLog(LL_WARNING,
2758 2759 2760 2761 2762
                    "Failover auth denied to %.40s: its master is up",
                    node->name);
        }
        return;
    }
2763

2764 2765 2766
    /* We did not voted for a slave about this master for two
     * times the node timeout. This is not strictly needed for correctness
     * of the algorithm but makes the base case more linear. */
2767
    if (mstime() - node->slaveof->voted_time < server.cluster_node_timeout * 2)
2768
    {
A
antirez 已提交
2769
        serverLog(LL_WARNING,
2770 2771
                "Failover auth denied to %.40s: "
                "can't vote about this master before %lld milliseconds",
2772
                node->name,
2773 2774
                (long long) ((server.cluster_node_timeout*2)-
                             (mstime() - node->slaveof->voted_time)));
2775
        return;
2776
    }
2777

2778 2779 2780
    /* The slave requesting the vote must have a configEpoch for the claimed
     * slots that is >= the one of the masters currently serving the same
     * slots in the current configuration. */
A
antirez 已提交
2781
    for (j = 0; j < CLUSTER_SLOTS; j++) {
2782 2783
        if (bitmapTestBit(claimed_slots, j) == 0) continue;
        if (server.cluster->slots[j] == NULL ||
A
antirez 已提交
2784 2785 2786 2787
            server.cluster->slots[j]->configEpoch <= requestConfigEpoch)
        {
            continue;
        }
2788 2789 2790
        /* If we reached this point we found a slot that in our current slots
         * is served by a master with a greater configEpoch than the one claimed
         * by the slave requesting our vote. Refuse to vote for this slave. */
A
antirez 已提交
2791
        serverLog(LL_WARNING,
2792 2793 2794 2795 2796
                "Failover auth denied to %.40s: "
                "slot %d epoch (%llu) > reqEpoch (%llu)",
                node->name, j,
                (unsigned long long) server.cluster->slots[j]->configEpoch,
                (unsigned long long) requestConfigEpoch);
2797 2798 2799
        return;
    }

2800
    /* We can vote for this slave. */
2801
    server.cluster->lastVoteEpoch = server.cluster->currentEpoch;
2802
    node->slaveof->voted_time = mstime();
2803 2804
    clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|CLUSTER_TODO_FSYNC_CONFIG);
    clusterSendFailoverAuth(node);
A
antirez 已提交
2805
    serverLog(LL_WARNING, "Failover auth granted to %.40s for epoch %llu",
2806
        node->name, (unsigned long long) server.cluster->currentEpoch);
2807 2808
}

2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825
/* This function returns the "rank" of this instance, a slave, in the context
 * of its master-slaves ring. The rank of the slave is given by the number of
 * other slaves for the same master that have a better replication offset
 * compared to the local one (better means, greater, so they claim more data).
 *
 * A slave with rank 0 is the one with the greatest (most up to date)
 * replication offset, and so forth. Note that because how the rank is computed
 * multiple slaves may have the same rank, in case they have the same offset.
 *
 * The slave rank is used to add a delay to start an election in order to
 * get voted and replace a failing master. Slaves with better replication
 * offsets are more likely to win. */
int clusterGetSlaveRank(void) {
    long long myoffset;
    int j, rank = 0;
    clusterNode *master;

A
antirez 已提交
2826
    serverAssert(nodeIsSlave(myself));
2827 2828 2829 2830 2831 2832
    master = myself->slaveof;
    if (master == NULL) return 0; /* Never called by slaves without master. */

    myoffset = replicationGetSlaveOffset();
    for (j = 0; j < master->numslaves; j++)
        if (master->slaves[j] != myself &&
2833
            !nodeCantFailover(master->slaves[j]) &&
2834 2835 2836 2837
            master->slaves[j]->repl_offset > myoffset) rank++;
    return rank;
}

2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850
/* This function is called by clusterHandleSlaveFailover() in order to
 * let the slave log why it is not able to failover. Sometimes there are
 * not the conditions, but since the failover function is called again and
 * again, we can't log the same things continuously.
 *
 * This function works by logging only if a given set of conditions are
 * true:
 *
 * 1) The reason for which the failover can't be initiated changed.
 *    The reasons also include a NONE reason we reset the state to
 *    when the slave finds that its master is fine (no FAIL flag).
 * 2) Also, the log is emitted again if the master is still down and
 *    the reason for not failing over is still the same, but more than
A
antirez 已提交
2851
 *    CLUSTER_CANT_FAILOVER_RELOG_PERIOD seconds elapsed.
2852 2853 2854 2855 2856
 * 3) Finally, the function only logs if the slave is down for more than
 *    five seconds + NODE_TIMEOUT. This way nothing is logged when a
 *    failover starts in a reasonable time.
 *
 * The function is called with the reason why the slave can't failover
A
antirez 已提交
2857
 * which is one of the integer macros CLUSTER_CANT_FAILOVER_*.
2858 2859 2860 2861 2862 2863 2864 2865 2866
 *
 * The function is guaranteed to be called only if 'myself' is a slave. */
void clusterLogCantFailover(int reason) {
    char *msg;
    static time_t lastlog_time = 0;
    mstime_t nolog_fail_time = server.cluster_node_timeout + 5000;

    /* Don't log if we have the same reason for some time. */
    if (reason == server.cluster->cant_failover_reason &&
A
antirez 已提交
2867
        time(NULL)-lastlog_time < CLUSTER_CANT_FAILOVER_RELOG_PERIOD)
2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879
        return;

    server.cluster->cant_failover_reason = reason;

    /* We also don't emit any log if the master failed no long ago, the
     * goal of this function is to log slaves in a stalled condition for
     * a long time. */
    if (myself->slaveof &&
        nodeFailed(myself->slaveof) &&
        (mstime() - myself->slaveof->fail_time) < nolog_fail_time) return;

    switch(reason) {
A
antirez 已提交
2880
    case CLUSTER_CANT_FAILOVER_DATA_AGE:
2881
        msg = "Disconnected from master for longer than allowed. "
2882
              "Please check the 'cluster-replica-validity-factor' configuration "
2883
              "option.";
2884
        break;
A
antirez 已提交
2885
    case CLUSTER_CANT_FAILOVER_WAITING_DELAY:
2886 2887
        msg = "Waiting the delay before I can start a new failover.";
        break;
A
antirez 已提交
2888
    case CLUSTER_CANT_FAILOVER_EXPIRED:
2889 2890
        msg = "Failover attempt expired.";
        break;
A
antirez 已提交
2891
    case CLUSTER_CANT_FAILOVER_WAITING_VOTES:
2892 2893 2894 2895 2896 2897 2898
        msg = "Waiting for votes, but majority still not reached.";
        break;
    default:
        msg = "Unknown reason code.";
        break;
    }
    lastlog_time = time(NULL);
A
antirez 已提交
2899
    serverLog(LL_WARNING,"Currently unable to failover: %s", msg);
2900 2901
}

2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918
/* This function implements the final part of automatic and manual failovers,
 * where the slave grabs its master's hash slots, and propagates the new
 * configuration.
 *
 * Note that it's up to the caller to be sure that the node got a new
 * configuration epoch already. */
void clusterFailoverReplaceYourMaster(void) {
    int j;
    clusterNode *oldmaster = myself->slaveof;

    if (nodeIsMaster(myself) || oldmaster == NULL) return;

    /* 1) Turn this node into a master. */
    clusterSetNodeAsMaster(myself);
    replicationUnsetMaster();

    /* 2) Claim all the slots assigned to our master. */
A
antirez 已提交
2919
    for (j = 0; j < CLUSTER_SLOTS; j++) {
2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937
        if (clusterNodeGetSlotBit(oldmaster,j)) {
            clusterDelSlot(j);
            clusterAddSlot(myself,j);
        }
    }

    /* 3) Update state and save config. */
    clusterUpdateState();
    clusterSaveConfigOrDie(1);

    /* 4) Pong all the other nodes so that they can update the state
     *    accordingly and detect that we switched to master role. */
    clusterBroadcastPong(CLUSTER_BROADCAST_ALL);

    /* 5) If there was a manual failover in progress, clear the state. */
    resetManualFailover();
}

2938
/* This function is called if we are a slave node and our master serving
2939
 * a non-zero amount of hash slots is in FAIL state.
2940 2941 2942
 *
 * The gaol of this function is:
 * 1) To check if we are able to perform a failover, is our data updated?
2943
 * 2) Try to get elected by masters.
2944
 * 3) Perform the failover informing all the other nodes.
2945 2946
 */
void clusterHandleSlaveFailover(void) {
2947
    mstime_t data_age;
2948
    mstime_t auth_age = mstime() - server.cluster->failover_auth_time;
2949
    int needed_quorum = (server.cluster->size / 2) + 1;
2950 2951
    int manual_failover = server.cluster->mf_end != 0 &&
                          server.cluster->mf_can_start;
2952 2953
    mstime_t auth_timeout, auth_retry_time;

2954 2955
    server.cluster->todo_before_sleep &= ~CLUSTER_TODO_HANDLE_FAILOVER;

2956 2957
    /* Compute the failover timeout (the max time we have to send votes
     * and wait for replies), and the failover retry time (the time to wait
2958
     * before trying to get voted again).
2959
     *
A
andyli 已提交
2960
     * Timeout is MAX(NODE_TIMEOUT*2,2000) milliseconds.
2961 2962 2963 2964 2965
     * Retry is two times the Timeout.
     */
    auth_timeout = server.cluster_node_timeout*2;
    if (auth_timeout < 2000) auth_timeout = 2000;
    auth_retry_time = auth_timeout*2;
2966

2967 2968
    /* Pre conditions to run the function, that must be met both in case
     * of an automatic or manual failover:
2969
     * 1) We are a slave.
2970
     * 2) Our master is flagged as FAIL, or this is a manual failover.
2971 2972 2973
     * 3) We don't have the no failover configuration set, and this is
     *    not a manual failover.
     * 4) It is serving slots. */
2974
    if (nodeIsMaster(myself) ||
2975
        myself->slaveof == NULL ||
2976
        (!nodeFailed(myself->slaveof) && !manual_failover) ||
2977
        (server.cluster_slave_no_failover && !manual_failover) ||
2978 2979 2980 2981
        myself->slaveof->numslots == 0)
    {
        /* There are no reasons to failover, so we set the reason why we
         * are returning without failing over to NONE. */
A
antirez 已提交
2982
        server.cluster->cant_failover_reason = CLUSTER_CANT_FAILOVER_NONE;
2983 2984
        return;
    }
2985

2986 2987
    /* Set data_age to the number of seconds we are disconnected from
     * the master. */
A
antirez 已提交
2988
    if (server.repl_state == REPL_STATE_CONNECTED) {
2989 2990
        data_age = (mstime_t)(server.unixtime - server.master->lastinteraction)
                   * 1000;
2991
    } else {
2992
        data_age = (mstime_t)(server.unixtime - server.repl_down_since) * 1000;
2993 2994
    }

2995 2996 2997 2998 2999 3000
    /* Remove the node timeout from the data age as it is fine that we are
     * disconnected from our master at least for the time it was down to be
     * flagged as FAIL, that's the baseline. */
    if (data_age > server.cluster_node_timeout)
        data_age -= server.cluster_node_timeout;

3001 3002
    /* Check if our data is recent enough according to the slave validity
     * factor configured by the user.
3003 3004
     *
     * Check bypassed for manual failovers. */
3005 3006 3007 3008
    if (server.cluster_slave_validity_factor &&
        data_age >
        (((mstime_t)server.repl_ping_slave_period * 1000) +
         (server.cluster_node_timeout * server.cluster_slave_validity_factor)))
3009
    {
3010
        if (!manual_failover) {
A
antirez 已提交
3011
            clusterLogCantFailover(CLUSTER_CANT_FAILOVER_DATA_AGE);
3012 3013
            return;
        }
3014
    }
3015

3016 3017 3018
    /* If the previous failover attempt timedout and the retry time has
     * elapsed, we can setup a new one. */
    if (auth_age > auth_retry_time) {
3019 3020 3021
        server.cluster->failover_auth_time = mstime() +
            500 + /* Fixed delay of 500 milliseconds, let FAIL msg propagate. */
            random() % 500; /* Random delay between 0 and 500 milliseconds. */
3022
        server.cluster->failover_auth_count = 0;
3023
        server.cluster->failover_auth_sent = 0;
3024 3025 3026 3027 3028 3029
        server.cluster->failover_auth_rank = clusterGetSlaveRank();
        /* We add another delay that is proportional to the slave rank.
         * Specifically 1 second * rank. This way slaves that have a probably
         * less updated replication offset, are penalized. */
        server.cluster->failover_auth_time +=
            server.cluster->failover_auth_rank * 1000;
3030 3031 3032 3033 3034
        /* However if this is a manual failover, no delay is needed. */
        if (server.cluster->mf_end) {
            server.cluster->failover_auth_time = mstime();
            server.cluster->failover_auth_rank = 0;
        }
A
antirez 已提交
3035
        serverLog(LL_WARNING,
3036 3037
            "Start of election delayed for %lld milliseconds "
            "(rank #%d, offset %lld).",
3038
            server.cluster->failover_auth_time - mstime(),
3039 3040
            server.cluster->failover_auth_rank,
            replicationGetSlaveOffset());
3041 3042 3043 3044
        /* Now that we have a scheduled election, broadcast our offset
         * to all the other slaves so that they'll updated their offsets
         * if our offset is better. */
        clusterBroadcastPong(CLUSTER_BROADCAST_LOCAL_SLAVES);
3045 3046 3047 3048 3049
        return;
    }

    /* It is possible that we received more updated offsets from other
     * slaves for the same master since we computed our election delay.
3050 3051 3052
     * Update the delay if our rank changed.
     *
     * Not performed if this is a manual failover. */
3053 3054 3055
    if (server.cluster->failover_auth_sent == 0 &&
        server.cluster->mf_end == 0)
    {
3056 3057 3058 3059 3060 3061
        int newrank = clusterGetSlaveRank();
        if (newrank > server.cluster->failover_auth_rank) {
            long long added_delay =
                (newrank - server.cluster->failover_auth_rank) * 1000;
            server.cluster->failover_auth_time += added_delay;
            server.cluster->failover_auth_rank = newrank;
A
antirez 已提交
3062
            serverLog(LL_WARNING,
3063
                "Replica rank updated to #%d, added %lld milliseconds of delay.",
3064 3065
                newrank, added_delay);
        }
3066 3067 3068
    }

    /* Return ASAP if we can't still start the election. */
3069
    if (mstime() < server.cluster->failover_auth_time) {
A
antirez 已提交
3070
        clusterLogCantFailover(CLUSTER_CANT_FAILOVER_WAITING_DELAY);
3071 3072
        return;
    }
3073 3074

    /* Return ASAP if the election is too old to be valid. */
3075
    if (auth_age > auth_timeout) {
A
antirez 已提交
3076
        clusterLogCantFailover(CLUSTER_CANT_FAILOVER_EXPIRED);
3077 3078
        return;
    }
3079 3080 3081 3082 3083

    /* Ask for votes if needed. */
    if (server.cluster->failover_auth_sent == 0) {
        server.cluster->currentEpoch++;
        server.cluster->failover_auth_epoch = server.cluster->currentEpoch;
A
antirez 已提交
3084
        serverLog(LL_WARNING,"Starting a failover election for epoch %llu.",
3085
            (unsigned long long) server.cluster->currentEpoch);
3086
        clusterRequestFailoverAuth();
3087
        server.cluster->failover_auth_sent = 1;
A
antirez 已提交
3088 3089 3090
        clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                             CLUSTER_TODO_UPDATE_STATE|
                             CLUSTER_TODO_FSYNC_CONFIG);
3091 3092 3093 3094
        return; /* Wait for replies. */
    }

    /* Check if we reached the quorum. */
3095
    if (server.cluster->failover_auth_count >= needed_quorum) {
3096
        /* We have the quorum, we can finally failover the master. */
3097

A
antirez 已提交
3098
        serverLog(LL_WARNING,
A
antirez 已提交
3099
            "Failover election won: I'm the new master.");
A
antirez 已提交
3100

3101
        /* Update my configEpoch to the epoch of the election. */
3102
        if (myself->configEpoch < server.cluster->failover_auth_epoch) {
3103
            myself->configEpoch = server.cluster->failover_auth_epoch;
A
antirez 已提交
3104
            serverLog(LL_WARNING,
3105 3106 3107
                "configEpoch set to %llu after successful failover",
                (unsigned long long) myself->configEpoch);
        }
3108

J
Jack Drogon 已提交
3109
        /* Take responsibility for the cluster slots. */
3110
        clusterFailoverReplaceYourMaster();
3111
    } else {
A
antirez 已提交
3112
        clusterLogCantFailover(CLUSTER_CANT_FAILOVER_WAITING_VOTES);
3113
    }
3114 3115
}

3116 3117 3118 3119 3120 3121
/* -----------------------------------------------------------------------------
 * CLUSTER slave migration
 *
 * Slave migration is the process that allows a slave of a master that is
 * already covered by at least another slave, to "migrate" to a master that
 * is orpaned, that is, left with no working slaves.
3122
 * ------------------------------------------------------------------------- */
3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149

/* This function is responsible to decide if this replica should be migrated
 * to a different (orphaned) master. It is called by the clusterCron() function
 * only if:
 *
 * 1) We are a slave node.
 * 2) It was detected that there is at least one orphaned master in
 *    the cluster.
 * 3) We are a slave of one of the masters with the greatest number of
 *    slaves.
 *
 * This checks are performed by the caller since it requires to iterate
 * the nodes anyway, so we spend time into clusterHandleSlaveMigration()
 * if definitely needed.
 *
 * The fuction is called with a pre-computed max_slaves, that is the max
 * number of working (not in FAIL state) slaves for a single master.
 *
 * Additional conditions for migration are examined inside the function.
 */
void clusterHandleSlaveMigration(int max_slaves) {
    int j, okslaves = 0;
    clusterNode *mymaster = myself->slaveof, *target = NULL, *candidate = NULL;
    dictIterator *di;
    dictEntry *de;

    /* Step 1: Don't migrate if the cluster state is not ok. */
A
antirez 已提交
3150
    if (server.cluster->state != CLUSTER_OK) return;
3151

3152 3153
    /* Step 2: Don't migrate if my master will not be left with at least
     *         'migration-barrier' slaves after my migration. */
3154 3155 3156 3157
    if (mymaster == NULL) return;
    for (j = 0; j < mymaster->numslaves; j++)
        if (!nodeFailed(mymaster->slaves[j]) &&
            !nodeTimedOut(mymaster->slaves[j])) okslaves++;
3158
    if (okslaves <= server.cluster_migration_barrier) return;
3159

J
Jack Drogon 已提交
3160
    /* Step 3: Identify a candidate for migration, and check if among the
3161
     * masters with the greatest number of ok slaves, I'm the one with the
A
antirez 已提交
3162
     * smallest node ID (the "candidate slave").
3163
     *
J
Jack Drogon 已提交
3164
     * Note: this means that eventually a replica migration will occur
3165
     * since slaves that are reachable again always have their FAIL flag
A
antirez 已提交
3166 3167 3168 3169
     * cleared, so eventually there must be a candidate. At the same time
     * this does not mean that there are no race conditions possible (two
     * slaves migrating at the same time), but this is unlikely to
     * happen, and harmless when happens. */
3170 3171 3172 3173
    candidate = myself;
    di = dictGetSafeIterator(server.cluster->nodes);
    while((de = dictNext(di)) != NULL) {
        clusterNode *node = dictGetVal(de);
A
antirez 已提交
3174
        int okslaves = 0, is_orphaned = 1;
3175

A
antirez 已提交
3176 3177 3178 3179 3180 3181
        /* We want to migrate only if this master is working, orphaned, and
         * used to have slaves or if failed over a master that had slaves
         * (MIGRATE_TO flag). This way we only migrate to instances that were
         * supposed to have replicas. */
        if (nodeIsSlave(node) || nodeFailed(node)) is_orphaned = 0;
        if (!(node->flags & CLUSTER_NODE_MIGRATE_TO)) is_orphaned = 0;
3182

A
antirez 已提交
3183 3184 3185
        /* Check number of working slaves. */
        if (nodeIsMaster(node)) okslaves = clusterCountNonFailingSlaves(node);
        if (okslaves > 0) is_orphaned = 0;
A
antirez 已提交
3186

A
antirez 已提交
3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199
        if (is_orphaned) {
            if (!target && node->numslots > 0) target = node;

            /* Track the starting time of the orphaned condition for this
             * master. */
            if (!node->orphaned_time) node->orphaned_time = mstime();
        } else {
            node->orphaned_time = 0;
        }

        /* Check if I'm the slave candidate for the migration: attached
         * to a master with the maximum number of slaves and with the smallest
         * node ID. */
3200 3201 3202 3203
        if (okslaves == max_slaves) {
            for (j = 0; j < node->numslaves; j++) {
                if (memcmp(node->slaves[j]->name,
                           candidate->name,
A
antirez 已提交
3204
                           CLUSTER_NAMELEN) < 0)
3205 3206 3207 3208 3209 3210
                {
                    candidate = node->slaves[j];
                }
            }
        }
    }
M
Matt Stancliff 已提交
3211
    dictReleaseIterator(di);
3212 3213

    /* Step 4: perform the migration if there is a target, and if I'm the
A
antirez 已提交
3214 3215 3216 3217 3218
     * candidate, but only if the master is continuously orphaned for a
     * couple of seconds, so that during failovers, we give some time to
     * the natural slaves of this instance to advertise their switch from
     * the old master to the new one. */
    if (target && candidate == myself &&
3219 3220
        (mstime()-target->orphaned_time) > CLUSTER_SLAVE_MIGRATION_DELAY &&
       !(server.cluster_module_flags & CLUSTER_MODULE_FLAG_NO_FAILOVER))
A
antirez 已提交
3221
    {
A
antirez 已提交
3222
        serverLog(LL_WARNING,"Migrating to orphaned master %.40s",
3223 3224 3225 3226 3227
            target->name);
        clusterSetMaster(target);
    }
}

3228 3229 3230 3231 3232 3233 3234 3235
/* -----------------------------------------------------------------------------
 * CLUSTER manual failover
 *
 * This are the important steps performed by slaves during a manual failover:
 * 1) User send CLUSTER FAILOVER command. The failover state is initialized
 *    setting mf_end to the millisecond unix time at which we'll abort the
 *    attempt.
 * 2) Slave sends a MFSTART message to the master requesting to pause clients
A
antirez 已提交
3236
 *    for two times the manual failover timeout CLUSTER_MF_TIMEOUT.
3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274
 *    When master is paused for manual failover, it also starts to flag
 *    packets with CLUSTERMSG_FLAG0_PAUSED.
 * 3) Slave waits for master to send its replication offset flagged as PAUSED.
 * 4) If slave received the offset from the master, and its offset matches,
 *    mf_can_start is set to 1, and clusterHandleSlaveFailover() will perform
 *    the failover as usually, with the difference that the vote request
 *    will be modified to force masters to vote for a slave that has a
 *    working master.
 *
 * From the point of view of the master things are simpler: when a
 * PAUSE_CLIENTS packet is received the master sets mf_end as well and
 * the sender in mf_slave. During the time limit for the manual failover
 * the master will just send PINGs more often to this slave, flagged with
 * the PAUSED flag, so that the slave will set mf_master_offset when receiving
 * a packet from the master with this flag set.
 *
 * The gaol of the manual failover is to perform a fast failover without
 * data loss due to the asynchronous master-slave replication.
 * -------------------------------------------------------------------------- */

/* Reset the manual failover state. This works for both masters and slavesa
 * as all the state about manual failover is cleared.
 *
 * The function can be used both to initialize the manual failover state at
 * startup or to abort a manual failover in progress. */
void resetManualFailover(void) {
    if (server.cluster->mf_end && clientsArePaused()) {
        server.clients_pause_end_time = 0;
        clientsArePaused(); /* Just use the side effect of the function. */
    }
    server.cluster->mf_end = 0; /* No manual failover in progress. */
    server.cluster->mf_can_start = 0;
    server.cluster->mf_slave = NULL;
    server.cluster->mf_master_offset = 0;
}

/* If a manual failover timed out, abort it. */
void manualFailoverCheckTimeout(void) {
3275
    if (server.cluster->mf_end && server.cluster->mf_end < mstime()) {
A
antirez 已提交
3276
        serverLog(LL_WARNING,"Manual failover timed out.");
3277 3278 3279 3280 3281 3282 3283 3284 3285 3286
        resetManualFailover();
    }
}

/* This function is called from the cluster cron function in order to go
 * forward with a manual failover state machine. */
void clusterHandleManualFailover(void) {
    /* Return ASAP if no manual failover is in progress. */
    if (server.cluster->mf_end == 0) return;

3287
    /* If mf_can_start is non-zero, the failover was already triggered so the
3288 3289 3290 3291 3292 3293 3294 3295 3296
     * next steps are performed by clusterHandleSlaveFailover(). */
    if (server.cluster->mf_can_start) return;

    if (server.cluster->mf_master_offset == 0) return; /* Wait for offset... */

    if (server.cluster->mf_master_offset == replicationGetSlaveOffset()) {
        /* Our replication offset matches the master replication offset
         * announced after clients were paused. We can start the failover. */
        server.cluster->mf_can_start = 1;
A
antirez 已提交
3297
        serverLog(LL_WARNING,
A
antirez 已提交
3298 3299
            "All master replication stream processed, "
            "manual failover can start.");
3300 3301 3302
    }
}

A
antirez 已提交
3303 3304 3305 3306
/* -----------------------------------------------------------------------------
 * CLUSTER cron job
 * -------------------------------------------------------------------------- */

3307
/* This is executed 10 times every second */
A
antirez 已提交
3308 3309 3310
void clusterCron(void) {
    dictIterator *di;
    dictEntry *de;
3311 3312 3313 3314
    int update_state = 0;
    int orphaned_masters; /* How many masters there are without ok slaves. */
    int max_slaves; /* Max number of ok slaves for a single master. */
    int this_slaves; /* Number of ok slaves for our master (if we are slave). */
3315
    mstime_t min_pong = 0, now = mstime();
3316
    clusterNode *min_pong_node = NULL;
3317
    static unsigned long long iteration = 0;
3318
    mstime_t handshake_timeout;
3319 3320

    iteration++; /* Number of times this function was called so far. */
A
antirez 已提交
3321

3322 3323 3324 3325 3326 3327 3328 3329 3330
    /* We want to take myself->ip in sync with the cluster-announce-ip option.
     * The option can be set at runtime via CONFIG SET, so we periodically check
     * if the option changed to reflect this into myself->ip. */
    {
        static char *prev_ip = NULL;
        char *curr_ip = server.cluster_announce_ip;
        int changed = 0;

        if (prev_ip == NULL && curr_ip != NULL) changed = 1;
3331 3332
        else if (prev_ip != NULL && curr_ip == NULL) changed = 1;
        else if (prev_ip && curr_ip && strcmp(prev_ip,curr_ip)) changed = 1;
3333 3334

        if (changed) {
3335 3336
            if (prev_ip) zfree(prev_ip);
            prev_ip = curr_ip;
3337

3338
            if (curr_ip) {
3339 3340 3341
                /* We always take a copy of the previous IP address, by
                 * duplicating the string. This way later we can check if
                 * the address really changed. */
3342
                prev_ip = zstrdup(prev_ip);
3343 3344 3345 3346 3347 3348 3349 3350
                strncpy(myself->ip,server.cluster_announce_ip,NET_IP_STR_LEN);
                myself->ip[NET_IP_STR_LEN-1] = '\0';
            } else {
                myself->ip[0] = '\0'; /* Force autodetection. */
            }
        }
    }

3351
    /* The handshake timeout is the time after which a handshake node that was
3352 3353 3354 3355 3356 3357
     * not turned into a normal node is removed from the nodes. Usually it is
     * just the NODE_TIMEOUT value, but when NODE_TIMEOUT is too small we use
     * the value of 1 second. */
    handshake_timeout = server.cluster_node_timeout;
    if (handshake_timeout < 1000) handshake_timeout = 1000;

3358 3359 3360
    /* Update myself flags. */
    clusterUpdateMyselfFlags();

3361 3362 3363
    /* Check if we have disconnected nodes and re-establish the connection.
     * Also update a few stats while we are here, that can be used to make
     * better decisions in other part of the code. */
3364
    di = dictGetSafeIterator(server.cluster->nodes);
3365
    server.cluster->stats_pfail_nodes = 0;
A
antirez 已提交
3366
    while((de = dictNext(di)) != NULL) {
3367
        clusterNode *node = dictGetVal(de);
A
antirez 已提交
3368

3369 3370
        /* Not interested in reconnecting the link with myself or nodes
         * for which we have no address. */
A
antirez 已提交
3371
        if (node->flags & (CLUSTER_NODE_MYSELF|CLUSTER_NODE_NOADDR)) continue;
3372

3373 3374 3375
        if (node->flags & CLUSTER_NODE_PFAIL)
            server.cluster->stats_pfail_nodes++;

3376 3377
        /* A Node in HANDSHAKE state has a limited lifespan equal to the
         * configured node timeout. */
3378
        if (nodeInHandshake(node) && now - node->ctime > handshake_timeout) {
3379
            clusterDelNode(node);
3380 3381 3382
            continue;
        }

A
antirez 已提交
3383 3384
        if (node->link == NULL) {
            int fd;
3385
            mstime_t old_ping_sent;
A
antirez 已提交
3386 3387
            clusterLink *link;

3388
            fd = anetTcpNonBlockBindConnect(server.neterr, node->ip,
3389
                node->cport, NET_FIRST_BIND_ADDR);
3390
            if (fd == -1) {
3391 3392 3393 3394 3395 3396
                /* We got a synchronous error from connect before
                 * clusterSendPing() had a chance to be called.
                 * If node->ping_sent is zero, failure detection can't work,
                 * so we claim we actually sent a ping now (that will
                 * be really sent as soon as the link is obtained). */
                if (node->ping_sent == 0) node->ping_sent = mstime();
A
antirez 已提交
3397
                serverLog(LL_DEBUG, "Unable to connect to "
3398
                    "Cluster Node [%s]:%d -> %s", node->ip,
3399
                    node->cport, server.neterr);
3400 3401
                continue;
            }
A
antirez 已提交
3402 3403 3404
            link = createClusterLink(node);
            link->fd = fd;
            node->link = link;
A
antirez 已提交
3405 3406
            aeCreateFileEvent(server.el,link->fd,AE_READABLE,
                    clusterReadHandler,link);
3407 3408 3409 3410
            /* Queue a PING in the new connection ASAP: this is crucial
             * to avoid false positives in failure detection.
             *
             * If the node is flagged as MEET, we send a MEET message instead
A
antirez 已提交
3411 3412
             * of a PING one, to force the receiver to add us in its node
             * table. */
3413
            old_ping_sent = node->ping_sent;
A
antirez 已提交
3414
            clusterSendPing(link, node->flags & CLUSTER_NODE_MEET ?
A
antirez 已提交
3415
                    CLUSTERMSG_TYPE_MEET : CLUSTERMSG_TYPE_PING);
3416 3417 3418 3419 3420 3421
            if (old_ping_sent) {
                /* If there was an active ping before the link was
                 * disconnected, we want to restore the ping time, otherwise
                 * replaced by the clusterSendPing() call. */
                node->ping_sent = old_ping_sent;
            }
A
antirez 已提交
3422 3423 3424 3425 3426
            /* We can clear the flag after the first packet is sent.
             * If we'll never receive a PONG, we'll never send new packets
             * to this node. Instead after the PONG is received and we
             * are no longer in meet/handshake status, we want to send
             * normal PING packets. */
A
antirez 已提交
3427
            node->flags &= ~CLUSTER_NODE_MEET;
A
antirez 已提交
3428

A
antirez 已提交
3429
            serverLog(LL_DEBUG,"Connecting with Node %.40s at %s:%d",
3430
                    node->name, node->ip, node->cport);
A
antirez 已提交
3431 3432 3433 3434
        }
    }
    dictReleaseIterator(di);

3435 3436 3437
    /* Ping some random node 1 time every 10 iterations, so that we usually ping
     * one random node every second. */
    if (!(iteration % 10)) {
3438 3439
        int j;

3440 3441 3442 3443 3444 3445 3446 3447
        /* Check a few random nodes and ping the one with the oldest
         * pong_received time. */
        for (j = 0; j < 5; j++) {
            de = dictGetRandomKey(server.cluster->nodes);
            clusterNode *this = dictGetVal(de);

            /* Don't ping nodes disconnected or with a ping currently active. */
            if (this->link == NULL || this->ping_sent != 0) continue;
A
antirez 已提交
3448
            if (this->flags & (CLUSTER_NODE_MYSELF|CLUSTER_NODE_HANDSHAKE))
A
antirez 已提交
3449
                continue;
3450 3451 3452 3453 3454 3455
            if (min_pong_node == NULL || min_pong > this->pong_received) {
                min_pong_node = this;
                min_pong = this->pong_received;
            }
        }
        if (min_pong_node) {
A
antirez 已提交
3456
            serverLog(LL_DEBUG,"Pinging node %.40s", min_pong_node->name);
3457
            clusterSendPing(min_pong_node->link, CLUSTERMSG_TYPE_PING);
A
antirez 已提交
3458 3459 3460
        }
    }

3461 3462 3463 3464 3465 3466 3467 3468 3469
    /* Iterate nodes to check if we need to flag something as failing.
     * This loop is also responsible to:
     * 1) Check if there are orphaned masters (masters without non failing
     *    slaves).
     * 2) Count the max number of non failing slaves for a single master.
     * 3) Count the number of slaves for our master, if we are a slave. */
    orphaned_masters = 0;
    max_slaves = 0;
    this_slaves = 0;
3470
    di = dictGetSafeIterator(server.cluster->nodes);
A
antirez 已提交
3471
    while((de = dictNext(di)) != NULL) {
3472
        clusterNode *node = dictGetVal(de);
3473
        now = mstime(); /* Use an updated time at every iteration. */
3474
        mstime_t delay;
A
antirez 已提交
3475 3476

        if (node->flags &
A
antirez 已提交
3477
            (CLUSTER_NODE_MYSELF|CLUSTER_NODE_NOADDR|CLUSTER_NODE_HANDSHAKE))
3478
                continue;
3479

3480 3481 3482 3483 3484
        /* Orphaned master check, useful only if the current instance
         * is a slave that may migrate to another master. */
        if (nodeIsSlave(myself) && nodeIsMaster(node) && !nodeFailed(node)) {
            int okslaves = clusterCountNonFailingSlaves(node);

3485 3486
            /* A master is orphaned if it is serving a non-zero number of
             * slots, have no working slaves, but used to have at least one
3487 3488 3489 3490
             * slave, or failed over a master that used to have slaves. */
            if (okslaves == 0 && node->numslots > 0 &&
                node->flags & CLUSTER_NODE_MIGRATE_TO)
            {
3491
                orphaned_masters++;
3492
            }
3493 3494 3495 3496 3497
            if (okslaves > max_slaves) max_slaves = okslaves;
            if (nodeIsSlave(myself) && myself->slaveof == node)
                this_slaves = okslaves;
        }

3498 3499 3500 3501
        /* If we are waiting for the PONG more than half the cluster
         * timeout, reconnect the link: maybe there is a connection
         * issue even if the node is alive. */
        if (node->link && /* is connected */
3502
            now - node->link->ctime >
3503
            server.cluster_node_timeout && /* was not already reconnected */
3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516
            node->ping_sent && /* we already sent a ping */
            node->pong_received < node->ping_sent && /* still waiting pong */
            /* and we are waiting for the pong more than timeout/2 */
            now - node->ping_sent > server.cluster_node_timeout/2)
        {
            /* Disconnect the link, it will be reconnected automatically. */
            freeClusterLink(node->link);
        }

        /* If we have currently no active ping in this instance, and the
         * received PONG is older than half the cluster timeout, send
         * a new ping now, to ensure all the nodes are pinged without
         * a too big delay. */
3517
        if (node->link &&
3518 3519
            node->ping_sent == 0 &&
            (now - node->pong_received) > server.cluster_node_timeout/2)
3520 3521 3522 3523 3524
        {
            clusterSendPing(node->link, CLUSTERMSG_TYPE_PING);
            continue;
        }

3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535
        /* If we are a master and one of the slaves requested a manual
         * failover, ping it continuously. */
        if (server.cluster->mf_end &&
            nodeIsMaster(myself) &&
            server.cluster->mf_slave == node &&
            node->link)
        {
            clusterSendPing(node->link, CLUSTERMSG_TYPE_PING);
            continue;
        }

3536 3537
        /* Check only if we have an active ping for this instance. */
        if (node->ping_sent == 0) continue;
3538

3539 3540 3541 3542
        /* Compute the delay of the PONG. Note that if we already received
         * the PONG, then node->ping_sent is zero, so can't reach this
         * code at all. */
        delay = now - node->ping_sent;
3543

3544
        if (delay > server.cluster_node_timeout) {
G
guiquanz 已提交
3545
            /* Timeout reached. Set the node as possibly failing if it is
3546
             * not already in this state. */
A
antirez 已提交
3547
            if (!(node->flags & (CLUSTER_NODE_PFAIL|CLUSTER_NODE_FAIL))) {
A
antirez 已提交
3548
                serverLog(LL_DEBUG,"*** NODE %.40s possibly failing",
A
antirez 已提交
3549
                    node->name);
A
antirez 已提交
3550
                node->flags |= CLUSTER_NODE_PFAIL;
3551
                update_state = 1;
A
antirez 已提交
3552 3553 3554 3555
            }
        }
    }
    dictReleaseIterator(di);
3556 3557 3558 3559

    /* If we are a slave node but the replication is still turned off,
     * enable it if we know the address of our master and it appears to
     * be up. */
3560
    if (nodeIsSlave(myself) &&
3561
        server.masterhost == NULL &&
3562
        myself->slaveof &&
3563
        nodeHasAddr(myself->slaveof))
3564
    {
3565
        replicationSetMaster(myself->slaveof->ip, myself->slaveof->port);
3566
    }
3567

3568 3569 3570
    /* Abourt a manual failover if the timeout is reached. */
    manualFailoverCheckTimeout();

3571
    if (nodeIsSlave(myself)) {
3572
        clusterHandleManualFailover();
3573 3574
        if (!(server.cluster_module_flags & CLUSTER_MODULE_FLAG_NO_FAILOVER))
            clusterHandleSlaveFailover();
3575 3576 3577 3578 3579 3580 3581 3582 3583
        /* If there are orphaned slaves, and we are a slave among the masters
         * with the max number of non-failing slaves, consider migrating to
         * the orphaned masters. Note that it does not make sense to try
         * a migration if there is no master with at least *two* working
         * slaves. */
        if (orphaned_masters && max_slaves >= 2 && this_slaves == max_slaves)
            clusterHandleSlaveMigration(max_slaves);
    }

A
antirez 已提交
3584
    if (update_state || server.cluster->state == CLUSTER_FAIL)
3585
        clusterUpdateState();
3586 3587 3588 3589 3590
}

/* This function is called before the event handler returns to sleep for
 * events. It is useful to perform operations that must be done ASAP in
 * reaction to events fired but that are not safe to perform inside event
A
antirez 已提交
3591 3592
 * handlers, or to perform potentially expansive tasks that we need to do
 * a single time before replying to clients. */
3593
void clusterBeforeSleep(void) {
A
antirez 已提交
3594 3595 3596
    /* Handle failover, this is needed when it is likely that there is already
     * the quorum from masters in order to react fast. */
    if (server.cluster->todo_before_sleep & CLUSTER_TODO_HANDLE_FAILOVER)
3597
        clusterHandleSlaveFailover();
A
antirez 已提交
3598 3599 3600 3601 3602 3603 3604

    /* Update the cluster state. */
    if (server.cluster->todo_before_sleep & CLUSTER_TODO_UPDATE_STATE)
        clusterUpdateState();

    /* Save the config, possibly using fsync. */
    if (server.cluster->todo_before_sleep & CLUSTER_TODO_SAVE_CONFIG) {
A
antirez 已提交
3605 3606
        int fsync = server.cluster->todo_before_sleep &
                    CLUSTER_TODO_FSYNC_CONFIG;
A
antirez 已提交
3607
        clusterSaveConfigOrDie(fsync);
3608
    }
A
antirez 已提交
3609

3610 3611
    /* Reset our flags (not strictly needed since every single function
     * called for flags set should be able to clear its flag). */
A
antirez 已提交
3612 3613 3614 3615 3616
    server.cluster->todo_before_sleep = 0;
}

void clusterDoBeforeSleep(int flags) {
    server.cluster->todo_before_sleep |= flags;
A
antirez 已提交
3617 3618 3619 3620 3621 3622
}

/* -----------------------------------------------------------------------------
 * Slots management
 * -------------------------------------------------------------------------- */

3623
/* Test bit 'pos' in a generic bitmap. Return 1 if the bit is set,
3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644
 * otherwise 0. */
int bitmapTestBit(unsigned char *bitmap, int pos) {
    off_t byte = pos/8;
    int bit = pos&7;
    return (bitmap[byte] & (1<<bit)) != 0;
}

/* Set the bit at position 'pos' in a bitmap. */
void bitmapSetBit(unsigned char *bitmap, int pos) {
    off_t byte = pos/8;
    int bit = pos&7;
    bitmap[byte] |= 1<<bit;
}

/* Clear the bit at position 'pos' in a bitmap. */
void bitmapClearBit(unsigned char *bitmap, int pos) {
    off_t byte = pos/8;
    int bit = pos&7;
    bitmap[byte] &= ~(1<<bit);
}

3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661
/* Return non-zero if there is at least one master with slaves in the cluster.
 * Otherwise zero is returned. Used by clusterNodeSetSlotBit() to set the
 * MIGRATE_TO flag the when a master gets the first slot. */
int clusterMastersHaveSlaves(void) {
    dictIterator *di = dictGetSafeIterator(server.cluster->nodes);
    dictEntry *de;
    int slaves = 0;
    while((de = dictNext(di)) != NULL) {
        clusterNode *node = dictGetVal(de);

        if (nodeIsSlave(node)) continue;
        slaves += node->numslaves;
    }
    dictReleaseIterator(di);
    return slaves != 0;
}

A
antirez 已提交
3662 3663
/* Set the slot bit and return the old value. */
int clusterNodeSetSlotBit(clusterNode *n, int slot) {
3664 3665
    int old = bitmapTestBit(n->slots,slot);
    bitmapSetBit(n->slots,slot);
3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683
    if (!old) {
        n->numslots++;
        /* When a master gets its first slot, even if it has no slaves,
         * it gets flagged with MIGRATE_TO, that is, the master is a valid
         * target for replicas migration, if and only if at least one of
         * the other masters has slaves right now.
         *
         * Normally masters are valid targerts of replica migration if:
         * 1. The used to have slaves (but no longer have).
         * 2. They are slaves failing over a master that used to have slaves.
         *
         * However new masters with slots assigned are considered valid
         * migration tagets if the rest of the cluster is not a slave-less.
         *
         * See https://github.com/antirez/redis/issues/3043 for more info. */
        if (n->numslots == 1 && clusterMastersHaveSlaves())
            n->flags |= CLUSTER_NODE_MIGRATE_TO;
    }
A
antirez 已提交
3684 3685 3686 3687 3688
    return old;
}

/* Clear the slot bit and return the old value. */
int clusterNodeClearSlotBit(clusterNode *n, int slot) {
3689 3690
    int old = bitmapTestBit(n->slots,slot);
    bitmapClearBit(n->slots,slot);
3691
    if (old) n->numslots--;
A
antirez 已提交
3692 3693 3694 3695 3696
    return old;
}

/* Return the slot bit from the cluster node structure. */
int clusterNodeGetSlotBit(clusterNode *n, int slot) {
3697
    return bitmapTestBit(n->slots,slot);
A
antirez 已提交
3698 3699 3700
}

/* Add the specified slot to the list of slots that node 'n' will
3701
 * serve. Return C_OK if the operation ended with success.
A
antirez 已提交
3702
 * If the slot is already assigned to another instance this is considered
3703
 * an error and C_ERR is returned. */
A
antirez 已提交
3704
int clusterAddSlot(clusterNode *n, int slot) {
3705
    if (server.cluster->slots[slot]) return C_ERR;
3706
    clusterNodeSetSlotBit(n,slot);
3707
    server.cluster->slots[slot] = n;
3708
    return C_OK;
A
antirez 已提交
3709 3710
}

A
antirez 已提交
3711
/* Delete the specified slot marking it as unassigned.
3712 3713
 * Returns C_OK if the slot was assigned, otherwise if the slot was
 * already unassigned C_ERR is returned. */
A
antirez 已提交
3714
int clusterDelSlot(int slot) {
3715
    clusterNode *n = server.cluster->slots[slot];
A
antirez 已提交
3716

3717
    if (!n) return C_ERR;
A
antirez 已提交
3718
    serverAssert(clusterNodeClearSlotBit(n,slot) == 1);
3719
    server.cluster->slots[slot] = NULL;
3720
    return C_OK;
A
antirez 已提交
3721 3722
}

3723 3724 3725 3726 3727
/* Delete all the slots associated with the specified node.
 * The number of deleted slots is returned. */
int clusterDelNodeSlots(clusterNode *node) {
    int deleted = 0, j;

A
antirez 已提交
3728
    for (j = 0; j < CLUSTER_SLOTS; j++) {
3729 3730 3731 3732
        if (clusterNodeGetSlotBit(node,j)) {
            clusterDelSlot(j);
            deleted++;
        }
3733 3734 3735 3736
    }
    return deleted;
}

A
antirez 已提交
3737 3738 3739 3740 3741 3742 3743 3744 3745
/* Clear the migrating / importing state for all the slots.
 * This is useful at initialization and when turning a master into slave. */
void clusterCloseAllSlots(void) {
    memset(server.cluster->migrating_slots_to,0,
        sizeof(server.cluster->migrating_slots_to));
    memset(server.cluster->importing_slots_from,0,
        sizeof(server.cluster->importing_slots_from));
}

A
antirez 已提交
3746 3747 3748
/* -----------------------------------------------------------------------------
 * Cluster state evaluation function
 * -------------------------------------------------------------------------- */
3749

3750
/* The following are defines that are only used in the evaluation function
J
Jack Drogon 已提交
3751
 * and are based on heuristics. Actually the main point about the rejoin and
3752 3753
 * writable delay is that they should be a few orders of magnitude larger
 * than the network latency. */
A
antirez 已提交
3754 3755 3756
#define CLUSTER_MAX_REJOIN_DELAY 5000
#define CLUSTER_MIN_REJOIN_DELAY 500
#define CLUSTER_WRITABLE_DELAY 2000
3757

A
antirez 已提交
3758
void clusterUpdateState(void) {
3759
    int j, new_state;
3760
    int reachable_masters = 0;
3761
    static mstime_t among_minority_time;
3762 3763
    static mstime_t first_call_time = 0;

3764 3765
    server.cluster->todo_before_sleep &= ~CLUSTER_TODO_UPDATE_STATE;

3766 3767 3768 3769 3770 3771 3772
    /* If this is a master node, wait some time before turning the state
     * into OK, since it is not a good idea to rejoin the cluster as a writable
     * master, after a reboot, without giving the cluster a chance to
     * reconfigure this node. Note that the delay is calculated starting from
     * the first call to this function and not since the server start, in order
     * to don't count the DB loading time. */
    if (first_call_time == 0) first_call_time = mstime();
3773
    if (nodeIsMaster(myself) &&
A
antirez 已提交
3774 3775
        server.cluster->state == CLUSTER_FAIL &&
        mstime() - first_call_time < CLUSTER_WRITABLE_DELAY) return;
A
antirez 已提交
3776

3777 3778
    /* Start assuming the state is OK. We'll turn it into FAIL if there
     * are the right conditions. */
A
antirez 已提交
3779
    new_state = CLUSTER_OK;
3780

3781
    /* Check if all the slots are covered. */
3782
    if (server.cluster_require_full_coverage) {
A
antirez 已提交
3783
        for (j = 0; j < CLUSTER_SLOTS; j++) {
3784
            if (server.cluster->slots[j] == NULL ||
A
antirez 已提交
3785
                server.cluster->slots[j]->flags & (CLUSTER_NODE_FAIL))
3786
            {
A
antirez 已提交
3787
                new_state = CLUSTER_FAIL;
3788 3789
                break;
            }
A
antirez 已提交
3790 3791
        }
    }
3792

3793
    /* Compute the cluster size, that is the number of master nodes
3794 3795
     * serving at least a single slot.
     *
3796 3797
     * At the same time count the number of reachable masters having
     * at least one slot. */
3798 3799 3800 3801 3802
    {
        dictIterator *di;
        dictEntry *de;

        server.cluster->size = 0;
3803
        di = dictGetSafeIterator(server.cluster->nodes);
3804 3805 3806
        while((de = dictNext(di)) != NULL) {
            clusterNode *node = dictGetVal(de);

3807
            if (nodeIsMaster(node) && node->numslots) {
3808
                server.cluster->size++;
A
antirez 已提交
3809
                if ((node->flags & (CLUSTER_NODE_FAIL|CLUSTER_NODE_PFAIL)) == 0)
3810
                    reachable_masters++;
3811
            }
3812 3813 3814
        }
        dictReleaseIterator(di);
    }
3815

3816 3817
    /* If we are in a minority partition, change the cluster state
     * to FAIL. */
3818 3819
    {
        int needed_quorum = (server.cluster->size / 2) + 1;
3820

3821
        if (reachable_masters < needed_quorum) {
A
antirez 已提交
3822
            new_state = CLUSTER_FAIL;
3823 3824
            among_minority_time = mstime();
        }
3825 3826
    }

3827
    /* Log a state change */
3828 3829 3830 3831 3832 3833 3834
    if (new_state != server.cluster->state) {
        mstime_t rejoin_delay = server.cluster_node_timeout;

        /* If the instance is a master and was partitioned away with the
         * minority, don't let it accept queries for some time after the
         * partition heals, to make sure there is enough time to receive
         * a configuration update. */
A
antirez 已提交
3835 3836 3837 3838
        if (rejoin_delay > CLUSTER_MAX_REJOIN_DELAY)
            rejoin_delay = CLUSTER_MAX_REJOIN_DELAY;
        if (rejoin_delay < CLUSTER_MIN_REJOIN_DELAY)
            rejoin_delay = CLUSTER_MIN_REJOIN_DELAY;
3839

A
antirez 已提交
3840
        if (new_state == CLUSTER_OK &&
3841
            nodeIsMaster(myself) &&
3842 3843 3844 3845 3846 3847
            mstime() - among_minority_time < rejoin_delay)
        {
            return;
        }

        /* Change the state and log the event. */
A
antirez 已提交
3848
        serverLog(LL_WARNING,"Cluster state changed: %s",
A
antirez 已提交
3849
            new_state == CLUSTER_OK ? "ok" : "fail");
3850 3851
        server.cluster->state = new_state;
    }
A
antirez 已提交
3852 3853
}

3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864
/* This function is called after the node startup in order to verify that data
 * loaded from disk is in agreement with the cluster configuration:
 *
 * 1) If we find keys about hash slots we have no responsibility for, the
 *    following happens:
 *    A) If no other node is in charge according to the current cluster
 *       configuration, we add these slots to our node.
 *    B) If according to our config other nodes are already in charge for
 *       this lots, we set the slots as IMPORTING from our point of view
 *       in order to justify we have those slots, and in order to make
 *       redis-trib aware of the issue, so that it can try to fix it.
3865
 * 2) If we find data in a DB different than DB0 we return C_ERR to
3866 3867 3868
 *    signal the caller it should quit the server with an error message
 *    or take other actions.
 *
3869
 * The function always returns C_OK even if it will try to correct
3870
 * the error described in "1". However if data is found in DB different
3871
 * from DB0, C_ERR is returned.
3872 3873 3874 3875 3876
 *
 * The function also uses the logging facility in order to warn the user
 * about desynchronizations between the data we have in memory and the
 * cluster configuration. */
int verifyClusterConfigWithData(void) {
3877 3878 3879
    int j;
    int update_config = 0;

3880 3881 3882 3883 3884
    /* Return ASAP if a module disabled cluster redirections. In that case
     * every master can store keys about every possible hash slot. */
    if (server.cluster_module_flags & CLUSTER_MODULE_FLAG_NO_REDIRECTION)
        return C_OK;

3885 3886
    /* If this node is a slave, don't perform the check at all as we
     * completely depend on the replication stream. */
3887
    if (nodeIsSlave(myself)) return C_OK;
3888

3889 3890
    /* Make sure we only have keys in DB0. */
    for (j = 1; j < server.dbnum; j++) {
3891
        if (dictSize(server.db[j].dict)) return C_ERR;
3892 3893 3894 3895
    }

    /* Check that all the slots we see populated memory have a corresponding
     * entry in the cluster table. Otherwise fix the table. */
A
antirez 已提交
3896
    for (j = 0; j < CLUSTER_SLOTS; j++) {
3897 3898 3899 3900
        if (!countKeysInSlot(j)) continue; /* No keys in this slot. */
        /* Check if we are assigned to this slot or if we are importing it.
         * In both cases check the next slot as the configuration makes
         * sense. */
3901
        if (server.cluster->slots[j] == myself ||
3902 3903 3904 3905 3906 3907 3908
            server.cluster->importing_slots_from[j] != NULL) continue;

        /* If we are here data and cluster config don't agree, and we have
         * slot 'j' populated even if we are not importing it, nor we are
         * assigned to this slot. Fix this condition. */

        update_config++;
3909
        /* Case A: slot is unassigned. Take responsibility for it. */
3910
        if (server.cluster->slots[j] == NULL) {
A
antirez 已提交
3911
            serverLog(LL_WARNING, "I have keys for unassigned slot %d. "
3912
                                    "Taking responsibility for it.",j);
3913
            clusterAddSlot(myself,j);
3914
        } else {
A
antirez 已提交
3915
            serverLog(LL_WARNING, "I have keys for slot %d, but the slot is "
3916 3917
                                    "assigned to another node. "
                                    "Setting it to importing state.",j);
3918 3919 3920
            server.cluster->importing_slots_from[j] = server.cluster->slots[j];
        }
    }
A
antirez 已提交
3921
    if (update_config) clusterSaveConfigOrDie(1);
3922
    return C_OK;
3923 3924
}

3925 3926 3927 3928
/* -----------------------------------------------------------------------------
 * SLAVE nodes handling
 * -------------------------------------------------------------------------- */

3929 3930
/* Set the specified node 'n' as master for this node.
 * If this node is currently a master, it is turned into a slave. */
3931
void clusterSetMaster(clusterNode *n) {
A
antirez 已提交
3932 3933
    serverAssert(n != myself);
    serverAssert(myself->numslots == 0);
3934

3935
    if (nodeIsMaster(myself)) {
3936
        myself->flags &= ~(CLUSTER_NODE_MASTER|CLUSTER_NODE_MIGRATE_TO);
A
antirez 已提交
3937
        myself->flags |= CLUSTER_NODE_SLAVE;
3938
        clusterCloseAllSlots();
3939 3940 3941
    } else {
        if (myself->slaveof)
            clusterNodeRemoveSlave(myself->slaveof,myself);
3942 3943
    }
    myself->slaveof = n;
3944
    clusterNodeAddSlave(n,myself);
3945
    replicationSetMaster(n->ip, n->port);
3946
    resetManualFailover();
3947 3948
}

A
antirez 已提交
3949
/* -----------------------------------------------------------------------------
3950
 * Nodes to string representation functions.
A
antirez 已提交
3951 3952
 * -------------------------------------------------------------------------- */

3953 3954 3955 3956 3957 3958
struct redisNodeFlags {
    uint16_t flag;
    char *name;
};

static struct redisNodeFlags redisNodeFlagsTable[] = {
3959 3960 3961 3962 3963 3964
    {CLUSTER_NODE_MYSELF,       "myself,"},
    {CLUSTER_NODE_MASTER,       "master,"},
    {CLUSTER_NODE_SLAVE,        "slave,"},
    {CLUSTER_NODE_PFAIL,        "fail?,"},
    {CLUSTER_NODE_FAIL,         "fail,"},
    {CLUSTER_NODE_HANDSHAKE,    "handshake,"},
3965 3966
    {CLUSTER_NODE_NOADDR,       "noaddr,"},
    {CLUSTER_NODE_NOFAILOVER,   "nofailover,"}
3967 3968 3969 3970
};

/* Concatenate the comma separated list of node flags to the given SDS
 * string 'ci'. */
3971
sds representClusterNodeFlags(sds ci, uint16_t flags) {
3972 3973 3974 3975 3976 3977 3978 3979
    size_t orig_len = sdslen(ci);
    int i, size = sizeof(redisNodeFlagsTable)/sizeof(struct redisNodeFlags);
    for (i = 0; i < size; i++) {
        struct redisNodeFlags *nodeflag = redisNodeFlagsTable + i;
        if (flags & nodeflag->flag) ci = sdscat(ci, nodeflag->name);
    }
    /* If no flag was added, add the "noflags" special flag. */
    if (sdslen(ci) == orig_len) ci = sdscat(ci,"noflags,");
3980 3981 3982 3983
    sdsIncrLen(ci,-1); /* Remove trailing comma. */
    return ci;
}

3984 3985 3986
/* Generate a csv-alike representation of the specified cluster node.
 * See clusterGenNodesDescription() top comment for more information.
 *
3987 3988
 * The function returns the string representation as an SDS string. */
sds clusterGenNodeDescription(clusterNode *node) {
3989
    int j, start;
3990
    sds ci;
3991 3992

    /* Node coordinates */
3993
    ci = sdscatprintf(sdsempty(),"%.40s %s:%d@%d ",
3994 3995
        node->name,
        node->ip,
3996 3997
        node->port,
        node->cport);
3998 3999

    /* Flags */
4000
    ci = representClusterNodeFlags(ci, node->flags);
4001 4002

    /* Slave of... or just "-" */
4003 4004 4005
    if (node->slaveof)
        ci = sdscatprintf(ci," %.40s ",node->slaveof->name);
    else
4006
        ci = sdscatlen(ci," - ",3);
4007

A
antirez 已提交
4008
    /* Latency from the POV of this node, config epoch, link status */
4009
    ci = sdscatprintf(ci,"%lld %lld %llu %s",
4010 4011 4012
        (long long) node->ping_sent,
        (long long) node->pong_received,
        (unsigned long long) node->configEpoch,
A
antirez 已提交
4013
        (node->link || node->flags & CLUSTER_NODE_MYSELF) ?
4014 4015 4016 4017
                    "connected" : "disconnected");

    /* Slots served by this instance */
    start = -1;
A
antirez 已提交
4018
    for (j = 0; j < CLUSTER_SLOTS; j++) {
4019 4020 4021 4022 4023
        int bit;

        if ((bit = clusterNodeGetSlotBit(node,j)) != 0) {
            if (start == -1) start = j;
        }
A
antirez 已提交
4024 4025
        if (start != -1 && (!bit || j == CLUSTER_SLOTS-1)) {
            if (bit && j == CLUSTER_SLOTS-1) j++;
4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038

            if (start == j-1) {
                ci = sdscatprintf(ci," %d",start);
            } else {
                ci = sdscatprintf(ci," %d-%d",start,j-1);
            }
            start = -1;
        }
    }

    /* Just for MYSELF node we also dump info about slots that
     * we are migrating to other instances or importing from other
     * instances. */
A
antirez 已提交
4039 4040
    if (node->flags & CLUSTER_NODE_MYSELF) {
        for (j = 0; j < CLUSTER_SLOTS; j++) {
4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052
            if (server.cluster->migrating_slots_to[j]) {
                ci = sdscatprintf(ci," [%d->-%.40s]",j,
                    server.cluster->migrating_slots_to[j]->name);
            } else if (server.cluster->importing_slots_from[j]) {
                ci = sdscatprintf(ci," [%d-<-%.40s]",j,
                    server.cluster->importing_slots_from[j]->name);
            }
        }
    }
    return ci;
}

4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065
/* Generate a csv-alike representation of the nodes we are aware of,
 * including the "myself" node, and return an SDS string containing the
 * representation (it is up to the caller to free it).
 *
 * All the nodes matching at least one of the node flags specified in
 * "filter" are excluded from the output, so using zero as a filter will
 * include all the known nodes in the representation, including nodes in
 * the HANDSHAKE state.
 *
 * The representation obtained using this function is used for the output
 * of the CLUSTER NODES function, and as format for the cluster
 * configuration file (nodes.conf) for a given node. */
sds clusterGenNodesDescription(int filter) {
4066
    sds ci = sdsempty(), ni;
A
antirez 已提交
4067 4068 4069
    dictIterator *di;
    dictEntry *de;

4070
    di = dictGetSafeIterator(server.cluster->nodes);
A
antirez 已提交
4071
    while((de = dictNext(di)) != NULL) {
4072
        clusterNode *node = dictGetVal(de);
A
antirez 已提交
4073

4074
        if (node->flags & filter) continue;
4075 4076 4077
        ni = clusterGenNodeDescription(node);
        ci = sdscatsds(ci,ni);
        sdsfree(ni);
4078
        ci = sdscatlen(ci,"\n",1);
A
antirez 已提交
4079 4080 4081 4082 4083
    }
    dictReleaseIterator(di);
    return ci;
}

4084 4085 4086 4087
/* -----------------------------------------------------------------------------
 * CLUSTER command
 * -------------------------------------------------------------------------- */

4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098
const char *clusterGetMessageTypeString(int type) {
    switch(type) {
    case CLUSTERMSG_TYPE_PING: return "ping";
    case CLUSTERMSG_TYPE_PONG: return "pong";
    case CLUSTERMSG_TYPE_MEET: return "meet";
    case CLUSTERMSG_TYPE_FAIL: return "fail";
    case CLUSTERMSG_TYPE_PUBLISH: return "publish";
    case CLUSTERMSG_TYPE_FAILOVER_AUTH_REQUEST: return "auth-req";
    case CLUSTERMSG_TYPE_FAILOVER_AUTH_ACK: return "auth-ack";
    case CLUSTERMSG_TYPE_UPDATE: return "update";
    case CLUSTERMSG_TYPE_MFSTART: return "mfstart";
4099
    case CLUSTERMSG_TYPE_MODULE: return "module";
4100 4101 4102 4103
    }
    return "unknown";
}

4104
int getSlotOrReply(client *c, robj *o) {
4105 4106
    long long slot;

4107
    if (getLongLongFromObject(o,&slot) != C_OK ||
A
antirez 已提交
4108
        slot < 0 || slot >= CLUSTER_SLOTS)
4109 4110 4111 4112 4113 4114 4115
    {
        addReplyError(c,"Invalid or out of range slot");
        return -1;
    }
    return (int) slot;
}

4116
void clusterReplyMultiBulkSlots(client *c) {
4117 4118 4119 4120
    /* Format: 1) 1) start slot
     *            2) end slot
     *            3) 1) master IP
     *               2) master port
4121
     *               3) node ID
4122 4123
     *            4) 1) replica IP
     *               2) replica port
4124
     *               3) node ID
4125 4126 4127
     *           ... continued until done
     */

4128 4129
    int num_masters = 0;
    void *slot_replylen = addDeferredMultiBulkLength(c);
4130 4131 4132 4133 4134 4135 4136

    dictEntry *de;
    dictIterator *di = dictGetSafeIterator(server.cluster->nodes);
    while((de = dictNext(di)) != NULL) {
        clusterNode *node = dictGetVal(de);
        int j = 0, start = -1;

4137 4138 4139
        /* Skip slaves (that are iterated when producing the output of their
         * master) and  masters not serving any slot. */
        if (!nodeIsMaster(node) || node->numslots == 0) continue;
4140

A
antirez 已提交
4141
        for (j = 0; j < CLUSTER_SLOTS; j++) {
4142
            int bit, i;
4143 4144 4145 4146

            if ((bit = clusterNodeGetSlotBit(node,j)) != 0) {
                if (start == -1) start = j;
            }
A
antirez 已提交
4147
            if (start != -1 && (!bit || j == CLUSTER_SLOTS-1)) {
4148 4149
                int nested_elements = 3; /* slots (2) + master addr (1). */
                void *nested_replylen = addDeferredMultiBulkLength(c);
4150

A
antirez 已提交
4151
                if (bit && j == CLUSTER_SLOTS-1) j++;
4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164

                /* If slot exists in output map, add to it's list.
                 * else, create a new output map for this slot */
                if (start == j-1) {
                    addReplyLongLong(c, start); /* only one slot; low==high */
                    addReplyLongLong(c, start);
                } else {
                    addReplyLongLong(c, start); /* low */
                    addReplyLongLong(c, j-1);   /* high */
                }
                start = -1;

                /* First node reply position is always the master */
4165
                addReplyMultiBulkLen(c, 3);
4166 4167
                addReplyBulkCString(c, node->ip);
                addReplyLongLong(c, node->port);
4168
                addReplyBulkCBuffer(c, node->name, CLUSTER_NAMELEN);
4169 4170 4171 4172 4173

                /* Remaining nodes in reply are replicas for slot range */
                for (i = 0; i < node->numslaves; i++) {
                    /* This loop is copy/pasted from clusterGenNodeDescription()
                     * with modifications for per-slot node aggregation */
4174
                    if (nodeFailed(node->slaves[i])) continue;
4175
                    addReplyMultiBulkLen(c, 3);
4176 4177
                    addReplyBulkCString(c, node->slaves[i]->ip);
                    addReplyLongLong(c, node->slaves[i]->port);
4178
                    addReplyBulkCBuffer(c, node->slaves[i]->name, CLUSTER_NAMELEN);
4179
                    nested_elements++;
4180
                }
4181 4182
                setDeferredMultiBulkLength(c, nested_replylen, nested_elements);
                num_masters++;
4183 4184 4185 4186
            }
        }
    }
    dictReleaseIterator(di);
4187
    setDeferredMultiBulkLength(c, slot_replylen, num_masters);
4188 4189
}

4190
void clusterCommand(client *c) {
A
antirez 已提交
4191 4192 4193 4194 4195
    if (server.cluster_enabled == 0) {
        addReplyError(c,"This instance has cluster support disabled");
        return;
    }

I
Itamar Haber 已提交
4196 4197
    if (c->argc == 2 && !strcasecmp(c->argv[1]->ptr,"help")) {
        const char *help[] = {
4198 4199 4200 4201 4202
"ADDSLOTS <slot> [slot ...] -- Assign slots to current node.",
"BUMPEPOCH -- Advance the cluster config epoch.",
"COUNT-failure-reports <node-id> -- Return number of failure reports for <node-id>.",
"COUNTKEYSINSLOT <slot> - Return the number of keys in <slot>.",
"DELSLOTS <slot> [slot ...] -- Delete slots information from current node.",
4203
"FAILOVER [force|takeover] -- Promote current replica node to being a master.",
4204 4205 4206 4207 4208 4209 4210 4211
"FORGET <node-id> -- Remove a node from the cluster.",
"GETKEYSINSLOT <slot> <count> -- Return key names stored by current node in a slot.",
"FLUSHSLOTS -- Delete current node own slots information.",
"INFO - Return onformation about the cluster.",
"KEYSLOT <key> -- Return the hash slot for <key>.",
"MEET <ip> <port> [bus-port] -- Connect nodes into a working cluster.",
"MYID -- Return the node id.",
"NODES -- Return cluster configuration seen by node. Output format:",
4212
"    <id> <ip:port> <flags> <master> <pings> <pongs> <epoch> <link> <slot> ... <slot>",
4213
"REPLICATE <node-id> -- Configure current node as replica to <node-id>.",
4214 4215 4216
"RESET [hard|soft] -- Reset current node (default: soft).",
"SET-config-epoch <epoch> - Set config epoch of current node.",
"SETSLOT <slot> (importing|migrating|stable|node <node-id>) -- Set slot state.",
4217
"REPLICAS <node-id> -- Return <node-id> replicas.",
4218
"SLOTS -- Return information about slots range mappings. Each range is made of:",
4219 4220
"    start, end, master and replicas IP addresses, ports and ids",
NULL
I
Itamar Haber 已提交
4221 4222 4223
        };
        addReplyHelp(c, help);
    } else if (!strcasecmp(c->argv[1]->ptr,"meet") && (c->argc == 4 || c->argc == 5)) {
4224 4225
        /* CLUSTER MEET <ip> <port> [cport] */
        long long port, cport;
A
antirez 已提交
4226

4227
        if (getLongLongFromObject(c->argv[3], &port) != C_OK) {
4228
            addReplyErrorFormat(c,"Invalid TCP base port specified: %s",
4229
                                (char*)c->argv[3]->ptr);
A
antirez 已提交
4230 4231 4232
            return;
        }

4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243
        if (c->argc == 5) {
            if (getLongLongFromObject(c->argv[4], &cport) != C_OK) {
                addReplyErrorFormat(c,"Invalid TCP bus port specified: %s",
                                    (char*)c->argv[4]->ptr);
                return;
            }
        } else {
            cport = port + CLUSTER_PORT_INCR;
        }

        if (clusterStartHandshake(c->argv[2]->ptr,port,cport) == 0 &&
4244 4245
            errno == EINVAL)
        {
4246 4247
            addReplyErrorFormat(c,"Invalid node address specified: %s:%s",
                            (char*)c->argv[2]->ptr, (char*)c->argv[3]->ptr);
4248 4249 4250
        } else {
            addReply(c,shared.ok);
        }
A
antirez 已提交
4251
    } else if (!strcasecmp(c->argv[1]->ptr,"nodes") && c->argc == 2) {
4252
        /* CLUSTER NODES */
A
antirez 已提交
4253
        robj *o;
4254
        sds ci = clusterGenNodesDescription(0);
A
antirez 已提交
4255

4256
        o = createObject(OBJ_STRING,ci);
A
antirez 已提交
4257 4258
        addReplyBulk(c,o);
        decrRefCount(o);
M
Michel Martens 已提交
4259 4260
    } else if (!strcasecmp(c->argv[1]->ptr,"myid") && c->argc == 2) {
        /* CLUSTER MYID */
A
antirez 已提交
4261
        addReplyBulkCBuffer(c,myself->name, CLUSTER_NAMELEN);
4262 4263 4264
    } else if (!strcasecmp(c->argv[1]->ptr,"slots") && c->argc == 2) {
        /* CLUSTER SLOTS */
        clusterReplyMultiBulkSlots(c);
4265 4266 4267 4268 4269 4270
    } else if (!strcasecmp(c->argv[1]->ptr,"flushslots") && c->argc == 2) {
        /* CLUSTER FLUSHSLOTS */
        if (dictSize(server.db[0].dict) != 0) {
            addReplyError(c,"DB must be empty to perform CLUSTER FLUSHSLOTS.");
            return;
        }
4271
        clusterDelNodeSlots(myself);
A
antirez 已提交
4272
        clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
4273
        addReply(c,shared.ok);
A
antirez 已提交
4274
    } else if ((!strcasecmp(c->argv[1]->ptr,"addslots") ||
A
antirez 已提交
4275 4276 4277 4278
               !strcasecmp(c->argv[1]->ptr,"delslots")) && c->argc >= 3)
    {
        /* CLUSTER ADDSLOTS <slot> [slot] ... */
        /* CLUSTER DELSLOTS <slot> [slot] ... */
4279
        int j, slot;
A
antirez 已提交
4280
        unsigned char *slots = zmalloc(CLUSTER_SLOTS);
A
antirez 已提交
4281
        int del = !strcasecmp(c->argv[1]->ptr,"delslots");
A
antirez 已提交
4282

A
antirez 已提交
4283
        memset(slots,0,CLUSTER_SLOTS);
4284
        /* Check that all the arguments are parseable and that all the
A
antirez 已提交
4285 4286
         * slots are not already busy. */
        for (j = 2; j < c->argc; j++) {
4287
            if ((slot = getSlotOrReply(c,c->argv[j])) == -1) {
A
antirez 已提交
4288 4289 4290
                zfree(slots);
                return;
            }
4291
            if (del && server.cluster->slots[slot] == NULL) {
4292
                addReplyErrorFormat(c,"Slot %d is already unassigned", slot);
A
antirez 已提交
4293 4294
                zfree(slots);
                return;
4295
            } else if (!del && server.cluster->slots[slot]) {
4296
                addReplyErrorFormat(c,"Slot %d is already busy", slot);
A
antirez 已提交
4297 4298 4299 4300 4301 4302 4303 4304 4305 4306
                zfree(slots);
                return;
            }
            if (slots[slot]++ == 1) {
                addReplyErrorFormat(c,"Slot %d specified multiple times",
                    (int)slot);
                zfree(slots);
                return;
            }
        }
A
antirez 已提交
4307
        for (j = 0; j < CLUSTER_SLOTS; j++) {
A
antirez 已提交
4308
            if (slots[j]) {
4309 4310
                int retval;

4311
                /* If this slot was set as importing we can clear this
4312
                 * state as now we are the real owner of the slot. */
4313 4314
                if (server.cluster->importing_slots_from[j])
                    server.cluster->importing_slots_from[j] = NULL;
4315 4316

                retval = del ? clusterDelSlot(j) :
4317
                               clusterAddSlot(myself,j);
4318
                serverAssertWithInfo(c,NULL,retval == C_OK);
A
antirez 已提交
4319 4320 4321
            }
        }
        zfree(slots);
A
antirez 已提交
4322
        clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
A
antirez 已提交
4323
        addReply(c,shared.ok);
4324
    } else if (!strcasecmp(c->argv[1]->ptr,"setslot") && c->argc >= 4) {
A
antirez 已提交
4325 4326
        /* SETSLOT 10 MIGRATING <node ID> */
        /* SETSLOT 10 IMPORTING <node ID> */
4327
        /* SETSLOT 10 STABLE */
A
antirez 已提交
4328
        /* SETSLOT 10 NODE <node ID> */
4329
        int slot;
4330 4331
        clusterNode *n;

4332 4333 4334 4335 4336
        if (nodeIsSlave(myself)) {
            addReplyError(c,"Please use SETSLOT only with masters.");
            return;
        }

4337 4338
        if ((slot = getSlotOrReply(c,c->argv[2])) == -1) return;

4339
        if (!strcasecmp(c->argv[3]->ptr,"migrating") && c->argc == 5) {
4340
            if (server.cluster->slots[slot] != myself) {
4341 4342 4343
                addReplyErrorFormat(c,"I'm not the owner of hash slot %u",slot);
                return;
            }
4344 4345 4346 4347 4348
            if ((n = clusterLookupNode(c->argv[4]->ptr)) == NULL) {
                addReplyErrorFormat(c,"I don't know about node %s",
                    (char*)c->argv[4]->ptr);
                return;
            }
4349
            server.cluster->migrating_slots_to[slot] = n;
4350
        } else if (!strcasecmp(c->argv[3]->ptr,"importing") && c->argc == 5) {
4351
            if (server.cluster->slots[slot] == myself) {
4352 4353 4354 4355
                addReplyErrorFormat(c,
                    "I'm already the owner of hash slot %u",slot);
                return;
            }
4356 4357
            if ((n = clusterLookupNode(c->argv[4]->ptr)) == NULL) {
                addReplyErrorFormat(c,"I don't know about node %s",
L
Leon Chen 已提交
4358
                    (char*)c->argv[4]->ptr);
4359 4360
                return;
            }
4361
            server.cluster->importing_slots_from[slot] = n;
4362
        } else if (!strcasecmp(c->argv[3]->ptr,"stable") && c->argc == 4) {
4363
            /* CLUSTER SETSLOT <SLOT> STABLE */
4364 4365
            server.cluster->importing_slots_from[slot] = NULL;
            server.cluster->migrating_slots_to[slot] = NULL;
4366
        } else if (!strcasecmp(c->argv[3]->ptr,"node") && c->argc == 5) {
4367 4368 4369
            /* CLUSTER SETSLOT <SLOT> NODE <NODE ID> */
            clusterNode *n = clusterLookupNode(c->argv[4]->ptr);

4370 4371 4372 4373 4374
            if (!n) {
                addReplyErrorFormat(c,"Unknown node %s",
                    (char*)c->argv[4]->ptr);
                return;
            }
4375 4376
            /* If this hash slot was served by 'myself' before to switch
             * make sure there are no longer local keys for this hash slot. */
4377
            if (server.cluster->slots[slot] == myself && n != myself) {
4378
                if (countKeysInSlot(slot) != 0) {
A
antirez 已提交
4379 4380 4381
                    addReplyErrorFormat(c,
                        "Can't assign hashslot %d to a different node "
                        "while I still hold keys for this hash slot.", slot);
4382 4383 4384
                    return;
                }
            }
4385 4386
            /* If this slot is in migrating status but we have no keys
             * for it assigning the slot to another node will clear
4387
             * the migratig status. */
4388
            if (countKeysInSlot(slot) == 0 &&
4389 4390
                server.cluster->migrating_slots_to[slot])
                server.cluster->migrating_slots_to[slot] = NULL;
4391

4392 4393
            /* If this node was importing this slot, assigning the slot to
             * itself also clears the importing status. */
4394
            if (n == myself &&
4395
                server.cluster->importing_slots_from[slot])
4396 4397
            {
                /* This slot was manually migrated, set this node configEpoch
4398 4399 4400
                 * to a new epoch so that the new version can be propagated
                 * by the cluster.
                 *
4401 4402 4403 4404 4405
                 * Note that if this ever results in a collision with another
                 * node getting the same configEpoch, for example because a
                 * failover happens at the same time we close the slot, the
                 * configEpoch collision resolution will fix it assigning
                 * a different epoch to each node. */
4406
                if (clusterBumpConfigEpochWithoutConsensus() == C_OK) {
A
antirez 已提交
4407
                    serverLog(LL_WARNING,
4408
                        "configEpoch updated after importing slot %d", slot);
4409
                }
4410
                server.cluster->importing_slots_from[slot] = NULL;
4411
            }
4412 4413
            clusterDelSlot(slot);
            clusterAddSlot(n,slot);
4414
        } else {
A
antirez 已提交
4415
            addReplyError(c,
4416
                "Invalid CLUSTER SETSLOT action or number of arguments. Try CLUSTER HELP");
4417
            return;
4418
        }
4419
        clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|CLUSTER_TODO_UPDATE_STATE);
4420
        addReply(c,shared.ok);
4421 4422 4423 4424 4425 4426 4427
    } else if (!strcasecmp(c->argv[1]->ptr,"bumpepoch") && c->argc == 2) {
        /* CLUSTER BUMPEPOCH */
        int retval = clusterBumpConfigEpochWithoutConsensus();
        sds reply = sdscatprintf(sdsempty(),"+%s %llu\r\n",
                (retval == C_OK) ? "BUMPED" : "STILL",
                (unsigned long long) myself->configEpoch);
        addReplySds(c,reply);
A
antirez 已提交
4428
    } else if (!strcasecmp(c->argv[1]->ptr,"info") && c->argc == 2) {
4429
        /* CLUSTER INFO */
A
antirez 已提交
4430 4431
        char *statestr[] = {"ok","fail","needhelp"};
        int slots_assigned = 0, slots_ok = 0, slots_pfail = 0, slots_fail = 0;
4432
        uint64_t myepoch;
A
antirez 已提交
4433 4434
        int j;

A
antirez 已提交
4435
        for (j = 0; j < CLUSTER_SLOTS; j++) {
4436
            clusterNode *n = server.cluster->slots[j];
A
antirez 已提交
4437 4438 4439

            if (n == NULL) continue;
            slots_assigned++;
4440
            if (nodeFailed(n)) {
A
antirez 已提交
4441
                slots_fail++;
4442
            } else if (nodeTimedOut(n)) {
A
antirez 已提交
4443 4444 4445 4446 4447 4448
                slots_pfail++;
            } else {
                slots_ok++;
            }
        }

4449 4450 4451
        myepoch = (nodeIsSlave(myself) && myself->slaveof) ?
                  myself->slaveof->configEpoch : myself->configEpoch;

A
antirez 已提交
4452 4453 4454 4455 4456 4457
        sds info = sdscatprintf(sdsempty(),
            "cluster_state:%s\r\n"
            "cluster_slots_assigned:%d\r\n"
            "cluster_slots_ok:%d\r\n"
            "cluster_slots_pfail:%d\r\n"
            "cluster_slots_fail:%d\r\n"
4458
            "cluster_known_nodes:%lu\r\n"
4459
            "cluster_size:%d\r\n"
4460
            "cluster_current_epoch:%llu\r\n"
4461
            "cluster_my_epoch:%llu\r\n"
4462
            , statestr[server.cluster->state],
A
antirez 已提交
4463 4464 4465
            slots_assigned,
            slots_ok,
            slots_pfail,
4466
            slots_fail,
4467
            dictSize(server.cluster->nodes),
4468
            server.cluster->size,
4469
            (unsigned long long) server.cluster->currentEpoch,
4470
            (unsigned long long) myepoch
A
antirez 已提交
4471
        );
4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499

        /* Show stats about messages sent and received. */
        long long tot_msg_sent = 0;
        long long tot_msg_received = 0;

        for (int i = 0; i < CLUSTERMSG_TYPE_COUNT; i++) {
            if (server.cluster->stats_bus_messages_sent[i] == 0) continue;
            tot_msg_sent += server.cluster->stats_bus_messages_sent[i];
            info = sdscatprintf(info,
                "cluster_stats_messages_%s_sent:%lld\r\n",
                clusterGetMessageTypeString(i),
                server.cluster->stats_bus_messages_sent[i]);
        }
        info = sdscatprintf(info,
            "cluster_stats_messages_sent:%lld\r\n", tot_msg_sent);

        for (int i = 0; i < CLUSTERMSG_TYPE_COUNT; i++) {
            if (server.cluster->stats_bus_messages_received[i] == 0) continue;
            tot_msg_received += server.cluster->stats_bus_messages_received[i];
            info = sdscatprintf(info,
                "cluster_stats_messages_%s_received:%lld\r\n",
                clusterGetMessageTypeString(i),
                server.cluster->stats_bus_messages_received[i]);
        }
        info = sdscatprintf(info,
            "cluster_stats_messages_received:%lld\r\n", tot_msg_received);

        /* Produce the reply protocol. */
4500 4501 4502 4503
        addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
            (unsigned long)sdslen(info)));
        addReplySds(c,info);
        addReply(c,shared.crlf);
4504
    } else if (!strcasecmp(c->argv[1]->ptr,"saveconfig") && c->argc == 2) {
A
antirez 已提交
4505
        int retval = clusterSaveConfig(1);
4506 4507 4508 4509 4510 4511

        if (retval == 0)
            addReply(c,shared.ok);
        else
            addReplyErrorFormat(c,"error saving the cluster node config: %s",
                strerror(errno));
A
antirez 已提交
4512
    } else if (!strcasecmp(c->argv[1]->ptr,"keyslot") && c->argc == 3) {
4513
        /* CLUSTER KEYSLOT <key> */
A
antirez 已提交
4514 4515 4516
        sds key = c->argv[2]->ptr;

        addReplyLongLong(c,keyHashSlot(key,sdslen(key)));
4517
    } else if (!strcasecmp(c->argv[1]->ptr,"countkeysinslot") && c->argc == 3) {
4518
        /* CLUSTER COUNTKEYSINSLOT <slot> */
4519 4520
        long long slot;

4521
        if (getLongLongFromObjectOrReply(c,c->argv[2],&slot,NULL) != C_OK)
4522
            return;
A
antirez 已提交
4523
        if (slot < 0 || slot >= CLUSTER_SLOTS) {
4524 4525 4526
            addReplyError(c,"Invalid slot");
            return;
        }
4527
        addReplyLongLong(c,countKeysInSlot(slot));
A
antirez 已提交
4528
    } else if (!strcasecmp(c->argv[1]->ptr,"getkeysinslot") && c->argc == 4) {
4529
        /* CLUSTER GETKEYSINSLOT <slot> <count> */
A
antirez 已提交
4530
        long long maxkeys, slot;
4531
        unsigned int numkeys, j;
A
antirez 已提交
4532 4533
        robj **keys;

4534
        if (getLongLongFromObjectOrReply(c,c->argv[2],&slot,NULL) != C_OK)
A
antirez 已提交
4535
            return;
A
antirez 已提交
4536
        if (getLongLongFromObjectOrReply(c,c->argv[3],&maxkeys,NULL)
4537
            != C_OK)
A
antirez 已提交
4538
            return;
A
antirez 已提交
4539
        if (slot < 0 || slot >= CLUSTER_SLOTS || maxkeys < 0) {
A
antirez 已提交
4540 4541 4542 4543
            addReplyError(c,"Invalid slot or number of keys");
            return;
        }

4544 4545 4546 4547 4548
        /* Avoid allocating more than needed in case of large COUNT argument
         * and smaller actual number of keys. */
        unsigned int keys_in_slot = countKeysInSlot(slot);
        if (maxkeys > keys_in_slot) maxkeys = keys_in_slot;

A
antirez 已提交
4549
        keys = zmalloc(sizeof(robj*)*maxkeys);
4550
        numkeys = getKeysInSlot(slot, keys, maxkeys);
A
antirez 已提交
4551
        addReplyMultiBulkLen(c,numkeys);
4552 4553 4554 4555
        for (j = 0; j < numkeys; j++) {
            addReplyBulk(c,keys[j]);
            decrRefCount(keys[j]);
        }
A
antirez 已提交
4556
        zfree(keys);
A
antirez 已提交
4557 4558 4559 4560
    } else if (!strcasecmp(c->argv[1]->ptr,"forget") && c->argc == 3) {
        /* CLUSTER FORGET <NODE ID> */
        clusterNode *n = clusterLookupNode(c->argv[2]->ptr);

4561
        if (!n) {
A
antirez 已提交
4562 4563
            addReplyErrorFormat(c,"Unknown node %s", (char*)c->argv[2]->ptr);
            return;
4564
        } else if (n == myself) {
4565 4566
            addReplyError(c,"I tried hard but I can't forget myself...");
            return;
4567
        } else if (nodeIsSlave(myself) && myself->slaveof == n) {
4568 4569
            addReplyError(c,"Can't forget my master!");
            return;
A
antirez 已提交
4570
        }
4571
        clusterBlacklistAddNode(n);
A
antirez 已提交
4572
        clusterDelNode(n);
A
antirez 已提交
4573 4574
        clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|
                             CLUSTER_TODO_SAVE_CONFIG);
A
antirez 已提交
4575
        addReply(c,shared.ok);
4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586
    } else if (!strcasecmp(c->argv[1]->ptr,"replicate") && c->argc == 3) {
        /* CLUSTER REPLICATE <NODE ID> */
        clusterNode *n = clusterLookupNode(c->argv[2]->ptr);

        /* Lookup the specified node in our table. */
        if (!n) {
            addReplyErrorFormat(c,"Unknown node %s", (char*)c->argv[2]->ptr);
            return;
        }

        /* I can't replicate myself. */
4587
        if (n == myself) {
4588 4589 4590 4591 4592
            addReplyError(c,"Can't replicate myself");
            return;
        }

        /* Can't replicate a slave. */
4593
        if (nodeIsSlave(n)) {
4594
            addReplyError(c,"I can only replicate a master, not a replica.");
4595 4596 4597
            return;
        }

4598 4599 4600
        /* If the instance is currently a master, it should have no assigned
         * slots nor keys to accept to replicate some other node.
         * Slaves can switch to another master without issues. */
4601 4602
        if (nodeIsMaster(myself) &&
            (myself->numslots != 0 || dictSize(server.db[0].dict) != 0)) {
A
antirez 已提交
4603 4604 4605
            addReplyError(c,
                "To set a master the node must be empty and "
                "without assigned slots.");
4606 4607 4608 4609 4610
            return;
        }

        /* Set the master. */
        clusterSetMaster(n);
A
antirez 已提交
4611
        clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
4612
        addReply(c,shared.ok);
4613 4614
    } else if ((!strcasecmp(c->argv[1]->ptr,"slaves") ||
                !strcasecmp(c->argv[1]->ptr,"replicas")) && c->argc == 3) {
4615 4616 4617 4618 4619 4620 4621 4622 4623 4624
        /* CLUSTER SLAVES <NODE ID> */
        clusterNode *n = clusterLookupNode(c->argv[2]->ptr);
        int j;

        /* Lookup the specified node in our table. */
        if (!n) {
            addReplyErrorFormat(c,"Unknown node %s", (char*)c->argv[2]->ptr);
            return;
        }

4625
        if (nodeIsSlave(n)) {
4626 4627 4628 4629 4630 4631
            addReplyError(c,"The specified node is not a master");
            return;
        }

        addReplyMultiBulkLen(c,n->numslaves);
        for (j = 0; j < n->numslaves; j++) {
4632
            sds ni = clusterGenNodeDescription(n->slaves[j]);
4633 4634 4635
            addReplyBulkCString(c,ni);
            sdsfree(ni);
        }
4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647
    } else if (!strcasecmp(c->argv[1]->ptr,"count-failure-reports") &&
               c->argc == 3)
    {
        /* CLUSTER COUNT-FAILURE-REPORTS <NODE ID> */
        clusterNode *n = clusterLookupNode(c->argv[2]->ptr);

        if (!n) {
            addReplyErrorFormat(c,"Unknown node %s", (char*)c->argv[2]->ptr);
            return;
        } else {
            addReplyLongLong(c,clusterNodeFailureReportsCount(n));
        }
A
antirez 已提交
4648 4649 4650
    } else if (!strcasecmp(c->argv[1]->ptr,"failover") &&
               (c->argc == 2 || c->argc == 3))
    {
4651 4652
        /* CLUSTER FAILOVER [FORCE|TAKEOVER] */
        int force = 0, takeover = 0;
A
antirez 已提交
4653 4654 4655 4656

        if (c->argc == 3) {
            if (!strcasecmp(c->argv[2]->ptr,"force")) {
                force = 1;
4657 4658 4659
            } else if (!strcasecmp(c->argv[2]->ptr,"takeover")) {
                takeover = 1;
                force = 1; /* Takeover also implies force. */
A
antirez 已提交
4660 4661 4662 4663 4664 4665
            } else {
                addReply(c,shared.syntaxerr);
                return;
            }
        }

4666
        /* Check preconditions. */
4667
        if (nodeIsMaster(myself)) {
4668
            addReplyError(c,"You should send CLUSTER FAILOVER to a replica");
4669
            return;
4670
        } else if (myself->slaveof == NULL) {
4671
            addReplyError(c,"I'm a replica but my master is unknown to me");
4672
            return;
A
antirez 已提交
4673
        } else if (!force &&
4674 4675
                   (nodeFailed(myself->slaveof) ||
                    myself->slaveof->link == NULL))
4676 4677 4678 4679 4680 4681
        {
            addReplyError(c,"Master is down or failed, "
                            "please use CLUSTER FAILOVER FORCE");
            return;
        }
        resetManualFailover();
A
antirez 已提交
4682
        server.cluster->mf_end = mstime() + CLUSTER_MF_TIMEOUT;
A
antirez 已提交
4683

4684 4685 4686 4687 4688
        if (takeover) {
            /* A takeover does not perform any initial check. It just
             * generates a new configuration epoch for this node without
             * consensus, claims the master's slots, and broadcast the new
             * configuration. */
A
antirez 已提交
4689
            serverLog(LL_WARNING,"Taking over the master (user request).");
4690 4691 4692 4693 4694 4695
            clusterBumpConfigEpochWithoutConsensus();
            clusterFailoverReplaceYourMaster();
        } else if (force) {
            /* If this is a forced failover, we don't need to talk with our
             * master to agree about the offset. We just failover taking over
             * it without coordination. */
A
antirez 已提交
4696
            serverLog(LL_WARNING,"Forced failover user request accepted.");
A
antirez 已提交
4697 4698
            server.cluster->mf_can_start = 1;
        } else {
A
antirez 已提交
4699
            serverLog(LL_WARNING,"Manual failover user request accepted.");
A
antirez 已提交
4700 4701
            clusterSendMFStart(myself->slaveof);
        }
4702
        addReply(c,shared.ok);
A
antirez 已提交
4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713
    } else if (!strcasecmp(c->argv[1]->ptr,"set-config-epoch") && c->argc == 3)
    {
        /* CLUSTER SET-CONFIG-EPOCH <epoch>
         *
         * The user is allowed to set the config epoch only when a node is
         * totally fresh: no config epoch, no other known node, and so forth.
         * This happens at cluster creation time to start with a cluster where
         * every node has a different node ID, without to rely on the conflicts
         * resolution system which is too slow when a big cluster is created. */
        long long epoch;

4714
        if (getLongLongFromObjectOrReply(c,c->argv[2],&epoch,NULL) != C_OK)
A
antirez 已提交
4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725
            return;

        if (epoch < 0) {
            addReplyErrorFormat(c,"Invalid config epoch specified: %lld",epoch);
        } else if (dictSize(server.cluster->nodes) > 1) {
            addReplyError(c,"The user can assign a config epoch only when the "
                            "node does not know any other node.");
        } else if (myself->configEpoch != 0) {
            addReplyError(c,"Node config epoch is already non-zero");
        } else {
            myself->configEpoch = epoch;
A
antirez 已提交
4726
            serverLog(LL_WARNING,
4727 4728 4729
                "configEpoch set to %llu via CLUSTER SET-CONFIG-EPOCH",
                (unsigned long long) myself->configEpoch);

4730
            if (server.cluster->currentEpoch < (uint64_t)epoch)
4731
                server.cluster->currentEpoch = epoch;
A
antirez 已提交
4732 4733 4734 4735 4736 4737 4738
            /* No need to fsync the config here since in the unlucky event
             * of a failure to persist the config, the conflict resolution code
             * will assign an unique config to this node. */
            clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|
                                 CLUSTER_TODO_SAVE_CONFIG);
            addReply(c,shared.ok);
        }
A
antirez 已提交
4739 4740 4741 4742 4743 4744 4745 4746 4747 4748
    } else if (!strcasecmp(c->argv[1]->ptr,"reset") &&
               (c->argc == 2 || c->argc == 3))
    {
        /* CLUSTER RESET [SOFT|HARD] */
        int hard = 0;

        /* Parse soft/hard argument. Default is soft. */
        if (c->argc == 3) {
            if (!strcasecmp(c->argv[2]->ptr,"hard")) {
                hard = 1;
4749
            } else if (!strcasecmp(c->argv[2]->ptr,"soft")) {
A
antirez 已提交
4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765
                hard = 0;
            } else {
                addReply(c,shared.syntaxerr);
                return;
            }
        }

        /* Slaves can be reset while containing data, but not master nodes
         * that must be empty. */
        if (nodeIsMaster(myself) && dictSize(c->db->dict) != 0) {
            addReplyError(c,"CLUSTER RESET can't be called with "
                            "master nodes containing keys");
            return;
        }
        clusterReset(hard);
        addReply(c,shared.ok);
A
antirez 已提交
4766
    } else {
4767
        addReplySubcommandSyntaxError(c);
I
Itamar Haber 已提交
4768
        return;
A
antirez 已提交
4769 4770 4771 4772
    }
}

/* -----------------------------------------------------------------------------
4773
 * DUMP, RESTORE and MIGRATE commands
A
antirez 已提交
4774 4775
 * -------------------------------------------------------------------------- */

4776 4777 4778
/* Generates a DUMP-format representation of the object 'o', adding it to the
 * io stream pointed by 'rio'. This function can't fail. */
void createDumpPayload(rio *payload, robj *o) {
4779 4780
    unsigned char buf[2];
    uint64_t crc;
4781 4782 4783 4784

    /* Serialize the object in a RDB-like format. It consist of an object type
     * byte followed by the serialized object. This is understood by RESTORE. */
    rioInitWithBuffer(payload,sdsempty());
A
antirez 已提交
4785 4786
    serverAssert(rdbSaveObjectType(payload,o));
    serverAssert(rdbSaveObject(payload,o));
4787 4788

    /* Write the footer, this is how it looks like:
4789 4790 4791 4792 4793
     * ----------------+---------------------+---------------+
     * ... RDB payload | 2 bytes RDB version | 8 bytes CRC64 |
     * ----------------+---------------------+---------------+
     * RDB version and CRC are both in little endian.
     */
4794 4795

    /* RDB version */
A
antirez 已提交
4796 4797
    buf[0] = RDB_VERSION & 0xff;
    buf[1] = (RDB_VERSION >> 8) & 0xff;
4798 4799
    payload->io.buffer.ptr = sdscatlen(payload->io.buffer.ptr,buf,2);

4800
    /* CRC64 */
4801
    crc = crc64(0,(unsigned char*)payload->io.buffer.ptr,
4802 4803 4804
                sdslen(payload->io.buffer.ptr));
    memrev64ifbe(&crc);
    payload->io.buffer.ptr = sdscatlen(payload->io.buffer.ptr,&crc,8);
4805 4806 4807
}

/* Verify that the RDB version of the dump payload matches the one of this Redis
4808
 * instance and that the checksum is ok.
4809
 * If the DUMP payload looks valid C_OK is returned, otherwise C_ERR
4810 4811
 * is returned. */
int verifyDumpPayload(unsigned char *p, size_t len) {
4812
    unsigned char *footer;
4813
    uint16_t rdbver;
4814
    uint64_t crc;
4815

4816
    /* At least 2 bytes of RDB version and 8 of CRC64 should be present. */
4817
    if (len < 10) return C_ERR;
4818
    footer = p+(len-10);
4819 4820

    /* Verify RDB version */
4821
    rdbver = (footer[1] << 8) | footer[0];
4822
    if (rdbver > RDB_VERSION) return C_ERR;
4823

4824
    /* Verify CRC64 */
4825
    crc = crc64(0,p,len-8);
4826
    memrev64ifbe(&crc);
4827
    return (memcmp(&crc,footer+2,8) == 0) ? C_OK : C_ERR;
4828 4829 4830 4831 4832
}

/* DUMP keyname
 * DUMP is actually not used by Redis Cluster but it is the obvious
 * complement of RESTORE and can be useful for different applications. */
4833
void dumpCommand(client *c) {
4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846
    robj *o, *dumpobj;
    rio payload;

    /* Check if the key is here. */
    if ((o = lookupKeyRead(c->db,c->argv[1])) == NULL) {
        addReply(c,shared.nullbulk);
        return;
    }

    /* Create the DUMP encoded representation. */
    createDumpPayload(&payload,o);

    /* Transfer to the client */
4847
    dumpobj = createObject(OBJ_STRING,payload.io.buffer.ptr);
4848 4849 4850 4851 4852
    addReplyBulk(c,dumpobj);
    decrRefCount(dumpobj);
    return;
}

A
antirez 已提交
4853
/* RESTORE key ttl serialized-value [REPLACE] */
4854
void restoreCommand(client *c) {
4855
    long long ttl, lfu_freq = -1, lru_idle = -1, lru_clock = -1;
4856
    rio payload;
4857
    int j, type, replace = 0, absttl = 0;
4858
    robj *obj;
A
antirez 已提交
4859

A
antirez 已提交
4860 4861
    /* Parse additional options */
    for (j = 4; j < c->argc; j++) {
4862
        int additional = c->argc-j-1;
A
antirez 已提交
4863 4864
        if (!strcasecmp(c->argv[j]->ptr,"replace")) {
            replace = 1;
4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887
        } else if (!strcasecmp(c->argv[j]->ptr,"absttl")) {
            absttl = 1;
        } else if (!strcasecmp(c->argv[j]->ptr,"idletime") && additional >= 1 &&
                   lfu_freq == -1)
        {
            if (getLongLongFromObjectOrReply(c,c->argv[j+1],&lru_idle,NULL)
                    != C_OK) return;
            if (lru_idle < 0) {
                addReplyError(c,"Invalid IDLETIME value, must be >= 0");
                return;
            }
            lru_clock = LRU_CLOCK();
            j++; /* Consume additional arg. */
        } else if (!strcasecmp(c->argv[j]->ptr,"freq") && additional >= 1 &&
                   lru_idle == -1)
        {
            if (getLongLongFromObjectOrReply(c,c->argv[j+1],&lfu_freq,NULL)
                    != C_OK) return;
            if (lfu_freq < 0 || lfu_freq > 255) {
                addReplyError(c,"Invalid FREQ value, must be >= 0 and <= 255");
                return;
            }
            j++; /* Consume additional arg. */
A
antirez 已提交
4888 4889 4890 4891 4892 4893
        } else {
            addReply(c,shared.syntaxerr);
            return;
        }
    }

A
antirez 已提交
4894
    /* Make sure this key does not already exist here... */
A
antirez 已提交
4895
    if (!replace && lookupKeyWrite(c->db,c->argv[1]) != NULL) {
4896
        addReply(c,shared.busykeyerr);
A
antirez 已提交
4897 4898 4899 4900
        return;
    }

    /* Check if the TTL value makes sense */
4901
    if (getLongLongFromObjectOrReply(c,c->argv[2],&ttl,NULL) != C_OK) {
A
antirez 已提交
4902 4903 4904 4905 4906 4907
        return;
    } else if (ttl < 0) {
        addReplyError(c,"Invalid TTL value, must be >= 0");
        return;
    }

4908
    /* Verify RDB version and data checksum. */
4909
    if (verifyDumpPayload(c->argv[3]->ptr,sdslen(c->argv[3]->ptr)) == C_ERR)
4910
    {
4911 4912 4913 4914
        addReplyError(c,"DUMP payload version or checksum are wrong");
        return;
    }

4915
    rioInitWithBuffer(&payload,c->argv[3]->ptr);
4916 4917
    if (((type = rdbLoadObjectType(&payload)) == -1) ||
        ((obj = rdbLoadObject(type,&payload)) == NULL))
4918
    {
4919
        addReplyError(c,"Bad data format");
A
antirez 已提交
4920 4921 4922
        return;
    }

A
antirez 已提交
4923 4924 4925
    /* Remove the old key if needed. */
    if (replace) dbDelete(c->db,c->argv[1]);

A
antirez 已提交
4926
    /* Create the key and set the TTL if any */
4927
    dbAdd(c->db,c->argv[1],obj);
4928 4929 4930 4931 4932
    if (ttl) {
        if (!absttl) ttl+=mstime();
        setExpire(c,c->db,c->argv[1],ttl);
    }
    objectSetLRUOrLFU(obj,lfu_freq,lru_idle,lru_clock);
4933
    signalModifiedKey(c->db,c->argv[1]);
A
antirez 已提交
4934
    addReply(c,shared.ok);
4935
    server.dirty++;
A
antirez 已提交
4936 4937
}

A
antirez 已提交
4938 4939 4940 4941 4942 4943 4944
/* MIGRATE socket cache implementation.
 *
 * We take a map between host:ip and a TCP socket that we used to connect
 * to this instance in recent time.
 * This sockets are closed when the max number we cache is reached, and also
 * in serverCron() when they are around for more than a few seconds. */
#define MIGRATE_SOCKET_CACHE_ITEMS 64 /* max num of items in the cache. */
4945
#define MIGRATE_SOCKET_CACHE_TTL 10 /* close cached sockets after 10 sec. */
A
antirez 已提交
4946 4947 4948

typedef struct migrateCachedSocket {
    int fd;
4949
    long last_dbid;
A
antirez 已提交
4950 4951 4952
    time_t last_use_time;
} migrateCachedSocket;

4953 4954
/* Return a migrateCachedSocket containing a TCP socket connected with the
 * target instance, possibly returning a cached one.
A
antirez 已提交
4955 4956 4957 4958 4959 4960 4961
 *
 * This function is responsible of sending errors to the client if a
 * connection can't be established. In this case -1 is returned.
 * Otherwise on success the socket is returned, and the caller should not
 * attempt to free it after usage.
 *
 * If the caller detects an error while using the socket, migrateCloseSocket()
4962
 * should be called so that the connection will be created from scratch
A
antirez 已提交
4963
 * the next time. */
4964
migrateCachedSocket* migrateGetSocket(client *c, robj *host, robj *port, long timeout) {
A
antirez 已提交
4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976
    int fd;
    sds name = sdsempty();
    migrateCachedSocket *cs;

    /* Check if we have an already cached socket for this ip:port pair. */
    name = sdscatlen(name,host->ptr,sdslen(host->ptr));
    name = sdscatlen(name,":",1);
    name = sdscatlen(name,port->ptr,sdslen(port->ptr));
    cs = dictFetchValue(server.migrate_cached_sockets,name);
    if (cs) {
        sdsfree(name);
        cs->last_use_time = server.unixtime;
4977
        return cs;
A
antirez 已提交
4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990
    }

    /* No cached socket, create one. */
    if (dictSize(server.migrate_cached_sockets) == MIGRATE_SOCKET_CACHE_ITEMS) {
        /* Too many items, drop one at random. */
        dictEntry *de = dictGetRandomKey(server.migrate_cached_sockets);
        cs = dictGetVal(de);
        close(cs->fd);
        zfree(cs);
        dictDelete(server.migrate_cached_sockets,dictGetKey(de));
    }

    /* Create the socket */
4991 4992
    fd = anetTcpNonBlockConnect(server.neterr,c->argv[1]->ptr,
                                atoi(c->argv[2]->ptr));
A
antirez 已提交
4993 4994 4995 4996
    if (fd == -1) {
        sdsfree(name);
        addReplyErrorFormat(c,"Can't connect to target node: %s",
            server.neterr);
4997
        return NULL;
A
antirez 已提交
4998
    }
4999
    anetEnableTcpNoDelay(server.neterr,fd);
A
antirez 已提交
5000 5001

    /* Check if it connects within the specified timeout. */
5002
    if ((aeWait(fd,AE_WRITABLE,timeout) & AE_WRITABLE) == 0) {
A
antirez 已提交
5003
        sdsfree(name);
A
antirez 已提交
5004 5005
        addReplySds(c,
            sdsnew("-IOERR error or timeout connecting to the client\r\n"));
A
antirez 已提交
5006
        close(fd);
5007
        return NULL;
A
antirez 已提交
5008 5009 5010 5011 5012
    }

    /* Add to the cache and return it to the caller. */
    cs = zmalloc(sizeof(*cs));
    cs->fd = fd;
5013
    cs->last_dbid = -1;
A
antirez 已提交
5014 5015
    cs->last_use_time = server.unixtime;
    dictAdd(server.migrate_cached_sockets,name,cs);
5016
    return cs;
A
antirez 已提交
5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054
}

/* Free a migrate cached connection. */
void migrateCloseSocket(robj *host, robj *port) {
    sds name = sdsempty();
    migrateCachedSocket *cs;

    name = sdscatlen(name,host->ptr,sdslen(host->ptr));
    name = sdscatlen(name,":",1);
    name = sdscatlen(name,port->ptr,sdslen(port->ptr));
    cs = dictFetchValue(server.migrate_cached_sockets,name);
    if (!cs) {
        sdsfree(name);
        return;
    }

    close(cs->fd);
    zfree(cs);
    dictDelete(server.migrate_cached_sockets,name);
    sdsfree(name);
}

void migrateCloseTimedoutSockets(void) {
    dictIterator *di = dictGetSafeIterator(server.migrate_cached_sockets);
    dictEntry *de;

    while((de = dictNext(di)) != NULL) {
        migrateCachedSocket *cs = dictGetVal(de);

        if ((server.unixtime - cs->last_use_time) > MIGRATE_SOCKET_CACHE_TTL) {
            close(cs->fd);
            zfree(cs);
            dictDelete(server.migrate_cached_sockets,dictGetKey(de));
        }
    }
    dictReleaseIterator(di);
}

A
antirez 已提交
5055
/* MIGRATE host port key dbid timeout [COPY | REPLACE | AUTH password]
A
antirez 已提交
5056 5057 5058
 *
 * On in the multiple keys form:
 *
A
antirez 已提交
5059 5060
 * MIGRATE host port "" dbid timeout [COPY | REPLACE | AUTH password] KEYS key1
 * key2 ... keyN */
5061
void migrateCommand(client *c) {
5062
    migrateCachedSocket *cs;
A
antirez 已提交
5063 5064
    int copy = 0, replace = 0, j;
    char *password = NULL;
A
antirez 已提交
5065 5066
    long timeout;
    long dbid;
A
antirez 已提交
5067 5068 5069
    robj **ov = NULL; /* Objects to migrate. */
    robj **kv = NULL; /* Key names. */
    robj **newargv = NULL; /* Used to rewrite the command as DEL ... keys ... */
5070
    rio cmd, payload;
5071
    int may_retry = 1;
A
antirez 已提交
5072
    int write_error = 0;
5073
    int argv_rewritten = 0;
A
antirez 已提交
5074 5075 5076 5077

    /* To support the KEYS option we need the following additional state. */
    int first_key = 3; /* Argument index of the first key. */
    int num_keys = 1;  /* By default only migrate the 'key' argument. */
A
antirez 已提交
5078

A
antirez 已提交
5079 5080
    /* Parse additional options */
    for (j = 6; j < c->argc; j++) {
A
antirez 已提交
5081
        int moreargs = j < c->argc-1;
A
antirez 已提交
5082 5083 5084 5085
        if (!strcasecmp(c->argv[j]->ptr,"copy")) {
            copy = 1;
        } else if (!strcasecmp(c->argv[j]->ptr,"replace")) {
            replace = 1;
A
antirez 已提交
5086 5087 5088 5089 5090 5091 5092
        } else if (!strcasecmp(c->argv[j]->ptr,"auth")) {
            if (!moreargs) {
                addReply(c,shared.syntaxerr);
                return;
            }
            j++;
            password = c->argv[j]->ptr;
A
antirez 已提交
5093 5094 5095 5096 5097 5098 5099 5100 5101 5102
        } else if (!strcasecmp(c->argv[j]->ptr,"keys")) {
            if (sdslen(c->argv[3]->ptr) != 0) {
                addReplyError(c,
                    "When using MIGRATE KEYS option, the key argument"
                    " must be set to the empty string");
                return;
            }
            first_key = j+1;
            num_keys = c->argc - j - 1;
            break; /* All the remaining args are keys. */
A
antirez 已提交
5103 5104 5105 5106 5107 5108
        } else {
            addReply(c,shared.syntaxerr);
            return;
        }
    }

A
antirez 已提交
5109
    /* Sanity check */
5110 5111 5112
    if (getLongFromObjectOrReply(c,c->argv[5],&timeout,NULL) != C_OK ||
        getLongFromObjectOrReply(c,c->argv[4],&dbid,NULL) != C_OK)
    {
A
antirez 已提交
5113
        return;
5114
    }
5115
    if (timeout <= 0) timeout = 1000;
A
antirez 已提交
5116

A
antirez 已提交
5117 5118 5119 5120 5121
    /* Check if the keys are here. If at least one key is to migrate, do it
     * otherwise if all the keys are missing reply with "NOKEY" to signal
     * the caller there was nothing to migrate. We don't return an error in
     * this case, since often this is due to a normal condition like the key
     * expiring in the meantime. */
A
antirez 已提交
5122 5123
    ov = zrealloc(ov,sizeof(robj*)*num_keys);
    kv = zrealloc(kv,sizeof(robj*)*num_keys);
A
antirez 已提交
5124
    int oi = 0;
A
antirez 已提交
5125

A
antirez 已提交
5126 5127 5128 5129 5130 5131 5132 5133 5134
    for (j = 0; j < num_keys; j++) {
        if ((ov[oi] = lookupKeyRead(c->db,c->argv[first_key+j])) != NULL) {
            kv[oi] = c->argv[first_key+j];
            oi++;
        }
    }
    num_keys = oi;
    if (num_keys == 0) {
        zfree(ov); zfree(kv);
5135
        addReplySds(c,sdsnew("+NOKEY\r\n"));
A
antirez 已提交
5136 5137
        return;
    }
5138

A
antirez 已提交
5139 5140 5141
try_again:
    write_error = 0;

A
antirez 已提交
5142
    /* Connect */
5143
    cs = migrateGetSocket(c,c->argv[1],c->argv[2],timeout);
5144 5145 5146 5147
    if (cs == NULL) {
        zfree(ov); zfree(kv);
        return; /* error sent to the client by migrateGetSocket() */
    }
A
antirez 已提交
5148

5149
    rioInitWithBuffer(&cmd,sdsempty());
5150

A
antirez 已提交
5151 5152 5153 5154 5155 5156 5157 5158
    /* Authentication */
    if (password) {
        serverAssertWithInfo(c,NULL,rioWriteBulkCount(&cmd,'*',2));
        serverAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,"AUTH",4));
        serverAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,password,
            sdslen(password)));
    }

A
antirez 已提交
5159 5160 5161
    /* Send the SELECT command if the current DB is not already selected. */
    int select = cs->last_dbid != dbid; /* Should we emit SELECT? */
    if (select) {
A
antirez 已提交
5162 5163 5164
        serverAssertWithInfo(c,NULL,rioWriteBulkCount(&cmd,'*',2));
        serverAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,"SELECT",6));
        serverAssertWithInfo(c,NULL,rioWriteBulkLongLong(&cmd,dbid));
5165
    }
A
antirez 已提交
5166

5167 5168 5169 5170
    int non_expired = 0; /* Number of keys that we'll find non expired.
                            Note that serializing large keys may take some time
                            so certain keys that were found non expired by the
                            lookupKey() function, may be expired later. */
W
WuYunlong 已提交
5171

A
antirez 已提交
5172
    /* Create RESTORE payload and generate the protocol to call the command. */
A
antirez 已提交
5173
    for (j = 0; j < num_keys; j++) {
5174 5175 5176
        long long ttl = 0;
        long long expireat = getExpire(c->db,kv[j]);

A
antirez 已提交
5177 5178
        if (expireat != -1) {
            ttl = expireat-mstime();
5179 5180 5181
            if (ttl < 0) {
                continue;
            }
A
antirez 已提交
5182 5183
            if (ttl < 1) ttl = 1;
        }
5184 5185
        kv[non_expired++] = kv[j];

A
antirez 已提交
5186 5187 5188
        serverAssertWithInfo(c,NULL,
            rioWriteBulkCount(&cmd,'*',replace ? 5 : 4));

A
antirez 已提交
5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201
        if (server.cluster_enabled)
            serverAssertWithInfo(c,NULL,
                rioWriteBulkString(&cmd,"RESTORE-ASKING",14));
        else
            serverAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,"RESTORE",7));
        serverAssertWithInfo(c,NULL,sdsEncodedObject(kv[j]));
        serverAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,kv[j]->ptr,
                sdslen(kv[j]->ptr)));
        serverAssertWithInfo(c,NULL,rioWriteBulkLongLong(&cmd,ttl));

        /* Emit the payload argument, that is the serialized object using
         * the DUMP format. */
        createDumpPayload(&payload,ov[j]);
A
antirez 已提交
5202
        serverAssertWithInfo(c,NULL,
A
antirez 已提交
5203 5204 5205 5206 5207 5208 5209 5210 5211
            rioWriteBulkString(&cmd,payload.io.buffer.ptr,
                               sdslen(payload.io.buffer.ptr)));
        sdsfree(payload.io.buffer.ptr);

        /* Add the REPLACE option to the RESTORE command if it was specified
         * as a MIGRATE option. */
        if (replace)
            serverAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,"REPLACE",7));
    }
5212
    num_keys = non_expired;
A
antirez 已提交
5213

G
guiquanz 已提交
5214
    /* Transfer the query to the other node in 64K chunks. */
A
antirez 已提交
5215
    errno = 0;
A
antirez 已提交
5216
    {
5217 5218
        sds buf = cmd.io.buffer.ptr;
        size_t pos = 0, towrite;
5219
        int nwritten = 0;
5220 5221 5222

        while ((towrite = sdslen(buf)-pos) > 0) {
            towrite = (towrite > (64*1024) ? (64*1024) : towrite);
5223
            nwritten = syncWrite(cs->fd,buf+pos,towrite,timeout);
A
antirez 已提交
5224 5225 5226 5227
            if (nwritten != (signed)towrite) {
                write_error = 1;
                goto socket_err;
            }
5228
            pos += nwritten;
A
antirez 已提交
5229 5230 5231
        }
    }

A
antirez 已提交
5232
    char buf0[1024]; /* Auth reply. */
A
antirez 已提交
5233 5234
    char buf1[1024]; /* Select reply. */
    char buf2[1024]; /* Restore reply. */
A
antirez 已提交
5235

A
antirez 已提交
5236 5237 5238 5239
    /* Read the AUTH reply if needed. */
    if (password && syncReadLine(cs->fd, buf0, sizeof(buf0), timeout) <= 0)
        goto socket_err;

A
antirez 已提交
5240 5241 5242 5243 5244 5245
    /* Read the SELECT reply if needed. */
    if (select && syncReadLine(cs->fd, buf1, sizeof(buf1), timeout) <= 0)
        goto socket_err;

    /* Read the RESTORE replies. */
    int error_from_target = 0;
5246
    int socket_error = 0;
5247 5248
    int del_idx = 1; /* Index of the key argument for the replicated DEL op. */

5249 5250 5251 5252
    /* Allocate the new argument vector that will replace the current command,
     * to propagate the MIGRATE as a DEL command (if no COPY option was given).
     * We allocate num_keys+1 because the additional argument is for "DEL"
     * command name itself. */
5253
    if (!copy) newargv = zmalloc(sizeof(robj*)*(num_keys+1));
5254

5255
    for (j = 0; j < num_keys; j++) {
5256 5257 5258 5259
        if (syncReadLine(cs->fd, buf2, sizeof(buf2), timeout) <= 0) {
            socket_error = 1;
            break;
        }
5260 5261 5262 5263
        if ((password && buf0[0] == '-') ||
            (select && buf1[0] == '-') ||
            buf2[0] == '-')
        {
A
antirez 已提交
5264
            /* On error assume that last_dbid is no longer valid. */
5265 5266
            if (!error_from_target) {
                cs->last_dbid = -1;
A
antirez 已提交
5267
                char *errbuf;
5268
                if (password && buf0[0] == '-') errbuf = buf0;
A
antirez 已提交
5269 5270 5271
                else if (select && buf1[0] == '-') errbuf = buf1;
                else errbuf = buf2;

5272
                error_from_target = 1;
A
antirez 已提交
5273 5274
                addReplyErrorFormat(c,"Target instance replied with error: %s",
                    errbuf+1);
5275
            }
A
antirez 已提交
5276
        } else {
A
antirez 已提交
5277 5278
            if (!copy) {
                /* No COPY option: remove the local key, signal the change. */
A
antirez 已提交
5279 5280
                dbDelete(c->db,kv[j]);
                signalModifiedKey(c->db,kv[j]);
A
antirez 已提交
5281
                server.dirty++;
5282

5283 5284
                /* Populate the argument vector to replace the old one. */
                newargv[del_idx++] = kv[j];
5285
                incrRefCount(kv[j]);
5286
            }
A
antirez 已提交
5287 5288 5289
        }
    }

5290 5291 5292 5293 5294 5295 5296 5297 5298
    /* On socket error, if we want to retry, do it now before rewriting the
     * command vector. We only retry if we are sure nothing was processed
     * and we failed to read the first reply (j == 0 test). */
    if (!error_from_target && socket_error && j == 0 && may_retry &&
        errno != ETIMEDOUT)
    {
        goto socket_err; /* A retry is guaranteed because of tested conditions.*/
    }

5299 5300 5301 5302 5303
    /* On socket errors, close the migration socket now that we still have
     * the original host/port in the ARGV. Later the original command may be
     * rewritten to DEL and will be too later. */
    if (socket_error) migrateCloseSocket(c->argv[1],c->argv[2]);

5304
    if (!copy) {
5305 5306 5307
        /* Translate MIGRATE as DEL for replication/AOF. Note that we do
         * this only for the keys for which we received an acknowledgement
         * from the receiving Redis server, by using the del_idx index. */
5308 5309
        if (del_idx > 1) {
            newargv[0] = createStringObject("DEL",3);
5310
            /* Note that the following call takes ownership of newargv. */
5311
            replaceClientCommandVector(c,del_idx,newargv);
5312
            argv_rewritten = 1;
5313 5314 5315 5316
        } else {
            /* No key transfer acknowledged, no need to rewrite as DEL. */
            zfree(newargv);
        }
5317 5318 5319 5320
        newargv = NULL; /* Make it safe to call zfree() on it in the future. */
    }

    /* If we are here and a socket error happened, we don't want to retry.
5321 5322
     * Just signal the problem to the client, but only do it if we did not
     * already queue a different error reported by the destination server. */
5323 5324 5325
    if (!error_from_target && socket_error) {
        may_retry = 0;
        goto socket_err;
5326 5327
    }

A
antirez 已提交
5328
    if (!error_from_target) {
A
antirez 已提交
5329
        /* Success! Update the last_dbid in migrateCachedSocket, so that we can
5330 5331 5332 5333 5334
         * avoid SELECT the next time if the target DB is the same. Reply +OK.
         *
         * Note: If we reached this point, even if socket_error is true
         * still the SELECT command succeeded (otherwise the code jumps to
         * socket_err label. */
A
antirez 已提交
5335 5336 5337
        cs->last_dbid = dbid;
        addReply(c,shared.ok);
    } else {
5338
        /* On error we already sent it in the for loop above, and set
A
antirez 已提交
5339
         * the currently selected socket to -1 to force SELECT the next time. */
A
antirez 已提交
5340
    }
A
antirez 已提交
5341

5342
    sdsfree(cmd.io.buffer.ptr);
5343
    zfree(ov); zfree(kv); zfree(newargv);
5344
    return;
A
antirez 已提交
5345

A
antirez 已提交
5346 5347 5348 5349
/* On socket errors we try to close the cached socket and try again.
 * It is very common for the cached socket to get closed, if just reopening
 * it works it's a shame to notify the error to the caller. */
socket_err:
A
antirez 已提交
5350 5351
    /* Cleanup we want to perform in both the retry and no retry case.
     * Note: Closing the migrate socket will also force SELECT next time. */
5352
    sdsfree(cmd.io.buffer.ptr);
5353 5354 5355 5356 5357 5358

    /* If the command was rewritten as DEL and there was a socket error,
     * we already closed the socket earlier. While migrateCloseSocket()
     * is idempotent, the host/port arguments are now gone, so don't do it
     * again. */
    if (!argv_rewritten) migrateCloseSocket(c->argv[1],c->argv[2]);
A
antirez 已提交
5359 5360 5361 5362 5363
    zfree(newargv);
    newargv = NULL; /* This will get reallocated on retry. */

    /* Retry only if it's not a timeout and we never attempted a retry
     * (or the code jumping here did not set may_retry to zero). */
5364 5365 5366 5367
    if (errno != ETIMEDOUT && may_retry) {
        may_retry = 0;
        goto try_again;
    }
A
antirez 已提交
5368 5369 5370

    /* Cleanup we want to do if no retry is attempted. */
    zfree(ov); zfree(kv);
A
antirez 已提交
5371
    addReplySds(c,
A
antirez 已提交
5372 5373 5374
        sdscatprintf(sdsempty(),
            "-IOERR error or timeout %s to target instance\r\n",
            write_error ? "writing" : "reading"));
5375 5376 5377
    return;
}

5378 5379 5380 5381
/* -----------------------------------------------------------------------------
 * Cluster functions related to serving / redirecting clients
 * -------------------------------------------------------------------------- */

5382
/* The ASKING command is required after a -ASK redirection.
G
guiquanz 已提交
5383
 * The client should issue ASKING before to actually send the command to
5384 5385
 * the target instance. See the Redis Cluster specification for more
 * information. */
5386
void askingCommand(client *c) {
5387 5388 5389 5390
    if (server.cluster_enabled == 0) {
        addReplyError(c,"This instance has cluster support disabled");
        return;
    }
A
antirez 已提交
5391
    c->flags |= CLIENT_ASKING;
5392 5393 5394
    addReply(c,shared.ok);
}

5395
/* The READONLY command is used by clients to enter the read-only mode.
5396 5397
 * In this mode slaves will not redirect clients as long as clients access
 * with read-only commands to keys that are served by the slave's master. */
5398
void readonlyCommand(client *c) {
5399 5400 5401 5402
    if (server.cluster_enabled == 0) {
        addReplyError(c,"This instance has cluster support disabled");
        return;
    }
A
antirez 已提交
5403
    c->flags |= CLIENT_READONLY;
5404 5405 5406 5407
    addReply(c,shared.ok);
}

/* The READWRITE command just clears the READONLY command state. */
5408
void readwriteCommand(client *c) {
A
antirez 已提交
5409
    c->flags &= ~CLIENT_READONLY;
5410 5411
    addReply(c,shared.ok);
}
A
antirez 已提交
5412

5413
/* Return the pointer to the cluster node that is able to serve the command.
5414
 * For the function to succeed the command should only target either:
A
antirez 已提交
5415
 *
5416 5417 5418
 * 1) A single key (even multiple times like LPOPRPUSH mylist mylist).
 * 2) Multiple keys in the same hash slot, while the slot is stable (no
 *    resharding in progress).
5419
 *
5420 5421 5422
 * On success the function returns the node that is able to serve the request.
 * If the node is not 'myself' a redirection must be perfomed. The kind of
 * redirection is specified setting the integer passed by reference
A
antirez 已提交
5423 5424
 * 'error_code', which will be set to CLUSTER_REDIR_ASK or
 * CLUSTER_REDIR_MOVED.
5425
 *
A
antirez 已提交
5426
 * When the node is 'myself' 'error_code' is set to CLUSTER_REDIR_NONE.
5427 5428 5429 5430
 *
 * If the command fails NULL is returned, and the reason of the failure is
 * provided via 'error_code', which will be set to:
 *
A
antirez 已提交
5431
 * CLUSTER_REDIR_CROSS_SLOT if the request contains multiple keys that
5432 5433
 * don't belong to the same hash slot.
 *
A
antirez 已提交
5434
 * CLUSTER_REDIR_UNSTABLE if the request contains multiple keys
5435
 * belonging to the same slot, but the slot is not stable (in migration or
5436 5437
 * importing state, likely because a resharding is in progress).
 *
A
antirez 已提交
5438
 * CLUSTER_REDIR_DOWN_UNBOUND if the request addresses a slot which is
5439 5440
 * not bound to any node. In this case the cluster global state should be
 * already "down" but it is fragile to rely on the update of the global state,
5441 5442 5443 5444
 * so we also handle it here.
 *
 * CLUSTER_REDIR_DOWN_STATE if the cluster is down but the user attempts to
 * execute a command that addresses one or more keys. */
5445
clusterNode *getNodeByQuery(client *c, struct redisCommand *cmd, robj **argv, int argc, int *hashslot, int *error_code) {
A
antirez 已提交
5446
    clusterNode *n = NULL;
5447
    robj *firstkey = NULL;
5448
    int multiple_keys = 0;
A
antirez 已提交
5449 5450
    multiState *ms, _ms;
    multiCmd mc;
5451 5452
    int i, slot = 0, migrating_slot = 0, importing_slot = 0, missing_keys = 0;

5453 5454 5455 5456
    /* Allow any key to be set if a module disabled cluster redirections. */
    if (server.cluster_module_flags & CLUSTER_MODULE_FLAG_NO_REDIRECTION)
        return myself;

5457
    /* Set error code optimistically for the base case. */
A
antirez 已提交
5458
    if (error_code) *error_code = CLUSTER_REDIR_NONE;
A
antirez 已提交
5459

5460 5461 5462 5463
    /* Modules can turn off Redis Cluster redirection: this is useful
     * when writing a module that implements a completely different
     * distributed system. */

A
antirez 已提交
5464 5465 5466
    /* We handle all the cases as if they were EXEC commands, so we have
     * a common code path for everything */
    if (cmd->proc == execCommand) {
A
antirez 已提交
5467
        /* If CLIENT_MULTI flag is not set EXEC is just going to return an
A
antirez 已提交
5468
         * error. */
A
antirez 已提交
5469
        if (!(c->flags & CLIENT_MULTI)) return myself;
A
antirez 已提交
5470 5471
        ms = &c->mstate;
    } else {
5472 5473 5474
        /* In order to have a single codepath create a fake Multi State
         * structure if the client is not in MULTI/EXEC state, this way
         * we have a single codepath below. */
A
antirez 已提交
5475 5476 5477 5478 5479 5480 5481 5482
        ms = &_ms;
        _ms.commands = &mc;
        _ms.count = 1;
        mc.argv = argv;
        mc.argc = argc;
        mc.cmd = cmd;
    }

5483 5484
    /* Check that all the keys are in the same hash slot, and obtain this
     * slot and the node associated. */
A
antirez 已提交
5485 5486 5487 5488 5489 5490 5491 5492 5493
    for (i = 0; i < ms->count; i++) {
        struct redisCommand *mcmd;
        robj **margv;
        int margc, *keyindex, numkeys, j;

        mcmd = ms->commands[i].cmd;
        margc = ms->commands[i].argc;
        margv = ms->commands[i].argv;

5494
        keyindex = getKeysFromCommand(mcmd,margv,margc,&numkeys);
A
antirez 已提交
5495
        for (j = 0; j < numkeys; j++) {
5496 5497 5498 5499
            robj *thiskey = margv[keyindex[j]];
            int thisslot = keyHashSlot((char*)thiskey->ptr,
                                       sdslen(thiskey->ptr));

5500 5501 5502
            if (firstkey == NULL) {
                /* This is the first key we see. Check what is the slot
                 * and node. */
5503 5504
                firstkey = thiskey;
                slot = thisslot;
5505
                n = server.cluster->slots[slot];
5506 5507 5508 5509 5510 5511 5512 5513

                /* Error: If a slot is not served, we are in "cluster down"
                 * state. However the state is yet to be updated, so this was
                 * not trapped earlier in processCommand(). Report the same
                 * error to the client. */
                if (n == NULL) {
                    getKeysFreeResult(keyindex);
                    if (error_code)
A
antirez 已提交
5514
                        *error_code = CLUSTER_REDIR_DOWN_UNBOUND;
5515 5516 5517
                    return NULL;
                }

5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529
                /* If we are migrating or importing this slot, we need to check
                 * if we have all the keys in the request (the only way we
                 * can safely serve the request, otherwise we return a TRYAGAIN
                 * error). To do so we set the importing/migrating state and
                 * increment a counter for every missing key. */
                if (n == myself &&
                    server.cluster->migrating_slots_to[slot] != NULL)
                {
                    migrating_slot = 1;
                } else if (server.cluster->importing_slots_from[slot] != NULL) {
                    importing_slot = 1;
                }
A
antirez 已提交
5530
            } else {
5531 5532
                /* If it is not the first key, make sure it is exactly
                 * the same key as the first we saw. */
5533 5534 5535 5536 5537
                if (!equalStringObjects(firstkey,thiskey)) {
                    if (slot != thisslot) {
                        /* Error: multiple keys from different slots. */
                        getKeysFreeResult(keyindex);
                        if (error_code)
A
antirez 已提交
5538
                            *error_code = CLUSTER_REDIR_CROSS_SLOT;
5539 5540 5541 5542 5543 5544
                        return NULL;
                    } else {
                        /* Flag this request as one with multiple different
                         * keys. */
                        multiple_keys = 1;
                    }
5545
                }
A
antirez 已提交
5546
            }
5547 5548 5549 5550 5551 5552 5553

            /* Migarting / Improrting slot? Count keys we don't have. */
            if ((migrating_slot || importing_slot) &&
                lookupKeyRead(&server.db[0],thiskey) == NULL)
            {
                missing_keys++;
            }
A
antirez 已提交
5554 5555 5556
        }
        getKeysFreeResult(keyindex);
    }
5557

5558
    /* No key at all in command? then we can serve the request
5559
     * without redirections or errors in all the cases. */
5560
    if (n == NULL) return myself;
5561

5562 5563 5564 5565 5566 5567
    /* Cluster is globally down but we got keys? We can't serve the request. */
    if (server.cluster->state != CLUSTER_OK) {
        if (error_code) *error_code = CLUSTER_REDIR_DOWN_STATE;
        return NULL;
    }

5568
    /* Return the hashslot by reference. */
5569
    if (hashslot) *hashslot = slot;
5570

5571 5572 5573 5574 5575
    /* MIGRATE always works in the context of the local node if the slot
     * is open (migrating or importing state). We need to be able to freely
     * move keys among instances in this case. */
    if ((migrating_slot || importing_slot) && cmd->proc == migrateCommand)
        return myself;
5576 5577

    /* If we don't have all the keys and we are migrating the slot, send
5578 5579
     * an ASK redirection. */
    if (migrating_slot && missing_keys) {
A
antirez 已提交
5580
        if (error_code) *error_code = CLUSTER_REDIR_ASK;
5581 5582 5583
        return server.cluster->migrating_slots_to[slot];
    }

5584 5585 5586 5587
    /* If we are receiving the slot, and the client correctly flagged the
     * request as "ASKING", we can serve the request. However if the request
     * involves multiple keys and we don't have them all, the only option is
     * to send a TRYAGAIN error. */
5588
    if (importing_slot &&
A
antirez 已提交
5589
        (c->flags & CLIENT_ASKING || cmd->flags & CMD_ASKING))
5590
    {
5591
        if (multiple_keys && missing_keys) {
A
antirez 已提交
5592
            if (error_code) *error_code = CLUSTER_REDIR_UNSTABLE;
5593 5594 5595 5596
            return NULL;
        } else {
            return myself;
        }
5597
    }
5598

5599 5600 5601
    /* Handle the read-only client case reading from a slave: if this
     * node is a slave and the request is about an hash slot our master
     * is serving, we can reply without redirection. */
A
antirez 已提交
5602
    if (c->flags & CLIENT_READONLY &&
5603 5604
        (cmd->flags & CMD_READONLY || cmd->proc == evalCommand ||
         cmd->proc == evalShaCommand) &&
5605
        nodeIsSlave(myself) &&
5606
        myself->slaveof == n)
5607
    {
5608
        return myself;
5609
    }
5610 5611 5612

    /* Base case: just return the right node. However if this node is not
     * myself, set error_code to MOVED since we need to issue a rediretion. */
A
antirez 已提交
5613
    if (n != myself && error_code) *error_code = CLUSTER_REDIR_MOVED;
5614
    return n;
A
antirez 已提交
5615
}
5616 5617

/* Send the client the right redirection code, according to error_code
A
antirez 已提交
5618
 * that should be set to one of CLUSTER_REDIR_* macros.
5619
 *
A
antirez 已提交
5620
 * If CLUSTER_REDIR_ASK or CLUSTER_REDIR_MOVED error codes
5621 5622 5623
 * are used, then the node 'n' should not be NULL, but should be the
 * node we want to mention in the redirection. Moreover hashslot should
 * be set to the hash slot that caused the redirection. */
5624
void clusterRedirectClient(client *c, clusterNode *n, int hashslot, int error_code) {
A
antirez 已提交
5625
    if (error_code == CLUSTER_REDIR_CROSS_SLOT) {
5626
        addReplySds(c,sdsnew("-CROSSSLOT Keys in request don't hash to the same slot\r\n"));
A
antirez 已提交
5627
    } else if (error_code == CLUSTER_REDIR_UNSTABLE) {
J
Jack Drogon 已提交
5628
        /* The request spawns multiple keys in the same slot,
5629 5630 5631
         * but the slot is not "stable" currently as there is
         * a migration or import in progress. */
        addReplySds(c,sdsnew("-TRYAGAIN Multiple keys request during rehashing of slot\r\n"));
A
antirez 已提交
5632
    } else if (error_code == CLUSTER_REDIR_DOWN_STATE) {
5633
        addReplySds(c,sdsnew("-CLUSTERDOWN The cluster is down\r\n"));
A
antirez 已提交
5634
    } else if (error_code == CLUSTER_REDIR_DOWN_UNBOUND) {
5635
        addReplySds(c,sdsnew("-CLUSTERDOWN Hash slot not served\r\n"));
A
antirez 已提交
5636 5637
    } else if (error_code == CLUSTER_REDIR_MOVED ||
               error_code == CLUSTER_REDIR_ASK)
5638 5639 5640
    {
        addReplySds(c,sdscatprintf(sdsempty(),
            "-%s %d %s:%d\r\n",
A
antirez 已提交
5641
            (error_code == CLUSTER_REDIR_ASK) ? "ASK" : "MOVED",
5642 5643
            hashslot,n->ip,n->port));
    } else {
A
antirez 已提交
5644
        serverPanic("getNodeByQuery() unknown error.");
5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658
    }
}

/* This function is called by the function processing clients incrementally
 * to detect timeouts, in order to handle the following case:
 *
 * 1) A client blocks with BLPOP or similar blocking operation.
 * 2) The master migrates the hash slot elsewhere or turns into a slave.
 * 3) The client may remain blocked forever (or up to the max timeout time)
 *    waiting for a key change that will never happen.
 *
 * If the client is found to be blocked into an hash slot this node no
 * longer handles, the client is sent a redirection error, and the function
 * returns 1. Otherwise 0 is returned and no operation is performed. */
5659
int clusterRedirectBlockedClientIfNeeded(client *c) {
5660 5661 5662 5663 5664
    if (c->flags & CLIENT_BLOCKED &&
        (c->btype == BLOCKED_LIST ||
         c->btype == BLOCKED_ZSET ||
         c->btype == BLOCKED_STREAM))
    {
5665 5666 5667 5668
        dictEntry *de;
        dictIterator *di;

        /* If the cluster is down, unblock the client with the right error. */
A
antirez 已提交
5669 5670
        if (server.cluster->state == CLUSTER_FAIL) {
            clusterRedirectClient(c,NULL,0,CLUSTER_REDIR_DOWN_STATE);
5671 5672 5673
            return 1;
        }

5674
        /* All keys must belong to the same slot, so check first key only. */
5675
        di = dictGetIterator(c->bpop.keys);
5676
        if ((de = dictNext(di)) != NULL) {
5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688
            robj *key = dictGetKey(de);
            int slot = keyHashSlot((char*)key->ptr, sdslen(key->ptr));
            clusterNode *node = server.cluster->slots[slot];

            /* We send an error and unblock the client if:
             * 1) The slot is unassigned, emitting a cluster down error.
             * 2) The slot is not handled by this node, nor being imported. */
            if (node != myself &&
                server.cluster->importing_slots_from[slot] == NULL)
            {
                if (node == NULL) {
                    clusterRedirectClient(c,NULL,0,
A
antirez 已提交
5689
                        CLUSTER_REDIR_DOWN_UNBOUND);
5690 5691
                } else {
                    clusterRedirectClient(c,node,slot,
A
antirez 已提交
5692
                        CLUSTER_REDIR_MOVED);
5693
                }
5694
                dictReleaseIterator(di);
5695 5696 5697 5698 5699 5700 5701
                return 1;
            }
        }
        dictReleaseIterator(di);
    }
    return 0;
}