cluster.c 221.5 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 1233
                node->name,
                nodeIsSlave(node) ? "slave" : "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 1592 1593 1594 1595 1596 1597 1598 1599
                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);
            }
        }
    }

    /* 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 已提交
1600
        serverLog(LL_WARNING,
A
antirez 已提交
1601 1602
            "Configuration change detected. Reconfiguring myself "
            "as a replica of %.40s", sender->name);
1603 1604 1605 1606
        clusterSetMaster(sender);
        clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                             CLUSTER_TODO_UPDATE_STATE|
                             CLUSTER_TODO_FSYNC_CONFIG);
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
    } 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]);
1617 1618 1619
    }
}

A
antirez 已提交
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
/* 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);

1634 1635
    if (type < CLUSTERMSG_TYPE_COUNT)
        server.cluster->stats_bus_messages_received[type]++;
A
antirez 已提交
1636
    serverLog(LL_DEBUG,"--- Processing packet of type %d, %lu bytes",
1637
        type, (unsigned long) totlen);
1638 1639

    /* Perform sanity checks */
1640
    if (totlen < 16) return 1; /* At least signature, version, totlen, count. */
A
antirez 已提交
1641
    if (totlen > sdslen(link->rcvbuf)) return 1;
1642 1643 1644 1645 1646 1647 1648 1649 1650 1651

    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 已提交
1652 1653 1654 1655 1656 1657 1658 1659 1660
    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;
1661
    } else if (type == CLUSTERMSG_TYPE_FAIL) {
A
antirez 已提交
1662 1663 1664 1665
        uint32_t explen = sizeof(clusterMsg)-sizeof(union clusterMsgData);

        explen += sizeof(clusterMsgDataFail);
        if (totlen != explen) return 1;
1666
    } else if (type == CLUSTERMSG_TYPE_PUBLISH) {
1667 1668
        uint32_t explen = sizeof(clusterMsg)-sizeof(union clusterMsgData);

1669 1670
        explen += sizeof(clusterMsgDataPublish) -
                8 +
1671 1672 1673
                ntohl(hdr->data.publish.msg.channel_len) +
                ntohl(hdr->data.publish.msg.message_len);
        if (totlen != explen) return 1;
1674
    } else if (type == CLUSTERMSG_TYPE_FAILOVER_AUTH_REQUEST ||
1675 1676 1677
               type == CLUSTERMSG_TYPE_FAILOVER_AUTH_ACK ||
               type == CLUSTERMSG_TYPE_MFSTART)
    {
1678 1679
        uint32_t explen = sizeof(clusterMsg)-sizeof(union clusterMsgData);

1680 1681 1682 1683 1684
        if (totlen != explen) return 1;
    } else if (type == CLUSTERMSG_TYPE_UPDATE) {
        uint32_t explen = sizeof(clusterMsg)-sizeof(union clusterMsgData);

        explen += sizeof(clusterMsgDataUpdate);
1685
        if (totlen != explen) return 1;
1686 1687 1688 1689 1690 1691
    } 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;
1692
    }
A
antirez 已提交
1693

1694
    /* Check if the sender is a known node. */
A
antirez 已提交
1695
    sender = clusterLookupNode(hdr->sender);
1696
    if (sender && !nodeInHandshake(sender)) {
1697
        /* Update our curretEpoch if we see a newer epoch in the cluster. */
1698 1699 1700 1701
        senderCurrentEpoch = ntohu64(hdr->currentEpoch);
        senderConfigEpoch = ntohu64(hdr->configEpoch);
        if (senderCurrentEpoch > server.cluster->currentEpoch)
            server.cluster->currentEpoch = senderCurrentEpoch;
1702
        /* Update the sender configEpoch if it is publishing a newer one. */
1703
        if (senderConfigEpoch > sender->configEpoch) {
1704
            sender->configEpoch = senderConfigEpoch;
A
antirez 已提交
1705 1706
            clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                                 CLUSTER_TODO_FSYNC_CONFIG);
1707
        }
1708 1709 1710
        /* Update the replication offset info for this node. */
        sender->repl_offset = ntohu64(hdr->offset);
        sender->repl_offset_time = mstime();
1711 1712 1713 1714 1715 1716 1717 1718 1719
        /* 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 已提交
1720
            serverLog(LL_WARNING,
A
antirez 已提交
1721 1722 1723
                "Received replication offset for paused "
                "master manual failover: %lld",
                server.cluster->mf_master_offset);
1724
        }
1725
    }
1726

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

A
antirez 已提交
1731 1732
        /* We use incoming MEET messages in order to set the address
         * for 'myself', since only other cluster nodes will send us
1733
         * MEET messages on handshakes, when the cluster joins, or
A
antirez 已提交
1734 1735 1736
         * 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
1737 1738 1739 1740 1741
         * 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. */
1742 1743 1744
        if ((type == CLUSTERMSG_TYPE_MEET || myself->ip[0] == '\0') &&
            server.cluster_announce_ip == NULL)
        {
A
antirez 已提交
1745
            char ip[NET_IP_STR_LEN];
A
antirez 已提交
1746 1747 1748 1749

            if (anetSockName(link->fd,ip,sizeof(ip),NULL) != -1 &&
                strcmp(ip,myself->ip))
            {
A
antirez 已提交
1750 1751
                memcpy(myself->ip,ip,NET_IP_STR_LEN);
                serverLog(LL_WARNING,"IP address for this node updated to %s",
1752
                    myself->ip);
A
antirez 已提交
1753 1754 1755 1756
                clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG);
            }
        }

A
antirez 已提交
1757 1758 1759
        /* 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
1760
         * resolved when we'll receive PONGs from the node. */
A
antirez 已提交
1761 1762 1763
        if (!sender && type == CLUSTERMSG_TYPE_MEET) {
            clusterNode *node;

A
antirez 已提交
1764
            node = createClusterNode(NULL,CLUSTER_NODE_HANDSHAKE);
1765
            nodeIp2String(node->ip,link,hdr->myip);
A
antirez 已提交
1766
            node->port = ntohs(hdr->port);
1767
            node->cport = ntohs(hdr->cport);
A
antirez 已提交
1768
            clusterAddNode(node);
A
antirez 已提交
1769
            clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG);
A
antirez 已提交
1770 1771
        }

1772 1773 1774 1775 1776
        /* 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 已提交
1777 1778 1779

        /* Anyway reply with a PONG */
        clusterSendPing(link,CLUSTERMSG_TYPE_PONG);
1780 1781
    }

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

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

1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
        /* 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 已提交
1848 1849
        /* Update the node address if it changed. */
        if (sender && type == CLUSTERMSG_TYPE_PING &&
1850
            !nodeInHandshake(sender) &&
1851
            nodeUpdateAddressIfNeeded(sender,link,hdr))
A
antirez 已提交
1852
        {
A
antirez 已提交
1853 1854
            clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                                 CLUSTER_TODO_UPDATE_STATE);
A
antirez 已提交
1855 1856
        }

A
antirez 已提交
1857
        /* Update our info about the node */
1858
        if (link->node && type == CLUSTERMSG_TYPE_PONG) {
1859
            link->node->pong_received = mstime();
1860 1861 1862
            link->node->ping_sent = 0;

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

1877
        /* Check for role switch: slave -> master or master -> slave. */
A
antirez 已提交
1878
        if (sender) {
A
antirez 已提交
1879
            if (!memcmp(hdr->slaveof,CLUSTER_NODE_NULL_NAME,
A
antirez 已提交
1880 1881
                sizeof(hdr->slaveof)))
            {
1882
                /* Node is a master. */
1883
                clusterSetNodeAsMaster(sender);
A
antirez 已提交
1884
            } else {
1885
                /* Node is a slave. */
A
antirez 已提交
1886 1887
                clusterNode *master = clusterLookupNode(hdr->slaveof);

1888
                if (nodeIsMaster(sender)) {
1889
                    /* Master turned into a slave! Reconfigure the node. */
1890
                    clusterDelNodeSlots(sender);
1891 1892
                    sender->flags &= ~(CLUSTER_NODE_MASTER|
                                       CLUSTER_NODE_MIGRATE_TO);
A
antirez 已提交
1893
                    sender->flags |= CLUSTER_NODE_SLAVE;
1894 1895

                    /* Update config and state. */
A
antirez 已提交
1896 1897
                    clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                                         CLUSTER_TODO_UPDATE_STATE);
1898 1899
                }

1900
                /* Master node changed for this slave? */
1901
                if (master && sender->slaveof != master) {
1902 1903
                    if (sender->slaveof)
                        clusterNodeRemoveSlave(sender->slaveof,sender);
1904 1905
                    clusterNodeAddSlave(master,sender);
                    sender->slaveof = master;
1906 1907

                    /* Update config. */
A
antirez 已提交
1908
                    clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG);
1909
                }
A
antirez 已提交
1910 1911 1912
            }
        }

1913
        /* Update our info about served slots.
1914
         *
1915
         * Note: this MUST happen after we update the master/slave state
A
antirez 已提交
1916
         * so that CLUSTER_NODE_MASTER flag will be set. */
1917 1918

        /* Many checks are only needed if the set of served slots this
1919 1920 1921 1922
         * 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. */
1923 1924 1925
        int dirty_slots = 0; /* Sender claimed slots don't match my view? */

        if (sender) {
1926
            sender_master = nodeIsMaster(sender) ? sender : sender->slaveof;
1927 1928 1929 1930 1931 1932
            if (sender_master) {
                dirty_slots = memcmp(sender_master->slots,
                        hdr->myslots,sizeof(hdr->myslots)) != 0;
            }
        }

1933 1934 1935
        /* 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. */
1936
        if (sender && nodeIsMaster(sender) && dirty_slots)
1937
            clusterUpdateSlotsConfigWith(sender,senderConfigEpoch,hdr->myslots);
1938

1939 1940 1941
        /* 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.
1942
         *
1943 1944 1945 1946
         * 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:
1947 1948 1949 1950 1951 1952
         *
         * 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
1953 1954 1955 1956
         * 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). */
1957 1958 1959
        if (sender && dirty_slots) {
            int j;

A
antirez 已提交
1960
            for (j = 0; j < CLUSTER_SLOTS; j++) {
1961 1962 1963 1964 1965 1966
                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 已提交
1967
                        serverLog(LL_VERBOSE,
1968
                            "Node %.40s has old slots configuration, sending "
1969
                            "an UPDATE message about %.40s",
1970
                                sender->name, server.cluster->slots[j]->name);
A
antirez 已提交
1971 1972
                        clusterSendUpdate(sender->link,
                            server.cluster->slots[j]);
1973 1974 1975 1976 1977

                        /* TODO: instead of exiting the loop send every other
                         * UPDATE packet for other nodes that are the new owner
                         * of sender's slots. */
                        break;
1978
                    }
1979
                }
A
antirez 已提交
1980 1981 1982
            }
        }

1983 1984 1985 1986 1987 1988 1989 1990 1991
        /* 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 已提交
1992
        /* Get info from the gossip section */
1993
        if (sender) clusterProcessGossipSection(hdr,link);
1994
    } else if (type == CLUSTERMSG_TYPE_FAIL) {
A
antirez 已提交
1995 1996
        clusterNode *failing;

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

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

        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. */
2075
        if (nodeIsSlave(n)) clusterSetNodeAsMaster(n);
2076

2077 2078
        /* Update the node's configEpoch. */
        n->configEpoch = reportedConfigEpoch;
A
antirez 已提交
2079 2080
        clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                             CLUSTER_TODO_FSYNC_CONFIG);
2081

2082
        /* Check the bitmap of served slots and update our
2083
         * config accordingly. */
2084 2085
        clusterUpdateSlotsConfigWith(n,reportedConfigEpoch,
            hdr->data.update.nodecfg.slots);
2086 2087 2088 2089 2090 2091 2092 2093 2094
    } 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 已提交
2095
    } else {
A
antirez 已提交
2096
        serverLog(LL_WARNING,"Received unknown packet type: %d", type);
A
antirez 已提交
2097 2098 2099 2100 2101 2102 2103
    }
    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.
2104

A
antirez 已提交
2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116
   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 已提交
2117 2118
    UNUSED(el);
    UNUSED(mask);
A
antirez 已提交
2119 2120 2121

    nwritten = write(fd, link->sndbuf, sdslen(link->sndbuf));
    if (nwritten <= 0) {
A
antirez 已提交
2122
        serverLog(LL_DEBUG,"I/O error writing to node link: %s",
S
shenlongxing 已提交
2123
            (nwritten == -1) ? strerror(errno) : "short write");
A
antirez 已提交
2124 2125 2126
        handleLinkIOError(link);
        return;
    }
2127
    sdsrange(link->sndbuf,nwritten,-1);
A
antirez 已提交
2128 2129 2130 2131 2132 2133 2134 2135
    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) {
2136
    char buf[sizeof(clusterMsg)];
A
antirez 已提交
2137 2138 2139
    ssize_t nread;
    clusterMsg *hdr;
    clusterLink *link = (clusterLink*) privdata;
2140
    unsigned int readlen, rcvbuflen;
A
antirez 已提交
2141 2142
    UNUSED(el);
    UNUSED(mask);
A
antirez 已提交
2143

2144 2145
    while(1) { /* Read as long as there is data to read. */
        rcvbuflen = sdslen(link->rcvbuf);
2146 2147
        if (rcvbuflen < 8) {
            /* First, obtain the first 8 bytes to get the full message
2148
             * length. */
2149
            readlen = 8 - rcvbuflen;
2150 2151 2152
        } else {
            /* Finally read the full message. */
            hdr = (clusterMsg*) link->rcvbuf;
2153 2154 2155 2156 2157 2158
            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 已提交
2159
                    serverLog(LL_WARNING,
2160 2161
                        "Bad message length or signature received "
                        "from Cluster bus.");
2162 2163 2164
                    handleLinkIOError(link);
                    return;
                }
2165
            }
2166 2167
            readlen = ntohl(hdr->totlen) - rcvbuflen;
            if (readlen > sizeof(buf)) readlen = sizeof(buf);
2168
        }
A
antirez 已提交
2169

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

2173 2174
        if (nread <= 0) {
            /* I/O error... */
A
antirez 已提交
2175
            serverLog(LL_DEBUG,"I/O error reading from node link: %s",
2176 2177 2178 2179 2180 2181 2182 2183 2184
                (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 已提交
2185

2186
        /* Total length obtained? Process this packet. */
2187
        if (rcvbuflen >= 8 && rcvbuflen == ntohl(hdr->totlen)) {
2188 2189 2190 2191 2192 2193
            if (clusterProcessPacket(link)) {
                sdsfree(link->rcvbuf);
                link->rcvbuf = sdsempty();
            } else {
                return; /* Link no longer valid. */
            }
A
antirez 已提交
2194 2195 2196 2197
        }
    }
}

2198 2199 2200 2201 2202
/* 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 已提交
2203 2204
void clusterSendMessage(clusterLink *link, unsigned char *msg, size_t msglen) {
    if (sdslen(link->sndbuf) == 0 && msglen != 0)
2205
        aeCreateFileEvent(server.el,link->fd,AE_WRITABLE|AE_BARRIER,
A
antirez 已提交
2206 2207 2208
                    clusterWriteHandler,link);

    link->sndbuf = sdscatlen(link->sndbuf, msg, msglen);
2209 2210 2211 2212 2213 2214

    /* 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 已提交
2215 2216
}

2217
/* Send a message to all the nodes that are part of the cluster having
2218
 * a connected link.
2219
 *
2220 2221 2222
 * 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. */
2223 2224 2225 2226
void clusterBroadcastMessage(void *buf, size_t len) {
    dictIterator *di;
    dictEntry *de;

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

        if (!node->link) continue;
A
antirez 已提交
2232
        if (node->flags & (CLUSTER_NODE_MYSELF|CLUSTER_NODE_HANDSHAKE))
2233
            continue;
2234 2235 2236 2237 2238
        clusterSendMessage(node->link,buf,len);
    }
    dictReleaseIterator(di);
}

2239 2240
/* Build the message header. hdr must point to a buffer at least
 * sizeof(clusterMsg) in bytes. */
A
antirez 已提交
2241
void clusterBuildMessageHdr(clusterMsg *hdr, int type) {
2242
    int totlen = 0;
2243
    uint64_t offset;
2244
    clusterNode *master;
2245 2246 2247 2248 2249

    /* 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. */
2250
    master = (nodeIsSlave(myself) && myself->slaveof) ?
2251
              myself->slaveof : myself;
A
antirez 已提交
2252 2253

    memset(hdr,0,sizeof(*hdr));
2254
    hdr->ver = htons(CLUSTER_PROTO_VER);
2255 2256
    hdr->sig[0] = 'R';
    hdr->sig[1] = 'C';
2257
    hdr->sig[2] = 'm';
2258
    hdr->sig[3] = 'b';
A
antirez 已提交
2259
    hdr->type = htons(type);
A
antirez 已提交
2260
    memcpy(hdr->sender,myself->name,CLUSTER_NAMELEN);
2261

2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277
    /* 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);

2278
    memcpy(hdr->myslots,master->slots,sizeof(hdr->myslots));
A
antirez 已提交
2279
    memset(hdr->slaveof,0,CLUSTER_NAMELEN);
2280
    if (myself->slaveof != NULL)
A
antirez 已提交
2281
        memcpy(hdr->slaveof,myself->slaveof->name, CLUSTER_NAMELEN);
2282 2283
    hdr->port = htons(announced_port);
    hdr->cport = htons(announced_cport);
2284
    hdr->flags = htons(myself->flags);
2285
    hdr->state = server.cluster->state;
A
antirez 已提交
2286

2287
    /* Set the currentEpoch and configEpochs. */
2288
    hdr->currentEpoch = htonu64(server.cluster->currentEpoch);
2289
    hdr->configEpoch = htonu64(master->configEpoch);
2290

2291
    /* Set the replication offset. */
2292 2293 2294
    if (nodeIsSlave(myself))
        offset = replicationGetSlaveOffset();
    else
2295 2296 2297
        offset = server.master_repl_offset;
    hdr->offset = htonu64(offset);

2298 2299 2300 2301
    /* Set the message flags. */
    if (nodeIsMaster(myself) && server.cluster->mf_end)
        hdr->mflags[0] |= CLUSTERMSG_FLAG0_PAUSED;

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

2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
/* 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 已提交
2342 2343 2344
/* Send a PING or PONG packet to the specified node, making sure to add enough
 * gossip informations. */
void clusterSendPing(clusterLink *link, int type) {
2345 2346 2347 2348 2349 2350 2351 2352 2353
    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. */
2354
    int freshnodes = dictSize(server.cluster->nodes)-2;
A
antirez 已提交
2355

2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379
    /* 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
2380
     * to feature our node, we set the number of entries per packet as
2381
     * 10% of the total nodes we have. */
2382
    wanted = floor(dictSize(server.cluster->nodes)/10);
2383
    if (wanted < 3) wanted = 3;
2384
    if (wanted > freshnodes) wanted = freshnodes;
2385

2386 2387 2388 2389
    /* 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;

2390 2391 2392 2393
    /* 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);
2394
    totlen += (sizeof(clusterMsgDataGossip)*(wanted+pfail_wanted));
2395 2396 2397 2398 2399 2400 2401
    /* 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 已提交
2402
    if (link->node && type == CLUSTERMSG_TYPE_PING)
2403
        link->node->ping_sent = mstime();
A
antirez 已提交
2404
    clusterBuildMessageHdr(hdr,type);
2405

A
antirez 已提交
2406
    /* Populate the gossip fields */
2407
    int maxiterations = wanted*3;
2408
    while(freshnodes > 0 && gossipcount < wanted && maxiterations--) {
A
antirez 已提交
2409
        dictEntry *de = dictGetRandomKey(server.cluster->nodes);
2410
        clusterNode *this = dictGetVal(de);
A
antirez 已提交
2411

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

2416 2417
        /* PFAIL nodes will be added later. */
        if (this->flags & CLUSTER_NODE_PFAIL) continue;
2418

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

2431 2432
        /* Do not add a node we already have. */
        if (clusterNodeIsInGossipSection(hdr,gossipcount,this)) continue;
A
antirez 已提交
2433 2434

        /* Add it */
2435
        clusterSetGossipEntry(hdr,gossipcount,this);
A
antirez 已提交
2436 2437 2438
        freshnodes--;
        gossipcount++;
    }
2439

2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461
    /* 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);
    }

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

2472 2473
/* Send a PONG packet to every connected node that's not in handshake state
 * and for which we have a valid link.
2474
 *
2475 2476
 * In Redis Cluster pongs are not used just for failure detection, but also
 * to carry important configuration information. So broadcasting a pong is
2477
 * useful when something changes in the configuration and we want to make
2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488
 * 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) {
2489 2490 2491
    dictIterator *di;
    dictEntry *de;

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

2496
        if (!node->link) continue;
2497
        if (node == myself || nodeInHandshake(node)) continue;
2498 2499
        if (target == CLUSTER_BROADCAST_LOCAL_SLAVES) {
            int local_slave =
2500
                nodeIsSlave(node) && node->slaveof &&
2501 2502 2503
                (node->slaveof == myself || node->slaveof == myself->slaveof);
            if (!local_slave) continue;
        }
2504 2505 2506 2507 2508
        clusterSendPing(node->link,CLUSTERMSG_TYPE_PONG);
    }
    dictReleaseIterator(di);
}

2509 2510 2511 2512
/* 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) {
2513
    unsigned char buf[sizeof(clusterMsg)], *payload;
2514 2515 2516
    clusterMsg *hdr = (clusterMsg*) buf;
    uint32_t totlen;
    uint32_t channel_len, message_len;
A
antirez 已提交
2517

2518 2519 2520 2521
    channel = getDecodedObject(channel);
    message = getDecodedObject(message);
    channel_len = sdslen(channel->ptr);
    message_len = sdslen(message->ptr);
A
antirez 已提交
2522

2523 2524
    clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_PUBLISH);
    totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
2525
    totlen += sizeof(clusterMsgDataPublish) - 8 + channel_len + message_len;
2526 2527 2528 2529 2530 2531 2532 2533 2534 2535

    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);
2536
        memcpy(payload,hdr,sizeof(*hdr));
2537
        hdr = (clusterMsg*) payload;
A
antirez 已提交
2538
    }
2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550
    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 已提交
2551 2552 2553 2554
}

/* 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 已提交
2555 2556
 * (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 已提交
2557 2558
 * nodes to do the same ASAP. */
void clusterSendFail(char *nodename) {
2559
    unsigned char buf[sizeof(clusterMsg)];
A
antirez 已提交
2560 2561 2562
    clusterMsg *hdr = (clusterMsg*) buf;

    clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_FAIL);
A
antirez 已提交
2563
    memcpy(hdr->data.fail.about.nodename,nodename,CLUSTER_NAMELEN);
A
antirez 已提交
2564 2565 2566
    clusterBroadcastMessage(buf,ntohl(hdr->totlen));
}

2567 2568 2569 2570
/* 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) {
2571
    unsigned char buf[sizeof(clusterMsg)];
2572 2573
    clusterMsg *hdr = (clusterMsg*) buf;

2574
    if (link == NULL) return;
2575
    clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_UPDATE);
A
antirez 已提交
2576
    memcpy(hdr->data.update.nodecfg.nodename,node->name,CLUSTER_NAMELEN);
2577 2578 2579 2580 2581
    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));
}

2582 2583 2584 2585 2586 2587 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
/* 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. */
2624
int clusterSendModuleMessageToTarget(const char *target, uint64_t module_id, uint8_t type, unsigned char *payload, uint32_t len) {
2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636
    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;
}

2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647
/* -----------------------------------------------------------------------------
 * 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);
}

2648 2649 2650 2651
/* -----------------------------------------------------------------------------
 * SLAVE node specific functions
 * -------------------------------------------------------------------------- */

2652 2653 2654 2655 2656 2657 2658
/* 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) {
2659
    unsigned char buf[sizeof(clusterMsg)];
2660 2661 2662 2663
    clusterMsg *hdr = (clusterMsg*) buf;
    uint32_t totlen;

    clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_FAILOVER_AUTH_REQUEST);
2664 2665 2666 2667
    /* 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;
2668 2669
    totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
    hdr->totlen = htonl(totlen);
2670
    clusterBroadcastMessage(buf,totlen);
2671 2672
}

2673 2674
/* Send a FAILOVER_AUTH_ACK message to the specified node. */
void clusterSendFailoverAuth(clusterNode *node) {
2675
    unsigned char buf[sizeof(clusterMsg)];
2676 2677 2678 2679 2680 2681 2682
    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);
2683
    clusterSendMessage(node->link,buf,totlen);
2684 2685
}

2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698
/* 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);
}

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

    /* 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
2710 2711
     * of masters serving at least one slot, and quorum is the cluster
     * size + 1 */
2712
    if (nodeIsSlave(myself) || myself->numslots == 0) return;
2713

2714 2715 2716 2717
    /* 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. */
2718
    if (requestCurrentEpoch < server.cluster->currentEpoch) {
A
antirez 已提交
2719
        serverLog(LL_WARNING,
2720 2721 2722 2723 2724 2725
            "Failover auth denied to %.40s: reqEpoch (%llu) < curEpoch(%llu)",
            node->name,
            (unsigned long long) requestCurrentEpoch,
            (unsigned long long) server.cluster->currentEpoch);
        return;
    }
2726

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

2736 2737 2738 2739
    /* 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 ||
2740 2741 2742
        (!nodeFailed(master) && !force_ack))
    {
        if (nodeIsMaster(node)) {
A
antirez 已提交
2743
            serverLog(LL_WARNING,
2744 2745 2746
                    "Failover auth denied to %.40s: it is a master node",
                    node->name);
        } else if (master == NULL) {
A
antirez 已提交
2747
            serverLog(LL_WARNING,
2748 2749 2750
                    "Failover auth denied to %.40s: I don't know its master",
                    node->name);
        } else if (!nodeFailed(master)) {
A
antirez 已提交
2751
            serverLog(LL_WARNING,
2752 2753 2754 2755 2756
                    "Failover auth denied to %.40s: its master is up",
                    node->name);
        }
        return;
    }
2757

2758 2759 2760
    /* 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. */
2761
    if (mstime() - node->slaveof->voted_time < server.cluster_node_timeout * 2)
2762
    {
A
antirez 已提交
2763
        serverLog(LL_WARNING,
2764 2765
                "Failover auth denied to %.40s: "
                "can't vote about this master before %lld milliseconds",
2766
                node->name,
2767 2768
                (long long) ((server.cluster_node_timeout*2)-
                             (mstime() - node->slaveof->voted_time)));
2769
        return;
2770
    }
2771

2772 2773 2774
    /* 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 已提交
2775
    for (j = 0; j < CLUSTER_SLOTS; j++) {
2776 2777
        if (bitmapTestBit(claimed_slots, j) == 0) continue;
        if (server.cluster->slots[j] == NULL ||
A
antirez 已提交
2778 2779 2780 2781
            server.cluster->slots[j]->configEpoch <= requestConfigEpoch)
        {
            continue;
        }
2782 2783 2784
        /* 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 已提交
2785
        serverLog(LL_WARNING,
2786 2787 2788 2789 2790
                "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);
2791 2792 2793
        return;
    }

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

2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819
/* 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 已提交
2820
    serverAssert(nodeIsSlave(myself));
2821 2822 2823 2824 2825 2826
    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 &&
2827
            !nodeCantFailover(master->slaves[j]) &&
2828 2829 2830 2831
            master->slaves[j]->repl_offset > myoffset) rank++;
    return rank;
}

2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844
/* 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 已提交
2845
 *    CLUSTER_CANT_FAILOVER_RELOG_PERIOD seconds elapsed.
2846 2847 2848 2849 2850
 * 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 已提交
2851
 * which is one of the integer macros CLUSTER_CANT_FAILOVER_*.
2852 2853 2854 2855 2856 2857 2858 2859 2860
 *
 * 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 已提交
2861
        time(NULL)-lastlog_time < CLUSTER_CANT_FAILOVER_RELOG_PERIOD)
2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873
        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 已提交
2874
    case CLUSTER_CANT_FAILOVER_DATA_AGE:
2875 2876 2877
        msg = "Disconnected from master for longer than allowed. "
              "Please check the 'cluster-slave-validity-factor' configuration "
              "option.";
2878
        break;
A
antirez 已提交
2879
    case CLUSTER_CANT_FAILOVER_WAITING_DELAY:
2880 2881
        msg = "Waiting the delay before I can start a new failover.";
        break;
A
antirez 已提交
2882
    case CLUSTER_CANT_FAILOVER_EXPIRED:
2883 2884
        msg = "Failover attempt expired.";
        break;
A
antirez 已提交
2885
    case CLUSTER_CANT_FAILOVER_WAITING_VOTES:
2886 2887 2888 2889 2890 2891 2892
        msg = "Waiting for votes, but majority still not reached.";
        break;
    default:
        msg = "Unknown reason code.";
        break;
    }
    lastlog_time = time(NULL);
A
antirez 已提交
2893
    serverLog(LL_WARNING,"Currently unable to failover: %s", msg);
2894 2895
}

2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912
/* 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 已提交
2913
    for (j = 0; j < CLUSTER_SLOTS; j++) {
2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931
        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();
}

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

2948 2949
    server.cluster->todo_before_sleep &= ~CLUSTER_TODO_HANDLE_FAILOVER;

2950 2951
    /* 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
2952
     * before trying to get voted again).
2953
     *
A
andyli 已提交
2954
     * Timeout is MAX(NODE_TIMEOUT*2,2000) milliseconds.
2955 2956 2957 2958 2959
     * 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;
2960

2961 2962
    /* Pre conditions to run the function, that must be met both in case
     * of an automatic or manual failover:
2963
     * 1) We are a slave.
2964
     * 2) Our master is flagged as FAIL, or this is a manual failover.
2965 2966 2967
     * 3) We don't have the no failover configuration set, and this is
     *    not a manual failover.
     * 4) It is serving slots. */
2968
    if (nodeIsMaster(myself) ||
2969
        myself->slaveof == NULL ||
2970
        (!nodeFailed(myself->slaveof) && !manual_failover) ||
2971
        (server.cluster_slave_no_failover && !manual_failover) ||
2972 2973 2974 2975
        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 已提交
2976
        server.cluster->cant_failover_reason = CLUSTER_CANT_FAILOVER_NONE;
2977 2978
        return;
    }
2979

2980 2981
    /* Set data_age to the number of seconds we are disconnected from
     * the master. */
A
antirez 已提交
2982
    if (server.repl_state == REPL_STATE_CONNECTED) {
2983 2984
        data_age = (mstime_t)(server.unixtime - server.master->lastinteraction)
                   * 1000;
2985
    } else {
2986
        data_age = (mstime_t)(server.unixtime - server.repl_down_since) * 1000;
2987 2988
    }

2989 2990 2991 2992 2993 2994
    /* 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;

2995 2996
    /* Check if our data is recent enough according to the slave validity
     * factor configured by the user.
2997 2998
     *
     * Check bypassed for manual failovers. */
2999 3000 3001 3002
    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)))
3003
    {
3004
        if (!manual_failover) {
A
antirez 已提交
3005
            clusterLogCantFailover(CLUSTER_CANT_FAILOVER_DATA_AGE);
3006 3007
            return;
        }
3008
    }
3009

3010 3011 3012
    /* If the previous failover attempt timedout and the retry time has
     * elapsed, we can setup a new one. */
    if (auth_age > auth_retry_time) {
3013 3014 3015
        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. */
3016
        server.cluster->failover_auth_count = 0;
3017
        server.cluster->failover_auth_sent = 0;
3018 3019 3020 3021 3022 3023
        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;
3024 3025 3026 3027 3028
        /* 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 已提交
3029
        serverLog(LL_WARNING,
3030 3031
            "Start of election delayed for %lld milliseconds "
            "(rank #%d, offset %lld).",
3032
            server.cluster->failover_auth_time - mstime(),
3033 3034
            server.cluster->failover_auth_rank,
            replicationGetSlaveOffset());
3035 3036 3037 3038
        /* 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);
3039 3040 3041 3042 3043
        return;
    }

    /* It is possible that we received more updated offsets from other
     * slaves for the same master since we computed our election delay.
3044 3045 3046
     * Update the delay if our rank changed.
     *
     * Not performed if this is a manual failover. */
3047 3048 3049
    if (server.cluster->failover_auth_sent == 0 &&
        server.cluster->mf_end == 0)
    {
3050 3051 3052 3053 3054 3055
        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 已提交
3056
            serverLog(LL_WARNING,
3057 3058 3059
                "Slave rank updated to #%d, added %lld milliseconds of delay.",
                newrank, added_delay);
        }
3060 3061 3062
    }

    /* Return ASAP if we can't still start the election. */
3063
    if (mstime() < server.cluster->failover_auth_time) {
A
antirez 已提交
3064
        clusterLogCantFailover(CLUSTER_CANT_FAILOVER_WAITING_DELAY);
3065 3066
        return;
    }
3067 3068

    /* Return ASAP if the election is too old to be valid. */
3069
    if (auth_age > auth_timeout) {
A
antirez 已提交
3070
        clusterLogCantFailover(CLUSTER_CANT_FAILOVER_EXPIRED);
3071 3072
        return;
    }
3073 3074 3075 3076 3077

    /* 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 已提交
3078
        serverLog(LL_WARNING,"Starting a failover election for epoch %llu.",
3079
            (unsigned long long) server.cluster->currentEpoch);
3080
        clusterRequestFailoverAuth();
3081
        server.cluster->failover_auth_sent = 1;
A
antirez 已提交
3082 3083 3084
        clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                             CLUSTER_TODO_UPDATE_STATE|
                             CLUSTER_TODO_FSYNC_CONFIG);
3085 3086 3087 3088
        return; /* Wait for replies. */
    }

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

A
antirez 已提交
3092
        serverLog(LL_WARNING,
A
antirez 已提交
3093
            "Failover election won: I'm the new master.");
A
antirez 已提交
3094

3095
        /* Update my configEpoch to the epoch of the election. */
3096
        if (myself->configEpoch < server.cluster->failover_auth_epoch) {
3097
            myself->configEpoch = server.cluster->failover_auth_epoch;
A
antirez 已提交
3098
            serverLog(LL_WARNING,
3099 3100 3101
                "configEpoch set to %llu after successful failover",
                (unsigned long long) myself->configEpoch);
        }
3102

J
Jack Drogon 已提交
3103
        /* Take responsibility for the cluster slots. */
3104
        clusterFailoverReplaceYourMaster();
3105
    } else {
A
antirez 已提交
3106
        clusterLogCantFailover(CLUSTER_CANT_FAILOVER_WAITING_VOTES);
3107
    }
3108 3109
}

3110 3111 3112 3113 3114 3115
/* -----------------------------------------------------------------------------
 * 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.
3116
 * ------------------------------------------------------------------------- */
3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143

/* 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 已提交
3144
    if (server.cluster->state != CLUSTER_OK) return;
3145

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

J
Jack Drogon 已提交
3154
    /* Step 3: Identify a candidate for migration, and check if among the
3155
     * masters with the greatest number of ok slaves, I'm the one with the
A
antirez 已提交
3156
     * smallest node ID (the "candidate slave").
3157
     *
J
Jack Drogon 已提交
3158
     * Note: this means that eventually a replica migration will occur
3159
     * since slaves that are reachable again always have their FAIL flag
A
antirez 已提交
3160 3161 3162 3163
     * 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. */
3164 3165 3166 3167
    candidate = myself;
    di = dictGetSafeIterator(server.cluster->nodes);
    while((de = dictNext(di)) != NULL) {
        clusterNode *node = dictGetVal(de);
A
antirez 已提交
3168
        int okslaves = 0, is_orphaned = 1;
3169

A
antirez 已提交
3170 3171 3172 3173 3174 3175
        /* 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;
3176

A
antirez 已提交
3177 3178 3179
        /* Check number of working slaves. */
        if (nodeIsMaster(node)) okslaves = clusterCountNonFailingSlaves(node);
        if (okslaves > 0) is_orphaned = 0;
A
antirez 已提交
3180

A
antirez 已提交
3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193
        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. */
3194 3195 3196 3197
        if (okslaves == max_slaves) {
            for (j = 0; j < node->numslaves; j++) {
                if (memcmp(node->slaves[j]->name,
                           candidate->name,
A
antirez 已提交
3198
                           CLUSTER_NAMELEN) < 0)
3199 3200 3201 3202 3203 3204
                {
                    candidate = node->slaves[j];
                }
            }
        }
    }
M
Matt Stancliff 已提交
3205
    dictReleaseIterator(di);
3206 3207

    /* Step 4: perform the migration if there is a target, and if I'm the
A
antirez 已提交
3208 3209 3210 3211 3212 3213 3214
     * 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 &&
        (mstime()-target->orphaned_time) > CLUSTER_SLAVE_MIGRATION_DELAY)
    {
A
antirez 已提交
3215
        serverLog(LL_WARNING,"Migrating to orphaned master %.40s",
3216 3217 3218 3219 3220
            target->name);
        clusterSetMaster(target);
    }
}

3221 3222 3223 3224 3225 3226 3227 3228
/* -----------------------------------------------------------------------------
 * 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 已提交
3229
 *    for two times the manual failover timeout CLUSTER_MF_TIMEOUT.
3230 3231 3232 3233 3234 3235 3236 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
 *    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) {
3268
    if (server.cluster->mf_end && server.cluster->mf_end < mstime()) {
A
antirez 已提交
3269
        serverLog(LL_WARNING,"Manual failover timed out.");
3270 3271 3272 3273 3274 3275 3276 3277 3278 3279
        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;

3280
    /* If mf_can_start is non-zero, the failover was already triggered so the
3281 3282 3283 3284 3285 3286 3287 3288 3289
     * 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 已提交
3290
        serverLog(LL_WARNING,
A
antirez 已提交
3291 3292
            "All master replication stream processed, "
            "manual failover can start.");
3293 3294 3295
    }
}

A
antirez 已提交
3296 3297 3298 3299
/* -----------------------------------------------------------------------------
 * CLUSTER cron job
 * -------------------------------------------------------------------------- */

3300
/* This is executed 10 times every second */
A
antirez 已提交
3301 3302 3303
void clusterCron(void) {
    dictIterator *di;
    dictEntry *de;
3304 3305 3306 3307
    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). */
3308
    mstime_t min_pong = 0, now = mstime();
3309
    clusterNode *min_pong_node = NULL;
3310
    static unsigned long long iteration = 0;
3311
    mstime_t handshake_timeout;
3312 3313

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

3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327
    /* 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;
        if (prev_ip != NULL && curr_ip == NULL) changed = 1;
        if (prev_ip && curr_ip && strcmp(prev_ip,curr_ip)) changed = 1;

        if (changed) {
3328
            if (prev_ip) zfree(prev_ip);
3329

3330
            prev_ip = curr_ip;
3331
            if (curr_ip) {
3332
                prev_ip = zstrdup(prev_ip);
3333 3334 3335 3336 3337 3338 3339 3340
                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. */
            }
        }
    }

3341
    /* The handshake timeout is the time after which a handshake node that was
3342 3343 3344 3345 3346 3347
     * 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;

3348 3349 3350
    /* Update myself flags. */
    clusterUpdateMyselfFlags();

3351 3352 3353
    /* 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. */
3354
    di = dictGetSafeIterator(server.cluster->nodes);
3355
    server.cluster->stats_pfail_nodes = 0;
A
antirez 已提交
3356
    while((de = dictNext(di)) != NULL) {
3357
        clusterNode *node = dictGetVal(de);
A
antirez 已提交
3358

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

3363 3364 3365
        if (node->flags & CLUSTER_NODE_PFAIL)
            server.cluster->stats_pfail_nodes++;

3366 3367
        /* A Node in HANDSHAKE state has a limited lifespan equal to the
         * configured node timeout. */
3368
        if (nodeInHandshake(node) && now - node->ctime > handshake_timeout) {
3369
            clusterDelNode(node);
3370 3371 3372
            continue;
        }

A
antirez 已提交
3373 3374
        if (node->link == NULL) {
            int fd;
3375
            mstime_t old_ping_sent;
A
antirez 已提交
3376 3377
            clusterLink *link;

3378
            fd = anetTcpNonBlockBindConnect(server.neterr, node->ip,
3379
                node->cport, NET_FIRST_BIND_ADDR);
3380
            if (fd == -1) {
3381 3382 3383 3384 3385 3386
                /* 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 已提交
3387
                serverLog(LL_DEBUG, "Unable to connect to "
3388
                    "Cluster Node [%s]:%d -> %s", node->ip,
3389
                    node->cport, server.neterr);
3390 3391
                continue;
            }
A
antirez 已提交
3392 3393 3394
            link = createClusterLink(node);
            link->fd = fd;
            node->link = link;
A
antirez 已提交
3395 3396
            aeCreateFileEvent(server.el,link->fd,AE_READABLE,
                    clusterReadHandler,link);
3397 3398 3399 3400
            /* 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 已提交
3401 3402
             * of a PING one, to force the receiver to add us in its node
             * table. */
3403
            old_ping_sent = node->ping_sent;
A
antirez 已提交
3404
            clusterSendPing(link, node->flags & CLUSTER_NODE_MEET ?
A
antirez 已提交
3405
                    CLUSTERMSG_TYPE_MEET : CLUSTERMSG_TYPE_PING);
3406 3407 3408 3409 3410 3411
            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 已提交
3412 3413 3414 3415 3416
            /* 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 已提交
3417
            node->flags &= ~CLUSTER_NODE_MEET;
A
antirez 已提交
3418

A
antirez 已提交
3419
            serverLog(LL_DEBUG,"Connecting with Node %.40s at %s:%d",
3420
                    node->name, node->ip, node->cport);
A
antirez 已提交
3421 3422 3423 3424
        }
    }
    dictReleaseIterator(di);

3425 3426 3427
    /* Ping some random node 1 time every 10 iterations, so that we usually ping
     * one random node every second. */
    if (!(iteration % 10)) {
3428 3429
        int j;

3430 3431 3432 3433 3434 3435 3436 3437
        /* 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 已提交
3438
            if (this->flags & (CLUSTER_NODE_MYSELF|CLUSTER_NODE_HANDSHAKE))
A
antirez 已提交
3439
                continue;
3440 3441 3442 3443 3444 3445
            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 已提交
3446
            serverLog(LL_DEBUG,"Pinging node %.40s", min_pong_node->name);
3447
            clusterSendPing(min_pong_node->link, CLUSTERMSG_TYPE_PING);
A
antirez 已提交
3448 3449 3450
        }
    }

3451 3452 3453 3454 3455 3456 3457 3458 3459
    /* 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;
3460
    di = dictGetSafeIterator(server.cluster->nodes);
A
antirez 已提交
3461
    while((de = dictNext(di)) != NULL) {
3462
        clusterNode *node = dictGetVal(de);
3463
        now = mstime(); /* Use an updated time at every iteration. */
3464
        mstime_t delay;
A
antirez 已提交
3465 3466

        if (node->flags &
A
antirez 已提交
3467
            (CLUSTER_NODE_MYSELF|CLUSTER_NODE_NOADDR|CLUSTER_NODE_HANDSHAKE))
3468
                continue;
3469

3470 3471 3472 3473 3474
        /* 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);

3475 3476
            /* 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
3477 3478 3479 3480
             * slave, or failed over a master that used to have slaves. */
            if (okslaves == 0 && node->numslots > 0 &&
                node->flags & CLUSTER_NODE_MIGRATE_TO)
            {
3481
                orphaned_masters++;
3482
            }
3483 3484 3485 3486 3487
            if (okslaves > max_slaves) max_slaves = okslaves;
            if (nodeIsSlave(myself) && myself->slaveof == node)
                this_slaves = okslaves;
        }

3488 3489 3490 3491
        /* 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 */
3492
            now - node->link->ctime >
3493
            server.cluster_node_timeout && /* was not already reconnected */
3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506
            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. */
3507
        if (node->link &&
3508 3509
            node->ping_sent == 0 &&
            (now - node->pong_received) > server.cluster_node_timeout/2)
3510 3511 3512 3513 3514
        {
            clusterSendPing(node->link, CLUSTERMSG_TYPE_PING);
            continue;
        }

3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525
        /* 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;
        }

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

3529 3530 3531 3532
        /* 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;
3533

3534
        if (delay > server.cluster_node_timeout) {
G
guiquanz 已提交
3535
            /* Timeout reached. Set the node as possibly failing if it is
3536
             * not already in this state. */
A
antirez 已提交
3537
            if (!(node->flags & (CLUSTER_NODE_PFAIL|CLUSTER_NODE_FAIL))) {
A
antirez 已提交
3538
                serverLog(LL_DEBUG,"*** NODE %.40s possibly failing",
A
antirez 已提交
3539
                    node->name);
A
antirez 已提交
3540
                node->flags |= CLUSTER_NODE_PFAIL;
3541
                update_state = 1;
A
antirez 已提交
3542 3543 3544 3545
            }
        }
    }
    dictReleaseIterator(di);
3546 3547 3548 3549

    /* 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. */
3550
    if (nodeIsSlave(myself) &&
3551
        server.masterhost == NULL &&
3552
        myself->slaveof &&
3553
        nodeHasAddr(myself->slaveof))
3554
    {
3555
        replicationSetMaster(myself->slaveof->ip, myself->slaveof->port);
3556
    }
3557

3558 3559 3560
    /* Abourt a manual failover if the timeout is reached. */
    manualFailoverCheckTimeout();

3561
    if (nodeIsSlave(myself)) {
3562
        clusterHandleManualFailover();
3563 3564 3565 3566 3567 3568 3569 3570 3571 3572
        clusterHandleSlaveFailover();
        /* 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 已提交
3573
    if (update_state || server.cluster->state == CLUSTER_FAIL)
3574
        clusterUpdateState();
3575 3576 3577 3578 3579
}

/* 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 已提交
3580 3581
 * handlers, or to perform potentially expansive tasks that we need to do
 * a single time before replying to clients. */
3582
void clusterBeforeSleep(void) {
A
antirez 已提交
3583 3584 3585
    /* 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)
3586
        clusterHandleSlaveFailover();
A
antirez 已提交
3587 3588 3589 3590 3591 3592 3593

    /* 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 已提交
3594 3595
        int fsync = server.cluster->todo_before_sleep &
                    CLUSTER_TODO_FSYNC_CONFIG;
A
antirez 已提交
3596
        clusterSaveConfigOrDie(fsync);
3597
    }
A
antirez 已提交
3598

3599 3600
    /* Reset our flags (not strictly needed since every single function
     * called for flags set should be able to clear its flag). */
A
antirez 已提交
3601 3602 3603 3604 3605
    server.cluster->todo_before_sleep = 0;
}

void clusterDoBeforeSleep(int flags) {
    server.cluster->todo_before_sleep |= flags;
A
antirez 已提交
3606 3607 3608 3609 3610 3611
}

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

3612
/* Test bit 'pos' in a generic bitmap. Return 1 if the bit is set,
3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633
 * 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);
}

3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650
/* 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 已提交
3651 3652
/* Set the slot bit and return the old value. */
int clusterNodeSetSlotBit(clusterNode *n, int slot) {
3653 3654
    int old = bitmapTestBit(n->slots,slot);
    bitmapSetBit(n->slots,slot);
3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672
    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 已提交
3673 3674 3675 3676 3677
    return old;
}

/* Clear the slot bit and return the old value. */
int clusterNodeClearSlotBit(clusterNode *n, int slot) {
3678 3679
    int old = bitmapTestBit(n->slots,slot);
    bitmapClearBit(n->slots,slot);
3680
    if (old) n->numslots--;
A
antirez 已提交
3681 3682 3683 3684 3685
    return old;
}

/* Return the slot bit from the cluster node structure. */
int clusterNodeGetSlotBit(clusterNode *n, int slot) {
3686
    return bitmapTestBit(n->slots,slot);
A
antirez 已提交
3687 3688 3689
}

/* Add the specified slot to the list of slots that node 'n' will
3690
 * serve. Return C_OK if the operation ended with success.
A
antirez 已提交
3691
 * If the slot is already assigned to another instance this is considered
3692
 * an error and C_ERR is returned. */
A
antirez 已提交
3693
int clusterAddSlot(clusterNode *n, int slot) {
3694
    if (server.cluster->slots[slot]) return C_ERR;
3695
    clusterNodeSetSlotBit(n,slot);
3696
    server.cluster->slots[slot] = n;
3697
    return C_OK;
A
antirez 已提交
3698 3699
}

A
antirez 已提交
3700
/* Delete the specified slot marking it as unassigned.
3701 3702
 * Returns C_OK if the slot was assigned, otherwise if the slot was
 * already unassigned C_ERR is returned. */
A
antirez 已提交
3703
int clusterDelSlot(int slot) {
3704
    clusterNode *n = server.cluster->slots[slot];
A
antirez 已提交
3705

3706
    if (!n) return C_ERR;
A
antirez 已提交
3707
    serverAssert(clusterNodeClearSlotBit(n,slot) == 1);
3708
    server.cluster->slots[slot] = NULL;
3709
    return C_OK;
A
antirez 已提交
3710 3711
}

3712 3713 3714 3715 3716
/* 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 已提交
3717
    for (j = 0; j < CLUSTER_SLOTS; j++) {
3718 3719 3720 3721
        if (clusterNodeGetSlotBit(node,j)) {
            clusterDelSlot(j);
            deleted++;
        }
3722 3723 3724 3725
    }
    return deleted;
}

A
antirez 已提交
3726 3727 3728 3729 3730 3731 3732 3733 3734
/* 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 已提交
3735 3736 3737
/* -----------------------------------------------------------------------------
 * Cluster state evaluation function
 * -------------------------------------------------------------------------- */
3738

3739
/* The following are defines that are only used in the evaluation function
J
Jack Drogon 已提交
3740
 * and are based on heuristics. Actually the main point about the rejoin and
3741 3742
 * writable delay is that they should be a few orders of magnitude larger
 * than the network latency. */
A
antirez 已提交
3743 3744 3745
#define CLUSTER_MAX_REJOIN_DELAY 5000
#define CLUSTER_MIN_REJOIN_DELAY 500
#define CLUSTER_WRITABLE_DELAY 2000
3746

A
antirez 已提交
3747
void clusterUpdateState(void) {
3748
    int j, new_state;
3749
    int reachable_masters = 0;
3750
    static mstime_t among_minority_time;
3751 3752
    static mstime_t first_call_time = 0;

3753 3754
    server.cluster->todo_before_sleep &= ~CLUSTER_TODO_UPDATE_STATE;

3755 3756 3757 3758 3759 3760 3761
    /* 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();
3762
    if (nodeIsMaster(myself) &&
A
antirez 已提交
3763 3764
        server.cluster->state == CLUSTER_FAIL &&
        mstime() - first_call_time < CLUSTER_WRITABLE_DELAY) return;
A
antirez 已提交
3765

3766 3767
    /* Start assuming the state is OK. We'll turn it into FAIL if there
     * are the right conditions. */
A
antirez 已提交
3768
    new_state = CLUSTER_OK;
3769

3770
    /* Check if all the slots are covered. */
3771
    if (server.cluster_require_full_coverage) {
A
antirez 已提交
3772
        for (j = 0; j < CLUSTER_SLOTS; j++) {
3773
            if (server.cluster->slots[j] == NULL ||
A
antirez 已提交
3774
                server.cluster->slots[j]->flags & (CLUSTER_NODE_FAIL))
3775
            {
A
antirez 已提交
3776
                new_state = CLUSTER_FAIL;
3777 3778
                break;
            }
A
antirez 已提交
3779 3780
        }
    }
3781

3782
    /* Compute the cluster size, that is the number of master nodes
3783 3784
     * serving at least a single slot.
     *
3785 3786
     * At the same time count the number of reachable masters having
     * at least one slot. */
3787 3788 3789 3790 3791
    {
        dictIterator *di;
        dictEntry *de;

        server.cluster->size = 0;
3792
        di = dictGetSafeIterator(server.cluster->nodes);
3793 3794 3795
        while((de = dictNext(di)) != NULL) {
            clusterNode *node = dictGetVal(de);

3796
            if (nodeIsMaster(node) && node->numslots) {
3797
                server.cluster->size++;
A
antirez 已提交
3798
                if ((node->flags & (CLUSTER_NODE_FAIL|CLUSTER_NODE_PFAIL)) == 0)
3799
                    reachable_masters++;
3800
            }
3801 3802 3803
        }
        dictReleaseIterator(di);
    }
3804

3805 3806
    /* If we are in a minority partition, change the cluster state
     * to FAIL. */
3807 3808
    {
        int needed_quorum = (server.cluster->size / 2) + 1;
3809

3810
        if (reachable_masters < needed_quorum) {
A
antirez 已提交
3811
            new_state = CLUSTER_FAIL;
3812 3813
            among_minority_time = mstime();
        }
3814 3815
    }

3816
    /* Log a state change */
3817 3818 3819 3820 3821 3822 3823
    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 已提交
3824 3825 3826 3827
        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;
3828

A
antirez 已提交
3829
        if (new_state == CLUSTER_OK &&
3830
            nodeIsMaster(myself) &&
3831 3832 3833 3834 3835 3836
            mstime() - among_minority_time < rejoin_delay)
        {
            return;
        }

        /* Change the state and log the event. */
A
antirez 已提交
3837
        serverLog(LL_WARNING,"Cluster state changed: %s",
A
antirez 已提交
3838
            new_state == CLUSTER_OK ? "ok" : "fail");
3839 3840
        server.cluster->state = new_state;
    }
A
antirez 已提交
3841 3842
}

3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853
/* 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.
3854
 * 2) If we find data in a DB different than DB0 we return C_ERR to
3855 3856 3857
 *    signal the caller it should quit the server with an error message
 *    or take other actions.
 *
3858
 * The function always returns C_OK even if it will try to correct
3859
 * the error described in "1". However if data is found in DB different
3860
 * from DB0, C_ERR is returned.
3861 3862 3863 3864 3865
 *
 * 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) {
3866 3867 3868
    int j;
    int update_config = 0;

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

3873 3874
    /* Make sure we only have keys in DB0. */
    for (j = 1; j < server.dbnum; j++) {
3875
        if (dictSize(server.db[j].dict)) return C_ERR;
3876 3877 3878 3879
    }

    /* Check that all the slots we see populated memory have a corresponding
     * entry in the cluster table. Otherwise fix the table. */
A
antirez 已提交
3880
    for (j = 0; j < CLUSTER_SLOTS; j++) {
3881 3882 3883 3884
        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. */
3885
        if (server.cluster->slots[j] == myself ||
3886 3887 3888 3889 3890 3891 3892
            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++;
3893
        /* Case A: slot is unassigned. Take responsibility for it. */
3894
        if (server.cluster->slots[j] == NULL) {
A
antirez 已提交
3895
            serverLog(LL_WARNING, "I have keys for unassigned slot %d. "
3896
                                    "Taking responsibility for it.",j);
3897
            clusterAddSlot(myself,j);
3898
        } else {
A
antirez 已提交
3899
            serverLog(LL_WARNING, "I have keys for slot %d, but the slot is "
3900 3901
                                    "assigned to another node. "
                                    "Setting it to importing state.",j);
3902 3903 3904
            server.cluster->importing_slots_from[j] = server.cluster->slots[j];
        }
    }
A
antirez 已提交
3905
    if (update_config) clusterSaveConfigOrDie(1);
3906
    return C_OK;
3907 3908
}

3909 3910 3911 3912
/* -----------------------------------------------------------------------------
 * SLAVE nodes handling
 * -------------------------------------------------------------------------- */

3913 3914
/* Set the specified node 'n' as master for this node.
 * If this node is currently a master, it is turned into a slave. */
3915
void clusterSetMaster(clusterNode *n) {
A
antirez 已提交
3916 3917
    serverAssert(n != myself);
    serverAssert(myself->numslots == 0);
3918

3919
    if (nodeIsMaster(myself)) {
3920
        myself->flags &= ~(CLUSTER_NODE_MASTER|CLUSTER_NODE_MIGRATE_TO);
A
antirez 已提交
3921
        myself->flags |= CLUSTER_NODE_SLAVE;
3922
        clusterCloseAllSlots();
3923 3924 3925
    } else {
        if (myself->slaveof)
            clusterNodeRemoveSlave(myself->slaveof,myself);
3926 3927
    }
    myself->slaveof = n;
3928
    clusterNodeAddSlave(n,myself);
3929
    replicationSetMaster(n->ip, n->port);
3930
    resetManualFailover();
3931 3932
}

A
antirez 已提交
3933
/* -----------------------------------------------------------------------------
3934
 * Nodes to string representation functions.
A
antirez 已提交
3935 3936
 * -------------------------------------------------------------------------- */

3937 3938 3939 3940 3941 3942
struct redisNodeFlags {
    uint16_t flag;
    char *name;
};

static struct redisNodeFlags redisNodeFlagsTable[] = {
3943 3944 3945 3946 3947 3948
    {CLUSTER_NODE_MYSELF,       "myself,"},
    {CLUSTER_NODE_MASTER,       "master,"},
    {CLUSTER_NODE_SLAVE,        "slave,"},
    {CLUSTER_NODE_PFAIL,        "fail?,"},
    {CLUSTER_NODE_FAIL,         "fail,"},
    {CLUSTER_NODE_HANDSHAKE,    "handshake,"},
3949 3950
    {CLUSTER_NODE_NOADDR,       "noaddr,"},
    {CLUSTER_NODE_NOFAILOVER,   "nofailover,"}
3951 3952 3953 3954
};

/* Concatenate the comma separated list of node flags to the given SDS
 * string 'ci'. */
3955
sds representClusterNodeFlags(sds ci, uint16_t flags) {
3956 3957 3958 3959 3960 3961 3962 3963
    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,");
3964 3965 3966 3967
    sdsIncrLen(ci,-1); /* Remove trailing comma. */
    return ci;
}

3968 3969 3970
/* Generate a csv-alike representation of the specified cluster node.
 * See clusterGenNodesDescription() top comment for more information.
 *
3971 3972
 * The function returns the string representation as an SDS string. */
sds clusterGenNodeDescription(clusterNode *node) {
3973
    int j, start;
3974
    sds ci;
3975 3976

    /* Node coordinates */
3977
    ci = sdscatprintf(sdsempty(),"%.40s %s:%d@%d ",
3978 3979
        node->name,
        node->ip,
3980 3981
        node->port,
        node->cport);
3982 3983

    /* Flags */
3984
    ci = representClusterNodeFlags(ci, node->flags);
3985 3986

    /* Slave of... or just "-" */
3987 3988 3989
    if (node->slaveof)
        ci = sdscatprintf(ci," %.40s ",node->slaveof->name);
    else
3990
        ci = sdscatlen(ci," - ",3);
3991

A
antirez 已提交
3992
    /* Latency from the POV of this node, config epoch, link status */
3993
    ci = sdscatprintf(ci,"%lld %lld %llu %s",
3994 3995 3996
        (long long) node->ping_sent,
        (long long) node->pong_received,
        (unsigned long long) node->configEpoch,
A
antirez 已提交
3997
        (node->link || node->flags & CLUSTER_NODE_MYSELF) ?
3998 3999 4000 4001
                    "connected" : "disconnected");

    /* Slots served by this instance */
    start = -1;
A
antirez 已提交
4002
    for (j = 0; j < CLUSTER_SLOTS; j++) {
4003 4004 4005 4006 4007
        int bit;

        if ((bit = clusterNodeGetSlotBit(node,j)) != 0) {
            if (start == -1) start = j;
        }
A
antirez 已提交
4008 4009
        if (start != -1 && (!bit || j == CLUSTER_SLOTS-1)) {
            if (bit && j == CLUSTER_SLOTS-1) j++;
4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022

            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 已提交
4023 4024
    if (node->flags & CLUSTER_NODE_MYSELF) {
        for (j = 0; j < CLUSTER_SLOTS; j++) {
4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036
            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;
}

4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049
/* 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) {
4050
    sds ci = sdsempty(), ni;
A
antirez 已提交
4051 4052 4053
    dictIterator *di;
    dictEntry *de;

4054
    di = dictGetSafeIterator(server.cluster->nodes);
A
antirez 已提交
4055
    while((de = dictNext(di)) != NULL) {
4056
        clusterNode *node = dictGetVal(de);
A
antirez 已提交
4057

4058
        if (node->flags & filter) continue;
4059 4060 4061
        ni = clusterGenNodeDescription(node);
        ci = sdscatsds(ci,ni);
        sdsfree(ni);
4062
        ci = sdscatlen(ci,"\n",1);
A
antirez 已提交
4063 4064 4065 4066 4067
    }
    dictReleaseIterator(di);
    return ci;
}

4068 4069 4070 4071
/* -----------------------------------------------------------------------------
 * CLUSTER command
 * -------------------------------------------------------------------------- */

4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082
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";
4083
    case CLUSTERMSG_TYPE_MODULE: return "module";
4084 4085 4086 4087
    }
    return "unknown";
}

4088
int getSlotOrReply(client *c, robj *o) {
4089 4090
    long long slot;

4091
    if (getLongLongFromObject(o,&slot) != C_OK ||
A
antirez 已提交
4092
        slot < 0 || slot >= CLUSTER_SLOTS)
4093 4094 4095 4096 4097 4098 4099
    {
        addReplyError(c,"Invalid or out of range slot");
        return -1;
    }
    return (int) slot;
}

4100
void clusterReplyMultiBulkSlots(client *c) {
4101 4102 4103 4104
    /* Format: 1) 1) start slot
     *            2) end slot
     *            3) 1) master IP
     *               2) master port
4105
     *               3) node ID
4106 4107
     *            4) 1) replica IP
     *               2) replica port
4108
     *               3) node ID
4109 4110 4111
     *           ... continued until done
     */

4112 4113
    int num_masters = 0;
    void *slot_replylen = addDeferredMultiBulkLength(c);
4114 4115 4116 4117 4118 4119 4120

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

4121 4122 4123
        /* 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;
4124

A
antirez 已提交
4125
        for (j = 0; j < CLUSTER_SLOTS; j++) {
4126
            int bit, i;
4127 4128 4129 4130

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

A
antirez 已提交
4135
                if (bit && j == CLUSTER_SLOTS-1) j++;
4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148

                /* 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 */
4149
                addReplyMultiBulkLen(c, 3);
4150 4151
                addReplyBulkCString(c, node->ip);
                addReplyLongLong(c, node->port);
4152
                addReplyBulkCBuffer(c, node->name, CLUSTER_NAMELEN);
4153 4154 4155 4156 4157

                /* 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 */
4158
                    if (nodeFailed(node->slaves[i])) continue;
4159
                    addReplyMultiBulkLen(c, 3);
4160 4161
                    addReplyBulkCString(c, node->slaves[i]->ip);
                    addReplyLongLong(c, node->slaves[i]->port);
4162
                    addReplyBulkCBuffer(c, node->slaves[i]->name, CLUSTER_NAMELEN);
4163
                    nested_elements++;
4164
                }
4165 4166
                setDeferredMultiBulkLength(c, nested_replylen, nested_elements);
                num_masters++;
4167 4168 4169 4170
            }
        }
    }
    dictReleaseIterator(di);
4171
    setDeferredMultiBulkLength(c, slot_replylen, num_masters);
4172 4173
}

4174
void clusterCommand(client *c) {
A
antirez 已提交
4175 4176 4177 4178 4179
    if (server.cluster_enabled == 0) {
        addReplyError(c,"This instance has cluster support disabled");
        return;
    }

I
Itamar Haber 已提交
4180 4181
    if (c->argc == 2 && !strcasecmp(c->argv[1]->ptr,"help")) {
        const char *help[] = {
4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195
"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.",
"FAILOVER [force|takeover] -- Promote current slave node to being a master.",
"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:",
4196
"    <id> <ip:port> <flags> <master> <pings> <pongs> <epoch> <link> <slot> ... <slot>",
4197 4198 4199 4200 4201 4202
"REPLICATE <node-id> -- Configure current node as slave to <node-id>.",
"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.",
"SLAVES <node-id> -- Return <node-id> slaves.",
"SLOTS -- Return information about slots range mappings. Each range is made of:",
4203 4204
"    start, end, master and replicas IP addresses, ports and ids",
NULL
I
Itamar Haber 已提交
4205 4206 4207
        };
        addReplyHelp(c, help);
    } else if (!strcasecmp(c->argv[1]->ptr,"meet") && (c->argc == 4 || c->argc == 5)) {
4208 4209
        /* CLUSTER MEET <ip> <port> [cport] */
        long long port, cport;
A
antirez 已提交
4210

4211
        if (getLongLongFromObject(c->argv[3], &port) != C_OK) {
4212
            addReplyErrorFormat(c,"Invalid TCP base port specified: %s",
4213
                                (char*)c->argv[3]->ptr);
A
antirez 已提交
4214 4215 4216
            return;
        }

4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227
        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 &&
4228 4229
            errno == EINVAL)
        {
4230 4231
            addReplyErrorFormat(c,"Invalid node address specified: %s:%s",
                            (char*)c->argv[2]->ptr, (char*)c->argv[3]->ptr);
4232 4233 4234
        } else {
            addReply(c,shared.ok);
        }
A
antirez 已提交
4235
    } else if (!strcasecmp(c->argv[1]->ptr,"nodes") && c->argc == 2) {
4236
        /* CLUSTER NODES */
A
antirez 已提交
4237
        robj *o;
4238
        sds ci = clusterGenNodesDescription(0);
A
antirez 已提交
4239

4240
        o = createObject(OBJ_STRING,ci);
A
antirez 已提交
4241 4242
        addReplyBulk(c,o);
        decrRefCount(o);
M
Michel Martens 已提交
4243 4244
    } else if (!strcasecmp(c->argv[1]->ptr,"myid") && c->argc == 2) {
        /* CLUSTER MYID */
A
antirez 已提交
4245
        addReplyBulkCBuffer(c,myself->name, CLUSTER_NAMELEN);
4246 4247 4248
    } else if (!strcasecmp(c->argv[1]->ptr,"slots") && c->argc == 2) {
        /* CLUSTER SLOTS */
        clusterReplyMultiBulkSlots(c);
4249 4250 4251 4252 4253 4254
    } 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;
        }
4255
        clusterDelNodeSlots(myself);
A
antirez 已提交
4256
        clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
4257
        addReply(c,shared.ok);
A
antirez 已提交
4258
    } else if ((!strcasecmp(c->argv[1]->ptr,"addslots") ||
A
antirez 已提交
4259 4260 4261 4262
               !strcasecmp(c->argv[1]->ptr,"delslots")) && c->argc >= 3)
    {
        /* CLUSTER ADDSLOTS <slot> [slot] ... */
        /* CLUSTER DELSLOTS <slot> [slot] ... */
4263
        int j, slot;
A
antirez 已提交
4264
        unsigned char *slots = zmalloc(CLUSTER_SLOTS);
A
antirez 已提交
4265
        int del = !strcasecmp(c->argv[1]->ptr,"delslots");
A
antirez 已提交
4266

A
antirez 已提交
4267
        memset(slots,0,CLUSTER_SLOTS);
4268
        /* Check that all the arguments are parseable and that all the
A
antirez 已提交
4269 4270
         * slots are not already busy. */
        for (j = 2; j < c->argc; j++) {
4271
            if ((slot = getSlotOrReply(c,c->argv[j])) == -1) {
A
antirez 已提交
4272 4273 4274
                zfree(slots);
                return;
            }
4275
            if (del && server.cluster->slots[slot] == NULL) {
4276
                addReplyErrorFormat(c,"Slot %d is already unassigned", slot);
A
antirez 已提交
4277 4278
                zfree(slots);
                return;
4279
            } else if (!del && server.cluster->slots[slot]) {
4280
                addReplyErrorFormat(c,"Slot %d is already busy", slot);
A
antirez 已提交
4281 4282 4283 4284 4285 4286 4287 4288 4289 4290
                zfree(slots);
                return;
            }
            if (slots[slot]++ == 1) {
                addReplyErrorFormat(c,"Slot %d specified multiple times",
                    (int)slot);
                zfree(slots);
                return;
            }
        }
A
antirez 已提交
4291
        for (j = 0; j < CLUSTER_SLOTS; j++) {
A
antirez 已提交
4292
            if (slots[j]) {
4293 4294
                int retval;

4295
                /* If this slot was set as importing we can clear this
4296
                 * state as now we are the real owner of the slot. */
4297 4298
                if (server.cluster->importing_slots_from[j])
                    server.cluster->importing_slots_from[j] = NULL;
4299 4300

                retval = del ? clusterDelSlot(j) :
4301
                               clusterAddSlot(myself,j);
4302
                serverAssertWithInfo(c,NULL,retval == C_OK);
A
antirez 已提交
4303 4304 4305
            }
        }
        zfree(slots);
A
antirez 已提交
4306
        clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
A
antirez 已提交
4307
        addReply(c,shared.ok);
4308
    } else if (!strcasecmp(c->argv[1]->ptr,"setslot") && c->argc >= 4) {
A
antirez 已提交
4309 4310
        /* SETSLOT 10 MIGRATING <node ID> */
        /* SETSLOT 10 IMPORTING <node ID> */
4311
        /* SETSLOT 10 STABLE */
A
antirez 已提交
4312
        /* SETSLOT 10 NODE <node ID> */
4313
        int slot;
4314 4315
        clusterNode *n;

4316 4317 4318 4319 4320
        if (nodeIsSlave(myself)) {
            addReplyError(c,"Please use SETSLOT only with masters.");
            return;
        }

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

4323
        if (!strcasecmp(c->argv[3]->ptr,"migrating") && c->argc == 5) {
4324
            if (server.cluster->slots[slot] != myself) {
4325 4326 4327
                addReplyErrorFormat(c,"I'm not the owner of hash slot %u",slot);
                return;
            }
4328 4329 4330 4331 4332
            if ((n = clusterLookupNode(c->argv[4]->ptr)) == NULL) {
                addReplyErrorFormat(c,"I don't know about node %s",
                    (char*)c->argv[4]->ptr);
                return;
            }
4333
            server.cluster->migrating_slots_to[slot] = n;
4334
        } else if (!strcasecmp(c->argv[3]->ptr,"importing") && c->argc == 5) {
4335
            if (server.cluster->slots[slot] == myself) {
4336 4337 4338 4339
                addReplyErrorFormat(c,
                    "I'm already the owner of hash slot %u",slot);
                return;
            }
4340 4341
            if ((n = clusterLookupNode(c->argv[4]->ptr)) == NULL) {
                addReplyErrorFormat(c,"I don't know about node %s",
L
Leon Chen 已提交
4342
                    (char*)c->argv[4]->ptr);
4343 4344
                return;
            }
4345
            server.cluster->importing_slots_from[slot] = n;
4346
        } else if (!strcasecmp(c->argv[3]->ptr,"stable") && c->argc == 4) {
4347
            /* CLUSTER SETSLOT <SLOT> STABLE */
4348 4349
            server.cluster->importing_slots_from[slot] = NULL;
            server.cluster->migrating_slots_to[slot] = NULL;
4350
        } else if (!strcasecmp(c->argv[3]->ptr,"node") && c->argc == 5) {
4351 4352 4353
            /* CLUSTER SETSLOT <SLOT> NODE <NODE ID> */
            clusterNode *n = clusterLookupNode(c->argv[4]->ptr);

4354 4355 4356 4357 4358
            if (!n) {
                addReplyErrorFormat(c,"Unknown node %s",
                    (char*)c->argv[4]->ptr);
                return;
            }
4359 4360
            /* If this hash slot was served by 'myself' before to switch
             * make sure there are no longer local keys for this hash slot. */
4361
            if (server.cluster->slots[slot] == myself && n != myself) {
4362
                if (countKeysInSlot(slot) != 0) {
A
antirez 已提交
4363 4364 4365
                    addReplyErrorFormat(c,
                        "Can't assign hashslot %d to a different node "
                        "while I still hold keys for this hash slot.", slot);
4366 4367 4368
                    return;
                }
            }
4369 4370
            /* If this slot is in migrating status but we have no keys
             * for it assigning the slot to another node will clear
4371
             * the migratig status. */
4372
            if (countKeysInSlot(slot) == 0 &&
4373 4374
                server.cluster->migrating_slots_to[slot])
                server.cluster->migrating_slots_to[slot] = NULL;
4375

4376 4377
            /* If this node was importing this slot, assigning the slot to
             * itself also clears the importing status. */
4378
            if (n == myself &&
4379
                server.cluster->importing_slots_from[slot])
4380 4381
            {
                /* This slot was manually migrated, set this node configEpoch
4382 4383 4384
                 * to a new epoch so that the new version can be propagated
                 * by the cluster.
                 *
4385 4386 4387 4388 4389
                 * 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. */
4390
                if (clusterBumpConfigEpochWithoutConsensus() == C_OK) {
A
antirez 已提交
4391
                    serverLog(LL_WARNING,
4392
                        "configEpoch updated after importing slot %d", slot);
4393
                }
4394
                server.cluster->importing_slots_from[slot] = NULL;
4395
            }
4396 4397
            clusterDelSlot(slot);
            clusterAddSlot(n,slot);
4398
        } else {
A
antirez 已提交
4399
            addReplyError(c,
4400
                "Invalid CLUSTER SETSLOT action or number of arguments. Try CLUSTER HELP");
4401
            return;
4402
        }
4403
        clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|CLUSTER_TODO_UPDATE_STATE);
4404
        addReply(c,shared.ok);
4405 4406 4407 4408 4409 4410 4411
    } 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 已提交
4412
    } else if (!strcasecmp(c->argv[1]->ptr,"info") && c->argc == 2) {
4413
        /* CLUSTER INFO */
A
antirez 已提交
4414 4415
        char *statestr[] = {"ok","fail","needhelp"};
        int slots_assigned = 0, slots_ok = 0, slots_pfail = 0, slots_fail = 0;
4416
        uint64_t myepoch;
A
antirez 已提交
4417 4418
        int j;

A
antirez 已提交
4419
        for (j = 0; j < CLUSTER_SLOTS; j++) {
4420
            clusterNode *n = server.cluster->slots[j];
A
antirez 已提交
4421 4422 4423

            if (n == NULL) continue;
            slots_assigned++;
4424
            if (nodeFailed(n)) {
A
antirez 已提交
4425
                slots_fail++;
4426
            } else if (nodeTimedOut(n)) {
A
antirez 已提交
4427 4428 4429 4430 4431 4432
                slots_pfail++;
            } else {
                slots_ok++;
            }
        }

4433 4434 4435
        myepoch = (nodeIsSlave(myself) && myself->slaveof) ?
                  myself->slaveof->configEpoch : myself->configEpoch;

A
antirez 已提交
4436 4437 4438 4439 4440 4441
        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"
4442
            "cluster_known_nodes:%lu\r\n"
4443
            "cluster_size:%d\r\n"
4444
            "cluster_current_epoch:%llu\r\n"
4445
            "cluster_my_epoch:%llu\r\n"
4446
            , statestr[server.cluster->state],
A
antirez 已提交
4447 4448 4449
            slots_assigned,
            slots_ok,
            slots_pfail,
4450
            slots_fail,
4451
            dictSize(server.cluster->nodes),
4452
            server.cluster->size,
4453
            (unsigned long long) server.cluster->currentEpoch,
4454
            (unsigned long long) myepoch
A
antirez 已提交
4455
        );
4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483

        /* 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. */
4484 4485 4486 4487
        addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
            (unsigned long)sdslen(info)));
        addReplySds(c,info);
        addReply(c,shared.crlf);
4488
    } else if (!strcasecmp(c->argv[1]->ptr,"saveconfig") && c->argc == 2) {
A
antirez 已提交
4489
        int retval = clusterSaveConfig(1);
4490 4491 4492 4493 4494 4495

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

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

4505
        if (getLongLongFromObjectOrReply(c,c->argv[2],&slot,NULL) != C_OK)
4506
            return;
A
antirez 已提交
4507
        if (slot < 0 || slot >= CLUSTER_SLOTS) {
4508 4509 4510
            addReplyError(c,"Invalid slot");
            return;
        }
4511
        addReplyLongLong(c,countKeysInSlot(slot));
A
antirez 已提交
4512
    } else if (!strcasecmp(c->argv[1]->ptr,"getkeysinslot") && c->argc == 4) {
4513
        /* CLUSTER GETKEYSINSLOT <slot> <count> */
A
antirez 已提交
4514
        long long maxkeys, slot;
4515
        unsigned int numkeys, j;
A
antirez 已提交
4516 4517
        robj **keys;

4518
        if (getLongLongFromObjectOrReply(c,c->argv[2],&slot,NULL) != C_OK)
A
antirez 已提交
4519
            return;
A
antirez 已提交
4520
        if (getLongLongFromObjectOrReply(c,c->argv[3],&maxkeys,NULL)
4521
            != C_OK)
A
antirez 已提交
4522
            return;
A
antirez 已提交
4523
        if (slot < 0 || slot >= CLUSTER_SLOTS || maxkeys < 0) {
A
antirez 已提交
4524 4525 4526 4527
            addReplyError(c,"Invalid slot or number of keys");
            return;
        }

4528 4529 4530 4531 4532
        /* 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 已提交
4533
        keys = zmalloc(sizeof(robj*)*maxkeys);
4534
        numkeys = getKeysInSlot(slot, keys, maxkeys);
A
antirez 已提交
4535
        addReplyMultiBulkLen(c,numkeys);
4536 4537 4538 4539
        for (j = 0; j < numkeys; j++) {
            addReplyBulk(c,keys[j]);
            decrRefCount(keys[j]);
        }
A
antirez 已提交
4540
        zfree(keys);
A
antirez 已提交
4541 4542 4543 4544
    } else if (!strcasecmp(c->argv[1]->ptr,"forget") && c->argc == 3) {
        /* CLUSTER FORGET <NODE ID> */
        clusterNode *n = clusterLookupNode(c->argv[2]->ptr);

4545
        if (!n) {
A
antirez 已提交
4546 4547
            addReplyErrorFormat(c,"Unknown node %s", (char*)c->argv[2]->ptr);
            return;
4548
        } else if (n == myself) {
4549 4550
            addReplyError(c,"I tried hard but I can't forget myself...");
            return;
4551
        } else if (nodeIsSlave(myself) && myself->slaveof == n) {
4552 4553
            addReplyError(c,"Can't forget my master!");
            return;
A
antirez 已提交
4554
        }
4555
        clusterBlacklistAddNode(n);
A
antirez 已提交
4556
        clusterDelNode(n);
A
antirez 已提交
4557 4558
        clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|
                             CLUSTER_TODO_SAVE_CONFIG);
A
antirez 已提交
4559
        addReply(c,shared.ok);
4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570
    } 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. */
4571
        if (n == myself) {
4572 4573 4574 4575 4576
            addReplyError(c,"Can't replicate myself");
            return;
        }

        /* Can't replicate a slave. */
4577
        if (nodeIsSlave(n)) {
4578 4579 4580 4581
            addReplyError(c,"I can only replicate a master, not a slave.");
            return;
        }

4582 4583 4584
        /* 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. */
4585 4586
        if (nodeIsMaster(myself) &&
            (myself->numslots != 0 || dictSize(server.db[0].dict) != 0)) {
A
antirez 已提交
4587 4588 4589
            addReplyError(c,
                "To set a master the node must be empty and "
                "without assigned slots.");
4590 4591 4592 4593 4594
            return;
        }

        /* Set the master. */
        clusterSetMaster(n);
A
antirez 已提交
4595
        clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
4596
        addReply(c,shared.ok);
4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607
    } else if (!strcasecmp(c->argv[1]->ptr,"slaves") && c->argc == 3) {
        /* 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;
        }

4608
        if (nodeIsSlave(n)) {
4609 4610 4611 4612 4613 4614
            addReplyError(c,"The specified node is not a master");
            return;
        }

        addReplyMultiBulkLen(c,n->numslaves);
        for (j = 0; j < n->numslaves; j++) {
4615
            sds ni = clusterGenNodeDescription(n->slaves[j]);
4616 4617 4618
            addReplyBulkCString(c,ni);
            sdsfree(ni);
        }
4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630
    } 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 已提交
4631 4632 4633
    } else if (!strcasecmp(c->argv[1]->ptr,"failover") &&
               (c->argc == 2 || c->argc == 3))
    {
4634 4635
        /* CLUSTER FAILOVER [FORCE|TAKEOVER] */
        int force = 0, takeover = 0;
A
antirez 已提交
4636 4637 4638 4639

        if (c->argc == 3) {
            if (!strcasecmp(c->argv[2]->ptr,"force")) {
                force = 1;
4640 4641 4642
            } else if (!strcasecmp(c->argv[2]->ptr,"takeover")) {
                takeover = 1;
                force = 1; /* Takeover also implies force. */
A
antirez 已提交
4643 4644 4645 4646 4647 4648
            } else {
                addReply(c,shared.syntaxerr);
                return;
            }
        }

4649
        /* Check preconditions. */
4650 4651 4652
        if (nodeIsMaster(myself)) {
            addReplyError(c,"You should send CLUSTER FAILOVER to a slave");
            return;
4653 4654 4655
        } else if (myself->slaveof == NULL) {
            addReplyError(c,"I'm a slave but my master is unknown to me");
            return;
A
antirez 已提交
4656
        } else if (!force &&
4657 4658
                   (nodeFailed(myself->slaveof) ||
                    myself->slaveof->link == NULL))
4659 4660 4661 4662 4663 4664
        {
            addReplyError(c,"Master is down or failed, "
                            "please use CLUSTER FAILOVER FORCE");
            return;
        }
        resetManualFailover();
A
antirez 已提交
4665
        server.cluster->mf_end = mstime() + CLUSTER_MF_TIMEOUT;
A
antirez 已提交
4666

4667 4668 4669 4670 4671
        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 已提交
4672
            serverLog(LL_WARNING,"Taking over the master (user request).");
4673 4674 4675 4676 4677 4678
            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 已提交
4679
            serverLog(LL_WARNING,"Forced failover user request accepted.");
A
antirez 已提交
4680 4681
            server.cluster->mf_can_start = 1;
        } else {
A
antirez 已提交
4682
            serverLog(LL_WARNING,"Manual failover user request accepted.");
A
antirez 已提交
4683 4684
            clusterSendMFStart(myself->slaveof);
        }
4685
        addReply(c,shared.ok);
A
antirez 已提交
4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696
    } 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;

4697
        if (getLongLongFromObjectOrReply(c,c->argv[2],&epoch,NULL) != C_OK)
A
antirez 已提交
4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708
            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 已提交
4709
            serverLog(LL_WARNING,
4710 4711 4712
                "configEpoch set to %llu via CLUSTER SET-CONFIG-EPOCH",
                (unsigned long long) myself->configEpoch);

4713
            if (server.cluster->currentEpoch < (uint64_t)epoch)
4714
                server.cluster->currentEpoch = epoch;
A
antirez 已提交
4715 4716 4717 4718 4719 4720 4721
            /* 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 已提交
4722 4723 4724 4725 4726 4727 4728 4729 4730 4731
    } 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;
4732
            } else if (!strcasecmp(c->argv[2]->ptr,"soft")) {
A
antirez 已提交
4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748
                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 已提交
4749
    } else {
4750
        addReplySubcommandSyntaxError(c);
I
Itamar Haber 已提交
4751
        return;
A
antirez 已提交
4752 4753 4754 4755
    }
}

/* -----------------------------------------------------------------------------
4756
 * DUMP, RESTORE and MIGRATE commands
A
antirez 已提交
4757 4758
 * -------------------------------------------------------------------------- */

4759 4760 4761
/* 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) {
4762 4763
    unsigned char buf[2];
    uint64_t crc;
4764 4765 4766 4767

    /* 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 已提交
4768 4769
    serverAssert(rdbSaveObjectType(payload,o));
    serverAssert(rdbSaveObject(payload,o));
4770 4771

    /* Write the footer, this is how it looks like:
4772 4773 4774 4775 4776
     * ----------------+---------------------+---------------+
     * ... RDB payload | 2 bytes RDB version | 8 bytes CRC64 |
     * ----------------+---------------------+---------------+
     * RDB version and CRC are both in little endian.
     */
4777 4778

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

4783
    /* CRC64 */
4784
    crc = crc64(0,(unsigned char*)payload->io.buffer.ptr,
4785 4786 4787
                sdslen(payload->io.buffer.ptr));
    memrev64ifbe(&crc);
    payload->io.buffer.ptr = sdscatlen(payload->io.buffer.ptr,&crc,8);
4788 4789 4790
}

/* Verify that the RDB version of the dump payload matches the one of this Redis
4791
 * instance and that the checksum is ok.
4792
 * If the DUMP payload looks valid C_OK is returned, otherwise C_ERR
4793 4794
 * is returned. */
int verifyDumpPayload(unsigned char *p, size_t len) {
4795
    unsigned char *footer;
4796
    uint16_t rdbver;
4797
    uint64_t crc;
4798

4799
    /* At least 2 bytes of RDB version and 8 of CRC64 should be present. */
4800
    if (len < 10) return C_ERR;
4801
    footer = p+(len-10);
4802 4803

    /* Verify RDB version */
4804
    rdbver = (footer[1] << 8) | footer[0];
4805
    if (rdbver > RDB_VERSION) return C_ERR;
4806

4807
    /* Verify CRC64 */
4808
    crc = crc64(0,p,len-8);
4809
    memrev64ifbe(&crc);
4810
    return (memcmp(&crc,footer+2,8) == 0) ? C_OK : C_ERR;
4811 4812 4813 4814 4815
}

/* 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. */
4816
void dumpCommand(client *c) {
4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829
    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 */
4830
    dumpobj = createObject(OBJ_STRING,payload.io.buffer.ptr);
4831 4832 4833 4834 4835
    addReplyBulk(c,dumpobj);
    decrRefCount(dumpobj);
    return;
}

A
antirez 已提交
4836
/* RESTORE key ttl serialized-value [REPLACE] */
4837
void restoreCommand(client *c) {
4838
    long long ttl, lfu_freq = -1, lru_idle = -1, lru_clock = -1;
4839
    rio payload;
4840
    int j, type, replace = 0, absttl = 0;
4841
    robj *obj;
A
antirez 已提交
4842

A
antirez 已提交
4843 4844
    /* Parse additional options */
    for (j = 4; j < c->argc; j++) {
4845
        int additional = c->argc-j-1;
A
antirez 已提交
4846 4847
        if (!strcasecmp(c->argv[j]->ptr,"replace")) {
            replace = 1;
4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870
        } 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 已提交
4871 4872 4873 4874 4875 4876
        } else {
            addReply(c,shared.syntaxerr);
            return;
        }
    }

A
antirez 已提交
4877
    /* Make sure this key does not already exist here... */
A
antirez 已提交
4878
    if (!replace && lookupKeyWrite(c->db,c->argv[1]) != NULL) {
4879
        addReply(c,shared.busykeyerr);
A
antirez 已提交
4880 4881 4882 4883
        return;
    }

    /* Check if the TTL value makes sense */
4884
    if (getLongLongFromObjectOrReply(c,c->argv[2],&ttl,NULL) != C_OK) {
A
antirez 已提交
4885 4886 4887 4888 4889 4890
        return;
    } else if (ttl < 0) {
        addReplyError(c,"Invalid TTL value, must be >= 0");
        return;
    }

4891
    /* Verify RDB version and data checksum. */
4892
    if (verifyDumpPayload(c->argv[3]->ptr,sdslen(c->argv[3]->ptr)) == C_ERR)
4893
    {
4894 4895 4896 4897
        addReplyError(c,"DUMP payload version or checksum are wrong");
        return;
    }

4898
    rioInitWithBuffer(&payload,c->argv[3]->ptr);
4899 4900
    if (((type = rdbLoadObjectType(&payload)) == -1) ||
        ((obj = rdbLoadObject(type,&payload)) == NULL))
4901
    {
4902
        addReplyError(c,"Bad data format");
A
antirez 已提交
4903 4904 4905
        return;
    }

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

A
antirez 已提交
4909
    /* Create the key and set the TTL if any */
4910
    dbAdd(c->db,c->argv[1],obj);
4911 4912 4913 4914 4915
    if (ttl) {
        if (!absttl) ttl+=mstime();
        setExpire(c,c->db,c->argv[1],ttl);
    }
    objectSetLRUOrLFU(obj,lfu_freq,lru_idle,lru_clock);
4916
    signalModifiedKey(c->db,c->argv[1]);
A
antirez 已提交
4917
    addReply(c,shared.ok);
4918
    server.dirty++;
A
antirez 已提交
4919 4920
}

A
antirez 已提交
4921 4922 4923 4924 4925 4926 4927
/* 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. */
4928
#define MIGRATE_SOCKET_CACHE_TTL 10 /* close cached sockets after 10 sec. */
A
antirez 已提交
4929 4930 4931

typedef struct migrateCachedSocket {
    int fd;
4932
    long last_dbid;
A
antirez 已提交
4933 4934 4935
    time_t last_use_time;
} migrateCachedSocket;

4936 4937
/* Return a migrateCachedSocket containing a TCP socket connected with the
 * target instance, possibly returning a cached one.
A
antirez 已提交
4938 4939 4940 4941 4942 4943 4944
 *
 * 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()
4945
 * should be called so that the connection will be created from scratch
A
antirez 已提交
4946
 * the next time. */
4947
migrateCachedSocket* migrateGetSocket(client *c, robj *host, robj *port, long timeout) {
A
antirez 已提交
4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959
    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;
4960
        return cs;
A
antirez 已提交
4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973
    }

    /* 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 */
4974 4975
    fd = anetTcpNonBlockConnect(server.neterr,c->argv[1]->ptr,
                                atoi(c->argv[2]->ptr));
A
antirez 已提交
4976 4977 4978 4979
    if (fd == -1) {
        sdsfree(name);
        addReplyErrorFormat(c,"Can't connect to target node: %s",
            server.neterr);
4980
        return NULL;
A
antirez 已提交
4981
    }
4982
    anetEnableTcpNoDelay(server.neterr,fd);
A
antirez 已提交
4983 4984

    /* Check if it connects within the specified timeout. */
4985
    if ((aeWait(fd,AE_WRITABLE,timeout) & AE_WRITABLE) == 0) {
A
antirez 已提交
4986
        sdsfree(name);
A
antirez 已提交
4987 4988
        addReplySds(c,
            sdsnew("-IOERR error or timeout connecting to the client\r\n"));
A
antirez 已提交
4989
        close(fd);
4990
        return NULL;
A
antirez 已提交
4991 4992 4993 4994 4995
    }

    /* Add to the cache and return it to the caller. */
    cs = zmalloc(sizeof(*cs));
    cs->fd = fd;
4996
    cs->last_dbid = -1;
A
antirez 已提交
4997 4998
    cs->last_use_time = server.unixtime;
    dictAdd(server.migrate_cached_sockets,name,cs);
4999
    return cs;
A
antirez 已提交
5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037
}

/* 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 已提交
5038
/* MIGRATE host port key dbid timeout [COPY | REPLACE | AUTH password]
A
antirez 已提交
5039 5040 5041
 *
 * On in the multiple keys form:
 *
A
antirez 已提交
5042 5043
 * MIGRATE host port "" dbid timeout [COPY | REPLACE | AUTH password] KEYS key1
 * key2 ... keyN */
5044
void migrateCommand(client *c) {
5045
    migrateCachedSocket *cs;
A
antirez 已提交
5046 5047
    int copy = 0, replace = 0, j;
    char *password = NULL;
A
antirez 已提交
5048 5049
    long timeout;
    long dbid;
A
antirez 已提交
5050 5051 5052
    robj **ov = NULL; /* Objects to migrate. */
    robj **kv = NULL; /* Key names. */
    robj **newargv = NULL; /* Used to rewrite the command as DEL ... keys ... */
5053
    rio cmd, payload;
5054
    int may_retry = 1;
A
antirez 已提交
5055
    int write_error = 0;
5056
    int argv_rewritten = 0;
A
antirez 已提交
5057 5058 5059 5060

    /* 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 已提交
5061

A
antirez 已提交
5062 5063
    /* Parse additional options */
    for (j = 6; j < c->argc; j++) {
A
antirez 已提交
5064
        int moreargs = j < c->argc-1;
A
antirez 已提交
5065 5066 5067 5068
        if (!strcasecmp(c->argv[j]->ptr,"copy")) {
            copy = 1;
        } else if (!strcasecmp(c->argv[j]->ptr,"replace")) {
            replace = 1;
A
antirez 已提交
5069 5070 5071 5072 5073 5074 5075
        } else if (!strcasecmp(c->argv[j]->ptr,"auth")) {
            if (!moreargs) {
                addReply(c,shared.syntaxerr);
                return;
            }
            j++;
            password = c->argv[j]->ptr;
A
antirez 已提交
5076 5077 5078 5079 5080 5081 5082 5083 5084 5085
        } 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 已提交
5086 5087 5088 5089 5090 5091
        } else {
            addReply(c,shared.syntaxerr);
            return;
        }
    }

A
antirez 已提交
5092
    /* Sanity check */
5093 5094 5095
    if (getLongFromObjectOrReply(c,c->argv[5],&timeout,NULL) != C_OK ||
        getLongFromObjectOrReply(c,c->argv[4],&dbid,NULL) != C_OK)
    {
A
antirez 已提交
5096
        return;
5097
    }
5098
    if (timeout <= 0) timeout = 1000;
A
antirez 已提交
5099

A
antirez 已提交
5100 5101 5102 5103 5104
    /* 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 已提交
5105 5106
    ov = zrealloc(ov,sizeof(robj*)*num_keys);
    kv = zrealloc(kv,sizeof(robj*)*num_keys);
A
antirez 已提交
5107
    int oi = 0;
A
antirez 已提交
5108

A
antirez 已提交
5109 5110 5111 5112 5113 5114 5115 5116 5117
    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);
5118
        addReplySds(c,sdsnew("+NOKEY\r\n"));
A
antirez 已提交
5119 5120
        return;
    }
5121

A
antirez 已提交
5122 5123 5124
try_again:
    write_error = 0;

A
antirez 已提交
5125
    /* Connect */
5126
    cs = migrateGetSocket(c,c->argv[1],c->argv[2],timeout);
5127 5128 5129 5130
    if (cs == NULL) {
        zfree(ov); zfree(kv);
        return; /* error sent to the client by migrateGetSocket() */
    }
A
antirez 已提交
5131

5132
    rioInitWithBuffer(&cmd,sdsempty());
5133

A
antirez 已提交
5134 5135 5136 5137 5138 5139 5140 5141
    /* 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 已提交
5142 5143 5144
    /* 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 已提交
5145 5146 5147
        serverAssertWithInfo(c,NULL,rioWriteBulkCount(&cmd,'*',2));
        serverAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,"SELECT",6));
        serverAssertWithInfo(c,NULL,rioWriteBulkLongLong(&cmd,dbid));
5148
    }
A
antirez 已提交
5149

5150 5151 5152 5153
    int expired = 0; /* Number of keys that we'll find already 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 已提交
5154

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

A
antirez 已提交
5160 5161
        if (expireat != -1) {
            ttl = expireat-mstime();
5162 5163 5164 5165
            if (ttl < 0) {
                expired++;
                continue;
            }
A
antirez 已提交
5166 5167
            if (ttl < 1) ttl = 1;
        }
A
antirez 已提交
5168 5169 5170
        serverAssertWithInfo(c,NULL,
            rioWriteBulkCount(&cmd,'*',replace ? 5 : 4));

A
antirez 已提交
5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183
        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 已提交
5184
        serverAssertWithInfo(c,NULL,
A
antirez 已提交
5185 5186 5187 5188 5189 5190 5191 5192 5193
            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));
    }
A
antirez 已提交
5194

G
guiquanz 已提交
5195
    /* Transfer the query to the other node in 64K chunks. */
A
antirez 已提交
5196
    errno = 0;
A
antirez 已提交
5197
    {
5198 5199
        sds buf = cmd.io.buffer.ptr;
        size_t pos = 0, towrite;
5200
        int nwritten = 0;
5201 5202 5203

        while ((towrite = sdslen(buf)-pos) > 0) {
            towrite = (towrite > (64*1024) ? (64*1024) : towrite);
5204
            nwritten = syncWrite(cs->fd,buf+pos,towrite,timeout);
A
antirez 已提交
5205 5206 5207 5208
            if (nwritten != (signed)towrite) {
                write_error = 1;
                goto socket_err;
            }
5209
            pos += nwritten;
A
antirez 已提交
5210 5211 5212
        }
    }

A
antirez 已提交
5213
    char buf0[1024]; /* Auth reply. */
A
antirez 已提交
5214 5215
    char buf1[1024]; /* Select reply. */
    char buf2[1024]; /* Restore reply. */
A
antirez 已提交
5216

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

A
antirez 已提交
5221 5222 5223 5224 5225 5226
    /* 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;
5227
    int socket_error = 0;
5228 5229
    int del_idx = 1; /* Index of the key argument for the replicated DEL op. */

5230 5231 5232 5233
    /* 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. */
5234
    if (!copy) newargv = zmalloc(sizeof(robj*)*(num_keys+1));
5235

5236
    for (j = 0; j < num_keys-expired; j++) {
5237 5238 5239 5240
        if (syncReadLine(cs->fd, buf2, sizeof(buf2), timeout) <= 0) {
            socket_error = 1;
            break;
        }
5241 5242 5243 5244
        if ((password && buf0[0] == '-') ||
            (select && buf1[0] == '-') ||
            buf2[0] == '-')
        {
A
antirez 已提交
5245
            /* On error assume that last_dbid is no longer valid. */
5246 5247
            if (!error_from_target) {
                cs->last_dbid = -1;
A
antirez 已提交
5248
                char *errbuf;
5249
                if (password && buf0[0] == '-') errbuf = buf0;
A
antirez 已提交
5250 5251 5252
                else if (select && buf1[0] == '-') errbuf = buf1;
                else errbuf = buf2;

5253
                error_from_target = 1;
A
antirez 已提交
5254 5255
                addReplyErrorFormat(c,"Target instance replied with error: %s",
                    errbuf+1);
5256
            }
A
antirez 已提交
5257
        } else {
A
antirez 已提交
5258 5259
            if (!copy) {
                /* No COPY option: remove the local key, signal the change. */
A
antirez 已提交
5260 5261
                dbDelete(c->db,kv[j]);
                signalModifiedKey(c->db,kv[j]);
A
antirez 已提交
5262
                server.dirty++;
5263

5264 5265
                /* Populate the argument vector to replace the old one. */
                newargv[del_idx++] = kv[j];
5266
                incrRefCount(kv[j]);
5267
            }
A
antirez 已提交
5268 5269 5270
        }
    }

5271 5272 5273 5274 5275 5276 5277 5278 5279
    /* 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.*/
    }

5280 5281 5282 5283 5284
    /* 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]);

5285
    if (!copy) {
5286 5287 5288
        /* 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. */
5289 5290
        if (del_idx > 1) {
            newargv[0] = createStringObject("DEL",3);
5291
            /* Note that the following call takes ownership of newargv. */
5292
            replaceClientCommandVector(c,del_idx,newargv);
5293
            argv_rewritten = 1;
5294 5295 5296 5297
        } else {
            /* No key transfer acknowledged, no need to rewrite as DEL. */
            zfree(newargv);
        }
5298 5299 5300 5301
        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.
5302 5303
     * 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. */
5304 5305 5306
    if (!error_from_target && socket_error) {
        may_retry = 0;
        goto socket_err;
5307 5308
    }

A
antirez 已提交
5309
    if (!error_from_target) {
A
antirez 已提交
5310
        /* Success! Update the last_dbid in migrateCachedSocket, so that we can
5311 5312 5313 5314 5315
         * 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 已提交
5316 5317 5318
        cs->last_dbid = dbid;
        addReply(c,shared.ok);
    } else {
5319
        /* On error we already sent it in the for loop above, and set
A
antirez 已提交
5320
         * the currently selected socket to -1 to force SELECT the next time. */
A
antirez 已提交
5321
    }
A
antirez 已提交
5322

5323
    sdsfree(cmd.io.buffer.ptr);
5324
    zfree(ov); zfree(kv); zfree(newargv);
5325
    return;
A
antirez 已提交
5326

A
antirez 已提交
5327 5328 5329 5330
/* 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 已提交
5331 5332
    /* Cleanup we want to perform in both the retry and no retry case.
     * Note: Closing the migrate socket will also force SELECT next time. */
5333
    sdsfree(cmd.io.buffer.ptr);
5334 5335 5336 5337 5338 5339

    /* 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 已提交
5340 5341 5342 5343 5344
    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). */
5345 5346 5347 5348
    if (errno != ETIMEDOUT && may_retry) {
        may_retry = 0;
        goto try_again;
    }
A
antirez 已提交
5349 5350 5351

    /* Cleanup we want to do if no retry is attempted. */
    zfree(ov); zfree(kv);
A
antirez 已提交
5352
    addReplySds(c,
A
antirez 已提交
5353 5354 5355
        sdscatprintf(sdsempty(),
            "-IOERR error or timeout %s to target instance\r\n",
            write_error ? "writing" : "reading"));
5356 5357 5358
    return;
}

5359 5360 5361 5362
/* -----------------------------------------------------------------------------
 * Cluster functions related to serving / redirecting clients
 * -------------------------------------------------------------------------- */

5363
/* The ASKING command is required after a -ASK redirection.
G
guiquanz 已提交
5364
 * The client should issue ASKING before to actually send the command to
5365 5366
 * the target instance. See the Redis Cluster specification for more
 * information. */
5367
void askingCommand(client *c) {
5368 5369 5370 5371
    if (server.cluster_enabled == 0) {
        addReplyError(c,"This instance has cluster support disabled");
        return;
    }
A
antirez 已提交
5372
    c->flags |= CLIENT_ASKING;
5373 5374 5375
    addReply(c,shared.ok);
}

5376
/* The READONLY command is used by clients to enter the read-only mode.
5377 5378
 * 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. */
5379
void readonlyCommand(client *c) {
5380 5381 5382 5383
    if (server.cluster_enabled == 0) {
        addReplyError(c,"This instance has cluster support disabled");
        return;
    }
A
antirez 已提交
5384
    c->flags |= CLIENT_READONLY;
5385 5386 5387 5388
    addReply(c,shared.ok);
}

/* The READWRITE command just clears the READONLY command state. */
5389
void readwriteCommand(client *c) {
A
antirez 已提交
5390
    c->flags &= ~CLIENT_READONLY;
5391 5392
    addReply(c,shared.ok);
}
A
antirez 已提交
5393

5394
/* Return the pointer to the cluster node that is able to serve the command.
5395
 * For the function to succeed the command should only target either:
A
antirez 已提交
5396
 *
5397 5398 5399
 * 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).
5400
 *
5401 5402 5403
 * 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 已提交
5404 5405
 * 'error_code', which will be set to CLUSTER_REDIR_ASK or
 * CLUSTER_REDIR_MOVED.
5406
 *
A
antirez 已提交
5407
 * When the node is 'myself' 'error_code' is set to CLUSTER_REDIR_NONE.
5408 5409 5410 5411
 *
 * 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 已提交
5412
 * CLUSTER_REDIR_CROSS_SLOT if the request contains multiple keys that
5413 5414
 * don't belong to the same hash slot.
 *
A
antirez 已提交
5415
 * CLUSTER_REDIR_UNSTABLE if the request contains multiple keys
5416
 * belonging to the same slot, but the slot is not stable (in migration or
5417 5418
 * importing state, likely because a resharding is in progress).
 *
A
antirez 已提交
5419
 * CLUSTER_REDIR_DOWN_UNBOUND if the request addresses a slot which is
5420 5421
 * 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,
5422 5423 5424 5425
 * 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. */
5426
clusterNode *getNodeByQuery(client *c, struct redisCommand *cmd, robj **argv, int argc, int *hashslot, int *error_code) {
A
antirez 已提交
5427
    clusterNode *n = NULL;
5428
    robj *firstkey = NULL;
5429
    int multiple_keys = 0;
A
antirez 已提交
5430 5431
    multiState *ms, _ms;
    multiCmd mc;
5432 5433 5434
    int i, slot = 0, migrating_slot = 0, importing_slot = 0, missing_keys = 0;

    /* Set error code optimistically for the base case. */
A
antirez 已提交
5435
    if (error_code) *error_code = CLUSTER_REDIR_NONE;
A
antirez 已提交
5436 5437 5438 5439

    /* 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 已提交
5440
        /* If CLIENT_MULTI flag is not set EXEC is just going to return an
A
antirez 已提交
5441
         * error. */
A
antirez 已提交
5442
        if (!(c->flags & CLIENT_MULTI)) return myself;
A
antirez 已提交
5443 5444
        ms = &c->mstate;
    } else {
5445 5446 5447
        /* 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 已提交
5448 5449 5450 5451 5452 5453 5454 5455
        ms = &_ms;
        _ms.commands = &mc;
        _ms.count = 1;
        mc.argv = argv;
        mc.argc = argc;
        mc.cmd = cmd;
    }

5456 5457
    /* Check that all the keys are in the same hash slot, and obtain this
     * slot and the node associated. */
A
antirez 已提交
5458 5459 5460 5461 5462 5463 5464 5465 5466
    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;

5467
        keyindex = getKeysFromCommand(mcmd,margv,margc,&numkeys);
A
antirez 已提交
5468
        for (j = 0; j < numkeys; j++) {
5469 5470 5471 5472
            robj *thiskey = margv[keyindex[j]];
            int thisslot = keyHashSlot((char*)thiskey->ptr,
                                       sdslen(thiskey->ptr));

5473 5474 5475
            if (firstkey == NULL) {
                /* This is the first key we see. Check what is the slot
                 * and node. */
5476 5477
                firstkey = thiskey;
                slot = thisslot;
5478
                n = server.cluster->slots[slot];
5479 5480 5481 5482 5483 5484 5485 5486

                /* 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 已提交
5487
                        *error_code = CLUSTER_REDIR_DOWN_UNBOUND;
5488 5489 5490
                    return NULL;
                }

5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502
                /* 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 已提交
5503
            } else {
5504 5505
                /* If it is not the first key, make sure it is exactly
                 * the same key as the first we saw. */
5506 5507 5508 5509 5510
                if (!equalStringObjects(firstkey,thiskey)) {
                    if (slot != thisslot) {
                        /* Error: multiple keys from different slots. */
                        getKeysFreeResult(keyindex);
                        if (error_code)
A
antirez 已提交
5511
                            *error_code = CLUSTER_REDIR_CROSS_SLOT;
5512 5513 5514 5515 5516 5517
                        return NULL;
                    } else {
                        /* Flag this request as one with multiple different
                         * keys. */
                        multiple_keys = 1;
                    }
5518
                }
A
antirez 已提交
5519
            }
5520 5521 5522 5523 5524 5525 5526

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

5531
    /* No key at all in command? then we can serve the request
5532
     * without redirections or errors in all the cases. */
5533
    if (n == NULL) return myself;
5534

5535 5536 5537 5538 5539 5540
    /* 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;
    }

5541
    /* Return the hashslot by reference. */
5542
    if (hashslot) *hashslot = slot;
5543

5544 5545 5546 5547 5548
    /* 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;
5549 5550

    /* If we don't have all the keys and we are migrating the slot, send
5551 5552
     * an ASK redirection. */
    if (migrating_slot && missing_keys) {
A
antirez 已提交
5553
        if (error_code) *error_code = CLUSTER_REDIR_ASK;
5554 5555 5556
        return server.cluster->migrating_slots_to[slot];
    }

5557 5558 5559 5560
    /* 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. */
5561
    if (importing_slot &&
A
antirez 已提交
5562
        (c->flags & CLIENT_ASKING || cmd->flags & CMD_ASKING))
5563
    {
5564
        if (multiple_keys && missing_keys) {
A
antirez 已提交
5565
            if (error_code) *error_code = CLUSTER_REDIR_UNSTABLE;
5566 5567 5568 5569
            return NULL;
        } else {
            return myself;
        }
5570
    }
5571

5572 5573 5574
    /* 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 已提交
5575
    if (c->flags & CLIENT_READONLY &&
5576 5577
        (cmd->flags & CMD_READONLY || cmd->proc == evalCommand ||
         cmd->proc == evalShaCommand) &&
5578
        nodeIsSlave(myself) &&
5579
        myself->slaveof == n)
5580
    {
5581
        return myself;
5582
    }
5583 5584 5585

    /* 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 已提交
5586
    if (n != myself && error_code) *error_code = CLUSTER_REDIR_MOVED;
5587
    return n;
A
antirez 已提交
5588
}
5589 5590

/* Send the client the right redirection code, according to error_code
A
antirez 已提交
5591
 * that should be set to one of CLUSTER_REDIR_* macros.
5592
 *
A
antirez 已提交
5593
 * If CLUSTER_REDIR_ASK or CLUSTER_REDIR_MOVED error codes
5594 5595 5596
 * 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. */
5597
void clusterRedirectClient(client *c, clusterNode *n, int hashslot, int error_code) {
A
antirez 已提交
5598
    if (error_code == CLUSTER_REDIR_CROSS_SLOT) {
5599
        addReplySds(c,sdsnew("-CROSSSLOT Keys in request don't hash to the same slot\r\n"));
A
antirez 已提交
5600
    } else if (error_code == CLUSTER_REDIR_UNSTABLE) {
J
Jack Drogon 已提交
5601
        /* The request spawns multiple keys in the same slot,
5602 5603 5604
         * 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 已提交
5605
    } else if (error_code == CLUSTER_REDIR_DOWN_STATE) {
5606
        addReplySds(c,sdsnew("-CLUSTERDOWN The cluster is down\r\n"));
A
antirez 已提交
5607
    } else if (error_code == CLUSTER_REDIR_DOWN_UNBOUND) {
5608
        addReplySds(c,sdsnew("-CLUSTERDOWN Hash slot not served\r\n"));
A
antirez 已提交
5609 5610
    } else if (error_code == CLUSTER_REDIR_MOVED ||
               error_code == CLUSTER_REDIR_ASK)
5611 5612 5613
    {
        addReplySds(c,sdscatprintf(sdsempty(),
            "-%s %d %s:%d\r\n",
A
antirez 已提交
5614
            (error_code == CLUSTER_REDIR_ASK) ? "ASK" : "MOVED",
5615 5616
            hashslot,n->ip,n->port));
    } else {
A
antirez 已提交
5617
        serverPanic("getNodeByQuery() unknown error.");
5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631
    }
}

/* 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. */
5632
int clusterRedirectBlockedClientIfNeeded(client *c) {
5633 5634 5635 5636 5637
    if (c->flags & CLIENT_BLOCKED &&
        (c->btype == BLOCKED_LIST ||
         c->btype == BLOCKED_ZSET ||
         c->btype == BLOCKED_STREAM))
    {
5638 5639 5640 5641
        dictEntry *de;
        dictIterator *di;

        /* If the cluster is down, unblock the client with the right error. */
A
antirez 已提交
5642 5643
        if (server.cluster->state == CLUSTER_FAIL) {
            clusterRedirectClient(c,NULL,0,CLUSTER_REDIR_DOWN_STATE);
5644 5645 5646
            return 1;
        }

5647
        /* All keys must belong to the same slot, so check first key only. */
5648
        di = dictGetIterator(c->bpop.keys);
5649
        if ((de = dictNext(di)) != NULL) {
5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661
            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 已提交
5662
                        CLUSTER_REDIR_DOWN_UNBOUND);
5663 5664
                } else {
                    clusterRedirectClient(c,node,slot,
A
antirez 已提交
5665
                        CLUSTER_REDIR_MOVED);
5666
                }
5667
                dictReleaseIterator(di);
5668 5669 5670 5671 5672 5673 5674
                return 1;
            }
        }
        dictReleaseIterator(di);
    }
    return 0;
}