cluster.c 228.1 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
void clusterAcceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
52
void clusterReadHandler(connection *conn);
A
antirez 已提交
53 54
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
        /* 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) {
141
            if (!(argc % 2)) goto fmterr;
142 143 144 145
            for (j = 1; j < argc; j += 2) {
                if (strcasecmp(argv[j],"currentEpoch") == 0) {
                    server.cluster->currentEpoch =
                            strtoull(argv[j+1],NULL,10);
146 147
                } else if (strcasecmp(argv[j],"lastVoteEpoch") == 0) {
                    server.cluster->lastVoteEpoch =
148 149
                            strtoull(argv[j+1],NULL,10);
                } else {
A
antirez 已提交
150
                    serverLog(LL_WARNING,
151 152 153 154
                        "Skipping unknown cluster config variable '%s'",
                        argv[j]);
                }
            }
155
            sdsfreesplitres(argv,argc);
156 157 158
            continue;
        }

159
        /* Regular config lines have at least eight fields */
160 161 162 163
        if (argc < 8) {
            sdsfreesplitres(argv,argc);
            goto fmterr;
        }
164

165 166 167 168 169 170 171
        /* Create this node if it does not exist */
        n = clusterLookupNode(argv[0]);
        if (!n) {
            n = createClusterNode(argv[0],0);
            clusterAddNode(n);
        }
        /* Address and port */
172 173 174 175
        if ((p = strrchr(argv[1],':')) == NULL) {
            sdsfreesplitres(argv,argc);
            goto fmterr;
        }
176 177
        *p = '\0';
        memcpy(n->ip,argv[1],strlen(argv[1])+1);
178 179 180 181 182 183 184 185 186 187 188
        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;
189 190 191 192 193 194 195

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

234
        /* Set ping sent / pong received timestamps */
235 236
        if (atoi(argv[4])) n->ping_sent = mstime();
        if (atoi(argv[5])) n->pong_received = mstime();
237

238 239 240
        /* Set configEpoch for this node. */
        n->configEpoch = strtoull(argv[6],NULL,10);

241
        /* Populate hash slots served by this instance. */
242
        for (j = 8; j < argc; j++) {
243 244
            int start, stop;

A
antirez 已提交
245 246 247 248 249 250 251
            if (argv[j][0] == '[') {
                /* Here we handle migrating / importing slots */
                int slot;
                char direction;
                clusterNode *cn;

                p = strchr(argv[j],'-');
A
antirez 已提交
252
                serverAssert(p != NULL);
A
antirez 已提交
253 254 255
                *p = '\0';
                direction = p[1]; /* Either '>' or '<' */
                slot = atoi(argv[j]+1);
256 257 258 259
                if (slot < 0 || slot >= CLUSTER_SLOTS) {
                    sdsfreesplitres(argv,argc);
                    goto fmterr;
                }
A
antirez 已提交
260 261 262 263 264 265 266
                p += 3;
                cn = clusterLookupNode(p);
                if (!cn) {
                    cn = createClusterNode(p,0);
                    clusterAddNode(cn);
                }
                if (direction == '>') {
267
                    server.cluster->migrating_slots_to[slot] = cn;
A
antirez 已提交
268
                } else {
269
                    server.cluster->importing_slots_from[slot] = cn;
A
antirez 已提交
270 271 272
                }
                continue;
            } else if ((p = strchr(argv[j],'-')) != NULL) {
273 274 275 276 277 278
                *p = '\0';
                start = atoi(argv[j]);
                stop = atoi(p+1);
            } else {
                start = stop = atoi(argv[j]);
            }
A
antirez 已提交
279 280 281
            if (start < 0 || start >= CLUSTER_SLOTS ||
                stop < 0 || stop >= CLUSTER_SLOTS)
            {
282 283 284
                sdsfreesplitres(argv,argc);
                goto fmterr;
            }
285 286
            while(start <= stop) clusterAddSlot(n, start++);
        }
A
antirez 已提交
287

288
        sdsfreesplitres(argv,argc);
A
antirez 已提交
289
    }
290 291 292
    /* Config sanity check */
    if (server.cluster->myself == NULL) goto fmterr;

A
antirez 已提交
293
    zfree(line);
A
antirez 已提交
294 295
    fclose(fp);

A
antirez 已提交
296
    serverLog(LL_NOTICE,"Node configuration loaded, I'm %.40s", myself->name);
297 298 299 300 301 302 303

    /* 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();
    }
304
    return C_OK;
A
antirez 已提交
305 306

fmterr:
A
antirez 已提交
307
    serverLog(LL_WARNING,
A
antirez 已提交
308
        "Unrecoverable error: corrupted cluster config file.");
309
    zfree(line);
310
    if (fp) fclose(fp);
A
antirez 已提交
311 312 313
    exit(1);
}

A
antirez 已提交
314 315 316
/* Cluster node configuration is exactly the same as CLUSTER NODES output.
 *
 * This function writes the node config and returns 0, on error -1
317 318 319 320 321 322 323 324 325
 * 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 已提交
326
int clusterSaveConfig(int do_fsync) {
327 328
    sds ci;
    size_t content_size;
329
    struct stat sb;
A
antirez 已提交
330
    int fd;
331

332 333
    server.cluster->todo_before_sleep &= ~CLUSTER_TODO_SAVE_CONFIG;

334
    /* Get the nodes description and concatenate our "vars" directive to
335
     * save currentEpoch and lastVoteEpoch. */
A
antirez 已提交
336
    ci = clusterGenNodesDescription(CLUSTER_NODE_HANDSHAKE);
337
    ci = sdscatprintf(ci,"vars currentEpoch %llu lastVoteEpoch %llu\n",
338
        (unsigned long long) server.cluster->currentEpoch,
339
        (unsigned long long) server.cluster->lastVoteEpoch);
340
    content_size = sdslen(ci);
341

342
    if ((fd = open(server.cluster_configfile,O_WRONLY|O_CREAT,0644))
A
antirez 已提交
343
        == -1) goto err;
344 345 346

    /* Pad the new payload if the existing file length is greater. */
    if (fstat(fd,&sb) != -1) {
347
        if (sb.st_size > (off_t)content_size) {
348 349 350 351
            ci = sdsgrowzero(ci,sb.st_size);
            memset(ci+content_size,'\n',sb.st_size-content_size);
        }
    }
A
antirez 已提交
352
    if (write(fd,ci,sdslen(ci)) != (ssize_t)sdslen(ci)) goto err;
353 354 355 356
    if (do_fsync) {
        server.cluster->todo_before_sleep &= ~CLUSTER_TODO_FSYNC_CONFIG;
        fsync(fd);
    }
357 358 359 360 361 362

    /* 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 已提交
363 364 365 366 367
    close(fd);
    sdsfree(ci);
    return 0;

err:
368
    if (fd != -1) close(fd);
A
antirez 已提交
369 370 371 372
    sdsfree(ci);
    return -1;
}

A
antirez 已提交
373 374
void clusterSaveConfigOrDie(int do_fsync) {
    if (clusterSaveConfig(do_fsync) == -1) {
A
antirez 已提交
375
        serverLog(LL_WARNING,"Fatal: can't update cluster config file.");
376 377 378 379
        exit(1);
    }
}

380 381 382 383 384 385 386
/* 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()).
 *
387 388
 * On success C_OK is returned, otherwise an error is logged and
 * the function returns C_ERR to signal a lock was not acquired. */
389
int clusterLockConfig(char *filename) {
390 391 392 393 394
/* 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)
395 396 397 398 399
    /* 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 已提交
400
        serverLog(LL_WARNING,
401 402
            "Can't open %s in order to acquire a lock: %s",
            filename, strerror(errno));
403
        return C_ERR;
404 405 406 407
    }

    if (flock(fd,LOCK_EX|LOCK_NB) == -1) {
        if (errno == EWOULDBLOCK) {
A
antirez 已提交
408
            serverLog(LL_WARNING,
409 410 411 412 413
                 "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 已提交
414
            serverLog(LL_WARNING,
415 416 417
                "Impossible to lock %s: %s", filename, strerror(errno));
        }
        close(fd);
418
        return C_ERR;
419 420 421
    }
    /* 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. */
422 423
#endif /* __sun */

424
    return C_OK;
425 426
}

427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
/* 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 已提交
443
void clusterInit(void) {
444
    int saveconf = 0;
445

446 447
    server.cluster = zmalloc(sizeof(clusterState));
    server.cluster->myself = NULL;
448
    server.cluster->currentEpoch = 0;
A
antirez 已提交
449
    server.cluster->state = CLUSTER_FAIL;
450
    server.cluster->size = 1;
451
    server.cluster->todo_before_sleep = 0;
452
    server.cluster->nodes = dictCreate(&clusterNodesDictType,NULL);
453 454
    server.cluster->nodes_black_list =
        dictCreate(&clusterNodesBlackListDictType,NULL);
455 456
    server.cluster->failover_auth_time = 0;
    server.cluster->failover_auth_count = 0;
457
    server.cluster->failover_auth_rank = 0;
458
    server.cluster->failover_auth_epoch = 0;
A
antirez 已提交
459
    server.cluster->cant_failover_reason = CLUSTER_CANT_FAILOVER_NONE;
460
    server.cluster->lastVoteEpoch = 0;
461 462 463 464
    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;
    }
465
    server.cluster->stats_pfail_nodes = 0;
A
antirez 已提交
466 467
    memset(server.cluster->slots,0, sizeof(server.cluster->slots));
    clusterCloseAllSlots();
468 469 470

    /* Lock the cluster config file to make sure every node uses
     * its own nodes.conf. */
471
    if (clusterLockConfig(server.cluster_configfile) == C_ERR)
472 473 474
        exit(1);

    /* Load or create a new nodes configuration. */
475
    if (clusterLoadConfig(server.cluster_configfile) == C_ERR) {
A
antirez 已提交
476 477
        /* No configuration found. We will just use the random name provided
         * by the createClusterNode() function. */
478
        myself = server.cluster->myself =
A
antirez 已提交
479
            createClusterNode(NULL,CLUSTER_NODE_MYSELF|CLUSTER_NODE_MASTER);
A
antirez 已提交
480
        serverLog(LL_NOTICE,"No cluster configuration found, I'm %.40s",
481 482
            myself->name);
        clusterAddNode(myself);
483 484
        saveconf = 1;
    }
A
antirez 已提交
485
    if (saveconf) clusterSaveConfigOrDie(1);
486 487

    /* We need a listening TCP port for our cluster messaging needs. */
488
    server.cfd_count = 0;
489 490

    /* Port sanity check II
A
antirez 已提交
491 492
     * The other handshake port check is triggered too late to stop
     * us from trying to use a too-high cluster port number. */
493 494
    int port = server.tls_cluster ? server.tls_port : server.port;
    if (port > (65535-CLUSTER_PORT_INCR)) {
A
antirez 已提交
495
        serverLog(LL_WARNING, "Redis port number too high. "
496 497 498 499
                   "Cluster communication port is 10,000 port "
                   "numbers higher than your Redis port. "
                   "Your Redis port number must be "
                   "lower than 55535.");
A
antirez 已提交
500
        exit(1);
501
    }
502
    if (listenToPort(port+CLUSTER_PORT_INCR,
503
        server.cfd,&server.cfd_count) == C_ERR)
504 505
    {
        exit(1);
506 507 508 509 510 511
    } 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 已提交
512
                    serverPanic("Unrecoverable error creating Redis Cluster "
513 514
                                "file event.");
        }
A
antirez 已提交
515
    }
516

517 518 519 520
    /* 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 已提交
521

522 523
    /* Set myself->port / cport to my listening ports, we'll just need to
     * discover the IP address via MEET messages. */
524 525
    myself->port = port;
    myself->cport = port+CLUSTER_PORT_INCR;
526 527 528 529
    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 已提交
530

A
antirez 已提交
531
    server.cluster->mf_end = 0;
532
    resetManualFailover();
533
    clusterUpdateMyselfFlags();
A
antirez 已提交
534 535
}

A
antirez 已提交
536 537 538 539 540 541 542
/* 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.
543 544
 * 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 已提交
545 546 547 548 549 550 551 552 553
void clusterReset(int hard) {
    dictIterator *di;
    dictEntry *de;
    int j;

    /* Turn into master. */
    if (nodeIsSlave(myself)) {
        clusterSetNodeAsMaster(myself);
        replicationUnsetMaster();
554
        emptyDb(-1,EMPTYDB_NO_FLAGS,NULL);
A
antirez 已提交
555 556 557 558 559 560 561
    }

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

    /* Unassign all the slots. */
A
antirez 已提交
562
    for (j = 0; j < CLUSTER_SLOTS; j++) clusterDelSlot(j);
A
antirez 已提交
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580

    /* 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 已提交
581
        serverLog(LL_WARNING, "configEpoch set to 0 via CLUSTER RESET HARD");
A
antirez 已提交
582 583 584

        /* 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 已提交
585
        oldname = sdsnewlen(myself->name, CLUSTER_NAMELEN);
A
antirez 已提交
586 587
        dictDelete(server.cluster->nodes,oldname);
        sdsfree(oldname);
A
antirez 已提交
588
        getRandomHexChars(myself->name, CLUSTER_NAMELEN);
A
antirez 已提交
589
        clusterAddNode(myself);
590
        serverLog(LL_NOTICE,"Node hard reset, now I'm %.40s", myself->name);
A
antirez 已提交
591 592 593 594 595 596 597 598
    }

    /* 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 已提交
599 600 601 602 603 604
/* -----------------------------------------------------------------------------
 * CLUSTER communication link
 * -------------------------------------------------------------------------- */

clusterLink *createClusterLink(clusterNode *node) {
    clusterLink *link = zmalloc(sizeof(*link));
605
    link->ctime = mstime();
A
antirez 已提交
606 607 608
    link->sndbuf = sdsempty();
    link->rcvbuf = sdsempty();
    link->node = node;
609
    link->conn = NULL;
A
antirez 已提交
610 611 612 613
    return link;
}

/* Free a cluster link, but does not free the associated node of course.
614
 * This function will just make sure that the original node associated
A
antirez 已提交
615 616
 * with this link will have the 'link' field set to NULL. */
void freeClusterLink(clusterLink *link) {
617 618 619
    if (link->conn) {
        connClose(link->conn);
        link->conn = NULL;
A
antirez 已提交
620 621 622 623 624 625 626 627
    }
    sdsfree(link->sndbuf);
    sdsfree(link->rcvbuf);
    if (link->node)
        link->node->link = NULL;
    zfree(link);
}

628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
static void clusterConnAcceptHandler(connection *conn) {
    clusterLink *link;

    if (connGetState(conn) != CONN_STATE_CONNECTED) {
        serverLog(LL_VERBOSE,
                "Error accepting cluster node connection: %s", connGetLastError(conn));
        connClose(conn);
        return;
    }

    /* 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->conn = conn;
    connSetPrivateData(conn, link);

    /* Register read handler */
    connSetReadHandler(conn, clusterReadHandler);
}

651
#define MAX_CLUSTER_ACCEPTS_PER_CALL 1000
A
antirez 已提交
652 653
void clusterAcceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
    int cport, cfd;
654
    int max = MAX_CLUSTER_ACCEPTS_PER_CALL;
A
antirez 已提交
655 656 657 658
    char cip[NET_IP_STR_LEN];
    UNUSED(el);
    UNUSED(mask);
    UNUSED(privdata);
A
antirez 已提交
659

660 661 662 663
    /* 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;

664 665 666 667
    while(max--) {
        cfd = anetTcpAccept(server.neterr, fd, cip, sizeof(cip), &cport);
        if (cfd == ANET_ERR) {
            if (errno != EWOULDBLOCK)
A
antirez 已提交
668
                serverLog(LL_VERBOSE,
669
                    "Error accepting cluster node: %s", server.neterr);
670 671
            return;
        }
672 673 674 675

        connection *conn = server.tls_cluster ? connCreateAcceptedTLS(cfd,1) : connCreateAcceptedSocket(cfd);
        connNonBlock(conn);
        connEnableTcpNoDelay(conn);
676 677

        /* Use non-blocking I/O for cluster messages. */
678 679 680 681 682 683
        serverLog(LL_VERBOSE,"Accepting cluster node connection from %s:%d", cip, cport);

        /* Accept the connection now.  connAccept() may call our handler directly
         * or schedule it for later depending on connection implementation.
         */
        if (connAccept(conn, clusterConnAcceptHandler) == C_ERR) {
684 685 686 687
            if (connGetState(conn) == CONN_STATE_ERROR)
                serverLog(LL_VERBOSE,
                        "Error accepting cluster node connection: %s",
                        connGetLastError(conn));
688 689 690
            connClose(conn);
            return;
        }
A
antirez 已提交
691 692 693
    }
}

694 695 696 697 698 699 700
/* Return the approximated number of sockets we are using in order to
 * take the cluster bus connections. */
unsigned long getClusterConnectionsCount(void) {
    return server.cluster_enabled ?
           (dictSize(server.cluster->nodes)*2) : 0;
}

A
antirez 已提交
701 702 703 704
/* -----------------------------------------------------------------------------
 * Key space handling
 * -------------------------------------------------------------------------- */

705
/* We have 16384 hash slots. The hash slot of a given key is obtained
706 707 708 709 710
 * 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 已提交
711
unsigned int keyHashSlot(char *key, int keylen) {
712 713 714 715 716 717 718 719 720 721 722 723
    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 已提交
724
    /* No '}' or nothing between {} ? Hash the whole key. */
725 726 727 728 729
    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 已提交
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
}

/* -----------------------------------------------------------------------------
 * 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 已提交
747
        memcpy(node->name, nodename, CLUSTER_NAMELEN);
A
antirez 已提交
748
    else
A
antirez 已提交
749
        getRandomHexChars(node->name, CLUSTER_NAMELEN);
750
    node->ctime = mstime();
751
    node->configEpoch = 0;
A
antirez 已提交
752 753
    node->flags = flags;
    memset(node->slots,0,sizeof(node->slots));
754
    node->numslots = 0;
A
antirez 已提交
755 756 757 758
    node->numslaves = 0;
    node->slaves = NULL;
    node->slaveof = NULL;
    node->ping_sent = node->pong_received = 0;
759
    node->data_received = 0;
A
antirez 已提交
760
    node->fail_time = 0;
A
antirez 已提交
761
    node->link = NULL;
762
    memset(node->ip,0,sizeof(node->ip));
763
    node->port = 0;
764
    node->cport = 0;
765
    node->fail_reports = listCreate();
766
    node->voted_time = 0;
A
antirez 已提交
767
    node->orphaned_time = 0;
768 769
    node->repl_offset_time = 0;
    node->repl_offset = 0;
770
    listSetFreeMethod(node->fail_reports,zfree);
A
antirez 已提交
771 772 773
    return node;
}

774 775 776 777 778
/* 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
779 780 781 782 783 784
 * '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) {
785 786 787 788 789 790 791 792 793 794 795
    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) {
796
            fr->time = mstime();
797
            return 0;
798 799 800 801 802 803
        }
    }

    /* Otherwise create a new report. */
    fr = zmalloc(sizeof(*fr));
    fr->node = sender;
804
    fr->time = mstime();
805
    listAddNodeTail(l,fr);
806
    return 1;
807 808
}

809 810 811 812 813 814 815 816 817 818
/* 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;
819
    mstime_t maxtime = server.cluster_node_timeout *
A
antirez 已提交
820
                     CLUSTER_FAIL_REPORT_VALIDITY_MULT;
821
    mstime_t now = mstime();
822 823 824 825 826 827 828 829

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

830 831 832 833 834 835 836
/* 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
837 838 839 840 841
 * time.
 *
 * The function returns 1 if the failure report was found and removed.
 * Otherwise 0 is returned. */
int clusterNodeDelFailureReport(clusterNode *node, clusterNode *sender) {
842 843 844 845 846 847 848 849 850 851 852
    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;
    }
853
    if (!ln) return 0; /* No failure report from this sender. */
854 855 856

    /* Remove the failure report. */
    listDelNode(l,ln);
857
    clusterNodeCleanupFailureReports(node);
858
    return 1;
859 860
}

861 862 863 864 865 866 867 868
/* 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 已提交
869 870 871 872 873
int clusterNodeRemoveSlave(clusterNode *master, clusterNode *slave) {
    int j;

    for (j = 0; j < master->numslaves; j++) {
        if (master->slaves[j] == slave) {
874 875 876 877 878
            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 已提交
879
            master->numslaves--;
880 881
            if (master->numslaves == 0)
                master->flags &= ~CLUSTER_NODE_MIGRATE_TO;
882
            return C_OK;
A
antirez 已提交
883 884
        }
    }
885
    return C_ERR;
A
antirez 已提交
886 887 888 889 890 891 892
}

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++)
893
        if (master->slaves[j] == slave) return C_ERR;
A
antirez 已提交
894 895 896 897
    master->slaves = zrealloc(master->slaves,
        sizeof(clusterNode*)*(master->numslaves+1));
    master->slaves[master->numslaves] = slave;
    master->numslaves++;
898
    master->flags |= CLUSTER_NODE_MIGRATE_TO;
899
    return C_OK;
A
antirez 已提交
900 901
}

902 903 904 905 906 907 908 909
int clusterCountNonFailingSlaves(clusterNode *n) {
    int j, okslaves = 0;

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

910
/* Low level cleanup of the node structure. Only called by clusterDelNode(). */
A
antirez 已提交
911 912
void freeClusterNode(clusterNode *n) {
    sds nodename;
913 914
    int j;

915
    /* If the node has associated slaves, we have to set
916
     * all the slaves->slaveof fields to NULL (unknown). */
917 918
    for (j = 0; j < n->numslaves; j++)
        n->slaves[j]->slaveof = NULL;
919

920 921 922 923
    /* 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 已提交
924
    nodename = sdsnewlen(n->name, CLUSTER_NAMELEN);
A
antirez 已提交
925
    serverAssert(dictDelete(server.cluster->nodes,nodename) == DICT_OK);
A
antirez 已提交
926
    sdsfree(nodename);
927 928

    /* Release link and associated data structures. */
A
antirez 已提交
929
    if (n->link) freeClusterLink(n->link);
930
    listRelease(n->fail_reports);
M
Matt Stancliff 已提交
931
    zfree(n->slaves);
A
antirez 已提交
932 933 934 935 936 937
    zfree(n);
}

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

939
    retval = dictAdd(server.cluster->nodes,
A
antirez 已提交
940
            sdsnewlen(node->name,CLUSTER_NAMELEN), node);
941
    return (retval == DICT_OK) ? C_OK : C_ERR;
A
antirez 已提交
942 943
}

H
hwware 已提交
944
/* Remove a node from the cluster. The function performs the high level
945 946 947 948 949 950 951 952 953
 * 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 已提交
954 955 956 957 958 959 960
 */
void clusterDelNode(clusterNode *delnode) {
    int j;
    dictIterator *di;
    dictEntry *de;

    /* 1) Mark slots as unassigned. */
A
antirez 已提交
961
    for (j = 0; j < CLUSTER_SLOTS; j++) {
A
antirez 已提交
962 963 964 965 966 967 968 969 970
        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. */
971
    di = dictGetSafeIterator(server.cluster->nodes);
A
antirez 已提交
972 973 974 975 976 977 978 979
    while((de = dictNext(di)) != NULL) {
        clusterNode *node = dictGetVal(de);

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

980
    /* 3) Free the node, unlinking it from the cluster. */
A
antirez 已提交
981 982 983
    freeClusterNode(delnode);
}

A
antirez 已提交
984
/* Node lookup by name */
985
clusterNode *clusterLookupNode(const char *name) {
A
antirez 已提交
986
    sds s = sdsnewlen(name, CLUSTER_NAMELEN);
A
antirez 已提交
987
    dictEntry *de;
A
antirez 已提交
988

989
    de = dictFind(server.cluster->nodes,s);
A
antirez 已提交
990 991
    sdsfree(s);
    if (de == NULL) return NULL;
992
    return dictGetVal(de);
A
antirez 已提交
993 994 995 996 997 998 999 1000
}

/* 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 已提交
1001
    sds s = sdsnewlen(node->name, CLUSTER_NAMELEN);
1002

A
antirez 已提交
1003
    serverLog(LL_DEBUG,"Renaming node %.40s into %.40s",
A
antirez 已提交
1004
        node->name, newname);
1005
    retval = dictDelete(server.cluster->nodes, s);
A
antirez 已提交
1006
    sdsfree(s);
A
antirez 已提交
1007
    serverAssert(retval == DICT_OK);
A
antirez 已提交
1008
    memcpy(node->name, newname, CLUSTER_NAMELEN);
A
antirez 已提交
1009 1010 1011
    clusterAddNode(node);
}

1012 1013 1014 1015
/* -----------------------------------------------------------------------------
 * CLUSTER config epoch handling
 * -------------------------------------------------------------------------- */

A
antirez 已提交
1016 1017
/* Return the greatest configEpoch found in the cluster, or the current
 * epoch if greater than any node configEpoch. */
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
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:
 *
1036
 * 1) Generate a new config epoch, incrementing the current epoch.
1037 1038 1039 1040
 * 2) Assign the new epoch to this node, WITHOUT any consensus.
 * 3) Persist the configuration on disk before sending packets with the
 *    new configuration.
 *
1041 1042
 * 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
1043 1044 1045 1046 1047 1048 1049 1050
 * 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 已提交
1051
 *    too expensive.
1052 1053 1054 1055
 * 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.
 *
1056
 * Redis Cluster will not explode using this function, even in the case of
1057 1058 1059
 * 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
1060
 * config epochs. However using this function may violate the "last failover
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
 * 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 已提交
1072
        serverLog(LL_WARNING,
1073 1074
            "New configEpoch set to %llu",
            (unsigned long long) myself->configEpoch);
1075
        return C_OK;
1076
    } else {
1077
        return C_ERR;
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
    }
}

/* 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 已提交
1132
    if (memcmp(sender->name,myself->name,CLUSTER_NAMELEN) <= 0) return;
1133 1134 1135 1136
    /* Get the next ID available at the best of this node knowledge. */
    server.cluster->currentEpoch++;
    myself->configEpoch = server.cluster->currentEpoch;
    clusterSaveConfigOrDie(1);
A
antirez 已提交
1137
    serverLog(LL_VERBOSE,
1138 1139 1140 1141 1142 1143
        "WARNING: configEpoch collision with node %.40s."
        " configEpoch set to %llu",
        sender->name,
        (unsigned long long) myself->configEpoch);
}

1144 1145 1146 1147 1148
/* -----------------------------------------------------------------------------
 * 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 已提交
1149
 * in seconds in CLUSTER_BLACKLIST_TTL).
1150 1151 1152 1153 1154 1155
 *
 * 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 已提交
1156
 * Currently the CLUSTER_BLACKLIST_TTL is set to 1 minute, this means
1157
 * that redis-trib has 60 seconds to send CLUSTER FORGET messages to nodes
1158
 * in the cluster without dealing with the problem of other nodes re-adding
1159 1160
 * back the node to nodes we already sent the FORGET command to.
 *
1161
 * The data structure used is a hash table with an sds string representing
1162 1163 1164 1165
 * the node ID as key, and the time when it is ok to re-add the node as
 * value.
 * -------------------------------------------------------------------------- */

A
antirez 已提交
1166
#define CLUSTER_BLACKLIST_TTL 60      /* 1 minute. */
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191


/* 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 已提交
1192
    sds id = sdsnewlen(node->name,CLUSTER_NAMELEN);
1193 1194

    clusterBlacklistCleanup();
1195 1196 1197 1198 1199 1200
    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 已提交
1201
    dictSetUnsignedIntegerVal(de,time(NULL)+CLUSTER_BLACKLIST_TTL);
1202
    sdsfree(id);
1203 1204 1205 1206 1207 1208
}

/* 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 已提交
1209
    sds id = sdsnewlen(nodeid,CLUSTER_NAMELEN);
1210 1211
    int retval;

1212
    clusterBlacklistCleanup();
1213 1214 1215 1216 1217
    retval = dictFind(server.cluster->nodes_black_list,id) != NULL;
    sdsfree(id);
    return retval;
}

A
antirez 已提交
1218 1219 1220 1221
/* -----------------------------------------------------------------------------
 * CLUSTER messages exchange - PING/PONG and gossip
 * -------------------------------------------------------------------------- */

1222 1223 1224
/* This function checks if a given node should be marked as FAIL.
 * It happens if the following conditions are met:
 *
1225 1226 1227 1228
 * 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.
1229 1230 1231
 *
 * 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.
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
 *
 * 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.
1242 1243 1244 1245 1246
 */
void markNodeAsFailingIfNeeded(clusterNode *node) {
    int failures;
    int needed_quorum = (server.cluster->size / 2) + 1;

1247 1248
    if (!nodeTimedOut(node)) return; /* We can reach it. */
    if (nodeFailed(node)) return; /* Already FAILing. */
1249

1250 1251
    failures = clusterNodeFailureReportsCount(node);
    /* Also count myself as a voter if I'm a master. */
1252
    if (nodeIsMaster(myself)) failures++;
1253
    if (failures < needed_quorum) return; /* No weak agreement from masters. */
1254

A
antirez 已提交
1255
    serverLog(LL_NOTICE,
1256 1257 1258
        "Marking node %.40s as failing (quorum reached).", node->name);

    /* Mark the node as failing. */
A
antirez 已提交
1259 1260
    node->flags &= ~CLUSTER_NODE_PFAIL;
    node->flags |= CLUSTER_NODE_FAIL;
1261
    node->fail_time = mstime();
1262

1263 1264
    /* Broadcast the failing node name to everybody, forcing all the other
     * reachable nodes to flag the node as FAIL. */
1265
    if (nodeIsMaster(myself)) clusterSendFail(node->name);
A
antirez 已提交
1266
    clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
1267 1268 1269 1270
}

/* 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
1271
 * state. */
1272
void clearNodeFailureIfNeeded(clusterNode *node) {
1273
    mstime_t now = mstime();
A
antirez 已提交
1274

A
antirez 已提交
1275
    serverAssert(nodeFailed(node));
A
antirez 已提交
1276 1277 1278

    /* For slaves we always clear the FAIL flag if we can contact the
     * node again. */
1279
    if (nodeIsSlave(node) || node->numslots == 0) {
A
antirez 已提交
1280
        serverLog(LL_NOTICE,
1281
            "Clear FAIL state for node %.40s: %s is reachable again.",
1282
                node->name,
1283
                nodeIsSlave(node) ? "replica" : "master without slots");
A
antirez 已提交
1284
        node->flags &= ~CLUSTER_NODE_FAIL;
A
antirez 已提交
1285
        clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
A
antirez 已提交
1286 1287 1288
    }

    /* If it is a master and...
1289
     * 1) The FAIL state is old enough.
A
antirez 已提交
1290 1291
     * 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. */
1292
    if (nodeIsMaster(node) && node->numslots > 0 &&
1293
        (now - node->fail_time) >
A
antirez 已提交
1294
        (server.cluster_node_timeout * CLUSTER_FAIL_UNDO_TIME_MULT))
A
antirez 已提交
1295
    {
A
antirez 已提交
1296
        serverLog(LL_NOTICE,
A
antirez 已提交
1297
            "Clear FAIL state for node %.40s: is reachable again and nobody is serving its slots after some time.",
1298
                node->name);
A
antirez 已提交
1299
        node->flags &= ~CLUSTER_NODE_FAIL;
A
antirez 已提交
1300
        clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
1301 1302 1303
    }
}

1304 1305 1306
/* 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. */
1307
int clusterHandshakeInProgress(char *ip, int port, int cport) {
1308 1309 1310 1311 1312 1313 1314
    dictIterator *di;
    dictEntry *de;

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

1315
        if (!nodeInHandshake(node)) continue;
1316 1317 1318
        if (!strcasecmp(node->ip,ip) &&
            node->port == port &&
            node->cport == cport) break;
1319 1320 1321 1322 1323
    }
    dictReleaseIterator(di);
    return de != NULL;
}

1324 1325 1326 1327 1328 1329 1330
/* 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. */
1331
int clusterStartHandshake(char *ip, int port, int cport) {
1332
    clusterNode *n;
A
antirez 已提交
1333
    char norm_ip[NET_IP_STR_LEN];
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
    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 */
1351
    if (port <= 0 || port > 65535 || cport <= 0 || cport > 65535) {
1352 1353 1354 1355 1356 1357
        errno = EINVAL;
        return 0;
    }

    /* Set norm_ip as the normalized string representation of the node
     * IP address. */
A
antirez 已提交
1358
    memset(norm_ip,0,NET_IP_STR_LEN);
1359 1360 1361
    if (sa.ss_family == AF_INET)
        inet_ntop(AF_INET,
            (void*)&(((struct sockaddr_in *)&sa)->sin_addr),
A
antirez 已提交
1362
            norm_ip,NET_IP_STR_LEN);
1363 1364 1365
    else
        inet_ntop(AF_INET6,
            (void*)&(((struct sockaddr_in6 *)&sa)->sin6_addr),
A
antirez 已提交
1366
            norm_ip,NET_IP_STR_LEN);
1367

1368
    if (clusterHandshakeInProgress(norm_ip,port,cport)) {
1369 1370 1371 1372 1373 1374
        errno = EAGAIN;
        return 0;
    }

    /* Add the node with a random address (NULL as first argument to
     * createClusterNode()). Everything will be fixed during the
1375
     * handshake. */
A
antirez 已提交
1376
    n = createClusterNode(NULL,CLUSTER_NODE_HANDSHAKE|CLUSTER_NODE_MEET);
1377 1378
    memcpy(n->ip,norm_ip,sizeof(n->ip));
    n->port = port;
1379
    n->cport = cport;
1380 1381 1382 1383
    clusterAddNode(n);
    return 1;
}

A
antirez 已提交
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
/* 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;
1396
        sds ci;
A
antirez 已提交
1397

1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
        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 已提交
1408 1409 1410

        /* Update our state accordingly to the gossip sections */
        node = clusterLookupNode(g->nodename);
1411
        if (node) {
1412 1413
            /* We already know this node.
               Handle failure reports, only when the sender is a master. */
1414
            if (sender && nodeIsMaster(sender) && node != myself) {
A
antirez 已提交
1415
                if (flags & (CLUSTER_NODE_FAIL|CLUSTER_NODE_PFAIL)) {
1416
                    if (clusterNodeAddFailureReport(node,sender)) {
A
antirez 已提交
1417
                        serverLog(LL_VERBOSE,
1418 1419 1420 1421 1422 1423
                            "Node %.40s reported node %.40s as not reachable.",
                            sender->name, node->name);
                    }
                    markNodeAsFailingIfNeeded(node);
                } else {
                    if (clusterNodeDelFailureReport(node,sender)) {
A
antirez 已提交
1424
                        serverLog(LL_VERBOSE,
1425 1426 1427 1428
                            "Node %.40s reported node %.40s is back online.",
                            sender->name, node->name);
                    }
                }
A
antirez 已提交
1429
            }
1430

1431 1432 1433 1434 1435 1436 1437 1438
            /* 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)
            {
1439 1440
                mstime_t pongtime = ntohl(g->pong_received);
                pongtime *= 1000; /* Convert back to milliseconds. */
1441 1442 1443 1444 1445 1446 1447 1448

                /* 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)
                {
1449
                    node->pong_received = pongtime;
1450
                }
1451 1452
            }

1453
            /* If we already know this node, but it is not reachable, and
1454 1455 1456 1457
             * 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 已提交
1458
            if (node->flags & (CLUSTER_NODE_FAIL|CLUSTER_NODE_PFAIL) &&
1459 1460
                !(flags & CLUSTER_NODE_NOADDR) &&
                !(flags & (CLUSTER_NODE_FAIL|CLUSTER_NODE_PFAIL)) &&
1461 1462 1463
                (strcasecmp(node->ip,g->ip) ||
                 node->port != ntohs(g->port) ||
                 node->cport != ntohs(g->cport)))
1464
            {
1465 1466
                if (node->link) freeClusterLink(node->link);
                memcpy(node->ip,g->ip,NET_IP_STR_LEN);
1467
                node->port = ntohs(g->port);
1468
                node->cport = ntohs(g->cport);
1469
                node->flags &= ~CLUSTER_NODE_NOADDR;
1470
            }
A
antirez 已提交
1471 1472
        } else {
            /* If it's not in NOADDR state and we don't have it, we
1473 1474 1475 1476
             * add it to our trusted dict with exact nodeid and flag.
             * Note that we cannot simply start a handshake against
             * this IP/PORT pairs, since IP/PORT can be reused already,
             * otherwise we risk joining another cluster.
A
antirez 已提交
1477 1478 1479 1480
             *
             * 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. */
1481
            if (sender &&
A
antirez 已提交
1482
                !(flags & CLUSTER_NODE_NOADDR) &&
1483 1484
                !clusterBlacklistExists(g->nodename))
            {
1485 1486 1487 1488 1489 1490
                clusterNode *node;
                node = createClusterNode(g->nodename, flags);
                memcpy(node->ip,g->ip,NET_IP_STR_LEN);
                node->port = ntohs(g->port);
                node->cport = ntohs(g->cport);
                clusterAddNode(node);
1491
            }
A
antirez 已提交
1492 1493 1494 1495 1496 1497 1498
        }

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

1499 1500 1501 1502 1503 1504 1505 1506
/* 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 {
1507
        connPeerToString(link->conn, buf, NET_IP_STR_LEN, NULL);
1508
    }
A
antirez 已提交
1509 1510 1511
}

/* Update the node address to the IP address that can be extracted
1512 1513 1514 1515 1516
 * 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 已提交
1517 1518 1519 1520 1521 1522
 *
 * 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. */
1523 1524 1525
int nodeUpdateAddressIfNeeded(clusterNode *node, clusterLink *link,
                              clusterMsg *hdr)
{
A
antirez 已提交
1526
    char ip[NET_IP_STR_LEN] = {0};
1527 1528
    int port = ntohs(hdr->port);
    int cport = ntohs(hdr->cport);
A
antirez 已提交
1529 1530 1531 1532 1533 1534 1535 1536 1537

    /* 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;

1538 1539 1540
    nodeIp2String(ip,link,hdr->myip);
    if (node->port == port && node->cport == cport &&
        strcmp(ip,node->ip) == 0) return 0;
A
antirez 已提交
1541 1542 1543 1544

    /* IP / port is different, update it. */
    memcpy(node->ip,ip,sizeof(ip));
    node->port = port;
1545
    node->cport = cport;
A
antirez 已提交
1546
    if (node->link) freeClusterLink(node->link);
A
antirez 已提交
1547
    node->flags &= ~CLUSTER_NODE_NOADDR;
A
antirez 已提交
1548
    serverLog(LL_WARNING,"Address updated for node %.40s, now %s:%d",
A
antirez 已提交
1549
        node->name, node->ip, node->port);
1550 1551 1552

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

1558 1559 1560 1561
/* 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) {
1562
    if (nodeIsMaster(n)) return;
1563

1564 1565 1566 1567
    if (n->slaveof) {
        clusterNodeRemoveSlave(n->slaveof,n);
        if (n != myself) n->flags |= CLUSTER_NODE_MIGRATE_TO;
    }
A
antirez 已提交
1568 1569
    n->flags &= ~CLUSTER_NODE_SLAVE;
    n->flags |= CLUSTER_NODE_MASTER;
1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
    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.
1586 1587
 * Sometimes it is not actually the "Sender" of the information, like in the
 * case we receive the info via an UPDATE packet. */
1588
void clusterUpdateSlotsConfigWith(clusterNode *sender, uint64_t senderConfigEpoch, unsigned char *slots) {
1589 1590
    int j;
    clusterNode *curmaster, *newmaster = NULL;
1591 1592 1593 1594 1595 1596 1597
    /* 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 已提交
1598
    uint16_t dirty_slots[CLUSTER_SLOTS];
1599
    int dirty_slots_count = 0;
1600 1601 1602 1603

    /* 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. */
1604
    curmaster = nodeIsMaster(myself) ? myself : myself->slaveof;
1605

1606
    if (sender == myself) {
A
antirez 已提交
1607
        serverLog(LL_WARNING,"Discarding UPDATE message about myself.");
1608 1609 1610
        return;
    }

A
antirez 已提交
1611
    for (j = 0; j < CLUSTER_SLOTS; j++) {
1612
        if (bitmapTestBit(slots,j)) {
1613 1614 1615 1616 1617 1618 1619 1620 1621
            /* 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;

1622
            /* We rebind the slot to the new node claiming it if:
1623 1624 1625
             * 1) The slot was unassigned or the new node claims it with a
             *    greater configEpoch.
             * 2) We are not currently importing the slot. */
1626
            if (server.cluster->slots[j] == NULL ||
1627
                server.cluster->slots[j]->configEpoch < senderConfigEpoch)
1628
            {
1629 1630
                /* Was this slot mine, and still contains keys? Mark it as
                 * a dirty slot. */
1631 1632 1633 1634
                if (server.cluster->slots[j] == myself &&
                    countKeysInSlot(j) &&
                    sender != myself)
                {
1635 1636
                    dirty_slots[dirty_slots_count] = j;
                    dirty_slots_count++;
1637 1638
                }

1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
                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);
            }
        }
    }

1650 1651 1652 1653 1654 1655
    /* After updating the slots configuration, don't do any actual change
     * in the state of the server if a module disabled Redis Cluster
     * keys redirections. */
    if (server.cluster_module_flags & CLUSTER_MODULE_FLAG_NO_REDIRECTION)
        return;

1656 1657 1658 1659 1660 1661 1662 1663
    /* 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 已提交
1664
        serverLog(LL_WARNING,
A
antirez 已提交
1665 1666
            "Configuration change detected. Reconfiguring myself "
            "as a replica of %.40s", sender->name);
1667 1668 1669 1670
        clusterSetMaster(sender);
        clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                             CLUSTER_TODO_UPDATE_STATE|
                             CLUSTER_TODO_FSYNC_CONFIG);
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
    } 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]);
1681 1682 1683
    }
}

A
antirez 已提交
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
/* 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);
1697
    mstime_t now = mstime();
A
antirez 已提交
1698

1699 1700
    if (type < CLUSTERMSG_TYPE_COUNT)
        server.cluster->stats_bus_messages_received[type]++;
A
antirez 已提交
1701
    serverLog(LL_DEBUG,"--- Processing packet of type %d, %lu bytes",
1702
        type, (unsigned long) totlen);
1703 1704

    /* Perform sanity checks */
1705
    if (totlen < 16) return 1; /* At least signature, version, totlen, count. */
A
antirez 已提交
1706
    if (totlen > sdslen(link->rcvbuf)) return 1;
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716

    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 已提交
1717 1718 1719 1720 1721 1722 1723 1724 1725
    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;
1726
    } else if (type == CLUSTERMSG_TYPE_FAIL) {
A
antirez 已提交
1727 1728 1729 1730
        uint32_t explen = sizeof(clusterMsg)-sizeof(union clusterMsgData);

        explen += sizeof(clusterMsgDataFail);
        if (totlen != explen) return 1;
1731
    } else if (type == CLUSTERMSG_TYPE_PUBLISH) {
1732 1733
        uint32_t explen = sizeof(clusterMsg)-sizeof(union clusterMsgData);

1734 1735
        explen += sizeof(clusterMsgDataPublish) -
                8 +
1736 1737 1738
                ntohl(hdr->data.publish.msg.channel_len) +
                ntohl(hdr->data.publish.msg.message_len);
        if (totlen != explen) return 1;
1739
    } else if (type == CLUSTERMSG_TYPE_FAILOVER_AUTH_REQUEST ||
1740 1741 1742
               type == CLUSTERMSG_TYPE_FAILOVER_AUTH_ACK ||
               type == CLUSTERMSG_TYPE_MFSTART)
    {
1743 1744
        uint32_t explen = sizeof(clusterMsg)-sizeof(union clusterMsgData);

1745 1746 1747 1748 1749
        if (totlen != explen) return 1;
    } else if (type == CLUSTERMSG_TYPE_UPDATE) {
        uint32_t explen = sizeof(clusterMsg)-sizeof(union clusterMsgData);

        explen += sizeof(clusterMsgDataUpdate);
1750
        if (totlen != explen) return 1;
1751 1752 1753 1754 1755 1756
    } 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;
1757
    }
A
antirez 已提交
1758

1759 1760 1761
    /* Check if the sender is a known node. Note that for incoming connections
     * we don't store link->node information, but resolve the node by the
     * ID in the header each time in the current implementation. */
A
antirez 已提交
1762
    sender = clusterLookupNode(hdr->sender);
1763 1764 1765 1766 1767 1768 1769

    /* Update the last time we saw any data from this node. We
     * use this in order to avoid detecting a timeout from a node that
     * is just sending a lot of data in the cluster bus, for instance
     * because of Pub/Sub. */
    if (sender) sender->data_received = now;

1770
    if (sender && !nodeInHandshake(sender)) {
1771
        /* Update our curretEpoch if we see a newer epoch in the cluster. */
1772 1773 1774 1775
        senderCurrentEpoch = ntohu64(hdr->currentEpoch);
        senderConfigEpoch = ntohu64(hdr->configEpoch);
        if (senderCurrentEpoch > server.cluster->currentEpoch)
            server.cluster->currentEpoch = senderCurrentEpoch;
1776
        /* Update the sender configEpoch if it is publishing a newer one. */
1777
        if (senderConfigEpoch > sender->configEpoch) {
1778
            sender->configEpoch = senderConfigEpoch;
A
antirez 已提交
1779 1780
            clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                                 CLUSTER_TODO_FSYNC_CONFIG);
1781
        }
1782 1783
        /* Update the replication offset info for this node. */
        sender->repl_offset = ntohu64(hdr->offset);
1784
        sender->repl_offset_time = now;
1785 1786 1787 1788 1789 1790 1791 1792 1793
        /* 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 已提交
1794
            serverLog(LL_WARNING,
A
antirez 已提交
1795 1796 1797
                "Received replication offset for paused "
                "master manual failover: %lld",
                server.cluster->mf_master_offset);
1798
        }
1799
    }
1800

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

A
antirez 已提交
1805 1806
        /* We use incoming MEET messages in order to set the address
         * for 'myself', since only other cluster nodes will send us
1807
         * MEET messages on handshakes, when the cluster joins, or
A
antirez 已提交
1808 1809 1810
         * 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
1811 1812 1813 1814 1815
         * 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. */
1816 1817 1818
        if ((type == CLUSTERMSG_TYPE_MEET || myself->ip[0] == '\0') &&
            server.cluster_announce_ip == NULL)
        {
A
antirez 已提交
1819
            char ip[NET_IP_STR_LEN];
A
antirez 已提交
1820

1821
            if (connSockName(link->conn,ip,sizeof(ip),NULL) != -1 &&
A
antirez 已提交
1822 1823
                strcmp(ip,myself->ip))
            {
A
antirez 已提交
1824 1825
                memcpy(myself->ip,ip,NET_IP_STR_LEN);
                serverLog(LL_WARNING,"IP address for this node updated to %s",
1826
                    myself->ip);
A
antirez 已提交
1827 1828 1829 1830
                clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG);
            }
        }

A
antirez 已提交
1831 1832 1833
        /* 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
1834
         * resolved when we'll receive PONGs from the node. */
A
antirez 已提交
1835 1836 1837
        if (!sender && type == CLUSTERMSG_TYPE_MEET) {
            clusterNode *node;

A
antirez 已提交
1838
            node = createClusterNode(NULL,CLUSTER_NODE_HANDSHAKE);
1839
            nodeIp2String(node->ip,link,hdr->myip);
A
antirez 已提交
1840
            node->port = ntohs(hdr->port);
1841
            node->cport = ntohs(hdr->cport);
A
antirez 已提交
1842
            clusterAddNode(node);
A
antirez 已提交
1843
            clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG);
A
antirez 已提交
1844 1845
        }

1846 1847 1848 1849 1850
        /* 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 已提交
1851 1852 1853

        /* Anyway reply with a PONG */
        clusterSendPing(link,CLUSTERMSG_TYPE_PONG);
1854 1855
    }

1856
    /* PING, PONG, MEET: process config information. */
1857 1858 1859
    if (type == CLUSTERMSG_TYPE_PING || type == CLUSTERMSG_TYPE_PONG ||
        type == CLUSTERMSG_TYPE_MEET)
    {
A
antirez 已提交
1860
        serverLog(LL_DEBUG,"%s packet received: %p",
1861 1862
            type == CLUSTERMSG_TYPE_PING ? "ping" : "pong",
            (void*)link->node);
A
antirez 已提交
1863
        if (link->node) {
1864
            if (nodeInHandshake(link->node)) {
A
antirez 已提交
1865 1866 1867
                /* If we already have this node, try to change the
                 * IP/port of the node with the new one. */
                if (sender) {
A
antirez 已提交
1868
                    serverLog(LL_VERBOSE,
A
antirez 已提交
1869 1870
                        "Handshake: we already know node %.40s, "
                        "updating the address if needed.", sender->name);
1871
                    if (nodeUpdateAddressIfNeeded(sender,link,hdr))
A
antirez 已提交
1872
                    {
A
antirez 已提交
1873 1874
                        clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                                             CLUSTER_TODO_UPDATE_STATE);
A
antirez 已提交
1875
                    }
1876
                    /* Free this node as we already have it. This will
A
antirez 已提交
1877
                     * cause the link to be freed as well. */
1878
                    clusterDelNode(link->node);
A
antirez 已提交
1879 1880 1881 1882
                    return 0;
                }

                /* First thing to do is replacing the random name with the
1883
                 * right node name if this was a handshake stage. */
A
antirez 已提交
1884
                clusterRenameNode(link->node, hdr->sender);
A
antirez 已提交
1885
                serverLog(LL_DEBUG,"Handshake with node %.40s completed.",
A
antirez 已提交
1886
                    link->node->name);
A
antirez 已提交
1887 1888
                link->node->flags &= ~CLUSTER_NODE_HANDSHAKE;
                link->node->flags |= flags&(CLUSTER_NODE_MASTER|CLUSTER_NODE_SLAVE);
A
antirez 已提交
1889
                clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG);
A
antirez 已提交
1890
            } else if (memcmp(link->node->name,hdr->sender,
A
antirez 已提交
1891
                        CLUSTER_NAMELEN) != 0)
A
antirez 已提交
1892 1893 1894 1895
            {
                /* If the reply has a non matching node ID we
                 * disconnect this node and set it as not having an associated
                 * address. */
1896
                serverLog(LL_DEBUG,"PONG contains mismatching sender ID. About node %.40s added %d ms ago, having flags %d",
1897
                    link->node->name,
1898
                    (int)(now-(link->node->ctime)),
1899
                    link->node->flags);
A
antirez 已提交
1900
                link->node->flags |= CLUSTER_NODE_NOADDR;
1901 1902
                link->node->ip[0] = '\0';
                link->node->port = 0;
1903
                link->node->cport = 0;
A
antirez 已提交
1904
                freeClusterLink(link);
A
antirez 已提交
1905
                clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG);
A
antirez 已提交
1906 1907 1908
                return 0;
            }
        }
1909

1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
        /* 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 已提交
1922 1923
        /* Update the node address if it changed. */
        if (sender && type == CLUSTERMSG_TYPE_PING &&
1924
            !nodeInHandshake(sender) &&
1925
            nodeUpdateAddressIfNeeded(sender,link,hdr))
A
antirez 已提交
1926
        {
A
antirez 已提交
1927 1928
            clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                                 CLUSTER_TODO_UPDATE_STATE);
A
antirez 已提交
1929 1930
        }

A
antirez 已提交
1931
        /* Update our info about the node */
1932
        if (link->node && type == CLUSTERMSG_TYPE_PONG) {
1933
            link->node->pong_received = now;
1934 1935 1936
            link->node->ping_sent = 0;

            /* The PFAIL condition can be reversed without external
1937
             * help if it is momentary (that is, if it does not
1938 1939 1940 1941
             * turn into a FAIL state).
             *
             * The FAIL condition is also reversible under specific
             * conditions detected by clearNodeFailureIfNeeded(). */
1942
            if (nodeTimedOut(link->node)) {
A
antirez 已提交
1943
                link->node->flags &= ~CLUSTER_NODE_PFAIL;
A
antirez 已提交
1944 1945
                clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                                     CLUSTER_TODO_UPDATE_STATE);
1946
            } else if (nodeFailed(link->node)) {
1947 1948 1949
                clearNodeFailureIfNeeded(link->node);
            }
        }
A
antirez 已提交
1950

1951
        /* Check for role switch: slave -> master or master -> slave. */
A
antirez 已提交
1952
        if (sender) {
A
antirez 已提交
1953
            if (!memcmp(hdr->slaveof,CLUSTER_NODE_NULL_NAME,
A
antirez 已提交
1954 1955
                sizeof(hdr->slaveof)))
            {
1956
                /* Node is a master. */
1957
                clusterSetNodeAsMaster(sender);
A
antirez 已提交
1958
            } else {
1959
                /* Node is a slave. */
A
antirez 已提交
1960 1961
                clusterNode *master = clusterLookupNode(hdr->slaveof);

1962
                if (nodeIsMaster(sender)) {
1963
                    /* Master turned into a slave! Reconfigure the node. */
1964
                    clusterDelNodeSlots(sender);
1965 1966
                    sender->flags &= ~(CLUSTER_NODE_MASTER|
                                       CLUSTER_NODE_MIGRATE_TO);
A
antirez 已提交
1967
                    sender->flags |= CLUSTER_NODE_SLAVE;
1968 1969

                    /* Update config and state. */
A
antirez 已提交
1970 1971
                    clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                                         CLUSTER_TODO_UPDATE_STATE);
1972 1973
                }

1974
                /* Master node changed for this slave? */
1975
                if (master && sender->slaveof != master) {
1976 1977
                    if (sender->slaveof)
                        clusterNodeRemoveSlave(sender->slaveof,sender);
1978 1979
                    clusterNodeAddSlave(master,sender);
                    sender->slaveof = master;
1980 1981

                    /* Update config. */
A
antirez 已提交
1982
                    clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG);
1983
                }
A
antirez 已提交
1984 1985 1986
            }
        }

1987
        /* Update our info about served slots.
1988
         *
1989
         * Note: this MUST happen after we update the master/slave state
A
antirez 已提交
1990
         * so that CLUSTER_NODE_MASTER flag will be set. */
1991 1992

        /* Many checks are only needed if the set of served slots this
1993 1994 1995 1996
         * 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. */
1997 1998 1999
        int dirty_slots = 0; /* Sender claimed slots don't match my view? */

        if (sender) {
2000
            sender_master = nodeIsMaster(sender) ? sender : sender->slaveof;
2001 2002 2003 2004 2005 2006
            if (sender_master) {
                dirty_slots = memcmp(sender_master->slots,
                        hdr->myslots,sizeof(hdr->myslots)) != 0;
            }
        }

2007 2008 2009
        /* 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. */
2010
        if (sender && nodeIsMaster(sender) && dirty_slots)
2011
            clusterUpdateSlotsConfigWith(sender,senderConfigEpoch,hdr->myslots);
2012

2013 2014 2015
        /* 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.
2016
         *
2017 2018 2019 2020
         * 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:
2021 2022 2023 2024 2025 2026
         *
         * 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
2027 2028 2029 2030
         * 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). */
2031 2032 2033
        if (sender && dirty_slots) {
            int j;

A
antirez 已提交
2034
            for (j = 0; j < CLUSTER_SLOTS; j++) {
2035 2036 2037 2038 2039 2040
                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 已提交
2041
                        serverLog(LL_VERBOSE,
2042
                            "Node %.40s has old slots configuration, sending "
2043
                            "an UPDATE message about %.40s",
2044
                                sender->name, server.cluster->slots[j]->name);
A
antirez 已提交
2045 2046
                        clusterSendUpdate(sender->link,
                            server.cluster->slots[j]);
2047 2048 2049 2050 2051

                        /* TODO: instead of exiting the loop send every other
                         * UPDATE packet for other nodes that are the new owner
                         * of sender's slots. */
                        break;
2052
                    }
2053
                }
A
antirez 已提交
2054 2055 2056
            }
        }

2057 2058 2059 2060 2061 2062 2063 2064 2065
        /* 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 已提交
2066
        /* Get info from the gossip section */
2067
        if (sender) clusterProcessGossipSection(hdr,link);
2068
    } else if (type == CLUSTERMSG_TYPE_FAIL) {
A
antirez 已提交
2069 2070
        clusterNode *failing;

2071 2072
        if (sender) {
            failing = clusterLookupNode(hdr->data.fail.about.nodename);
2073
            if (failing &&
A
antirez 已提交
2074
                !(failing->flags & (CLUSTER_NODE_FAIL|CLUSTER_NODE_MYSELF)))
2075
            {
A
antirez 已提交
2076
                serverLog(LL_NOTICE,
2077 2078
                    "FAIL message received from %.40s about %.40s",
                    hdr->sender, hdr->data.fail.about.nodename);
A
antirez 已提交
2079
                failing->flags |= CLUSTER_NODE_FAIL;
2080
                failing->fail_time = now;
A
antirez 已提交
2081
                failing->flags &= ~CLUSTER_NODE_PFAIL;
A
antirez 已提交
2082 2083
                clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                                     CLUSTER_TODO_UPDATE_STATE);
2084 2085
            }
        } else {
A
antirez 已提交
2086
            serverLog(LL_NOTICE,
2087
                "Ignoring FAIL message from unknown node %.40s about %.40s",
A
antirez 已提交
2088 2089
                hdr->sender, hdr->data.fail.about.nodename);
        }
2090 2091 2092 2093
    } else if (type == CLUSTERMSG_TYPE_PUBLISH) {
        robj *channel, *message;
        uint32_t channel_len, message_len;

A
antirez 已提交
2094 2095
        /* Don't bother creating useless objects if there are no
         * Pub/Sub subscribers. */
2096 2097 2098
        if (dictSize(server.pubsub_channels) ||
           listLength(server.pubsub_patterns))
        {
2099 2100 2101 2102 2103
            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(
2104 2105
                        (char*)hdr->data.publish.msg.bulk_data+channel_len,
                        message_len);
2106 2107 2108 2109
            pubsubPublishMessage(channel,message);
            decrRefCount(channel);
            decrRefCount(message);
        }
2110
    } else if (type == CLUSTERMSG_TYPE_FAILOVER_AUTH_REQUEST) {
A
antirez 已提交
2111
        if (!sender) return 1;  /* We don't know that node. */
2112
        clusterSendFailoverAuthIfNeeded(sender,hdr);
2113
    } else if (type == CLUSTERMSG_TYPE_FAILOVER_AUTH_ACK) {
A
antirez 已提交
2114
        if (!sender) return 1;  /* We don't know that node. */
2115
        /* We consider this vote only if the sender is a master serving
2116 2117
         * a non zero number of slots, and its currentEpoch is greater or
         * equal to epoch where this node started the election. */
2118
        if (nodeIsMaster(sender) && sender->numslots > 0 &&
2119
            senderCurrentEpoch >= server.cluster->failover_auth_epoch)
2120
        {
2121
            server.cluster->failover_auth_count++;
2122 2123
            /* Maybe we reached a quorum here, set a flag to make sure
             * we check ASAP. */
A
antirez 已提交
2124
            clusterDoBeforeSleep(CLUSTER_TODO_HANDLE_FAILOVER);
2125
        }
2126 2127 2128 2129 2130 2131 2132
    } 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();
2133
        server.cluster->mf_end = now + CLUSTER_MF_TIMEOUT;
2134
        server.cluster->mf_slave = sender;
2135
        pauseClients(now+(CLUSTER_MF_TIMEOUT*CLUSTER_MF_PAUSE_MULT));
2136
        serverLog(LL_WARNING,"Manual failover requested by replica %.40s.",
2137
            sender->name);
2138 2139
    } else if (type == CLUSTERMSG_TYPE_UPDATE) {
        clusterNode *n; /* The node the update is about. */
A
antirez 已提交
2140 2141
        uint64_t reportedConfigEpoch =
                    ntohu64(hdr->data.update.nodecfg.configEpoch);
2142 2143 2144 2145 2146 2147 2148

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

2151 2152
        /* Update the node's configEpoch. */
        n->configEpoch = reportedConfigEpoch;
A
antirez 已提交
2153 2154
        clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                             CLUSTER_TODO_FSYNC_CONFIG);
2155

2156
        /* Check the bitmap of served slots and update our
2157
         * config accordingly. */
2158 2159
        clusterUpdateSlotsConfigWith(n,reportedConfigEpoch,
            hdr->data.update.nodecfg.slots);
2160 2161 2162 2163 2164 2165 2166 2167 2168
    } 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 已提交
2169
    } else {
A
antirez 已提交
2170
        serverLog(LL_WARNING,"Received unknown packet type: %d", type);
A
antirez 已提交
2171 2172 2173 2174 2175 2176 2177
    }
    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.
2178

A
antirez 已提交
2179 2180 2181 2182 2183 2184 2185 2186 2187
   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. */
2188 2189
void clusterWriteHandler(connection *conn) {
    clusterLink *link = connGetPrivateData(conn);
A
antirez 已提交
2190 2191
    ssize_t nwritten;

2192
    nwritten = connWrite(conn, link->sndbuf, sdslen(link->sndbuf));
A
antirez 已提交
2193
    if (nwritten <= 0) {
A
antirez 已提交
2194
        serverLog(LL_DEBUG,"I/O error writing to node link: %s",
2195
            (nwritten == -1) ? connGetLastError(conn) : "short write");
A
antirez 已提交
2196 2197 2198
        handleLinkIOError(link);
        return;
    }
2199
    sdsrange(link->sndbuf,nwritten,-1);
A
antirez 已提交
2200
    if (sdslen(link->sndbuf) == 0)
2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246
        connSetWriteHandler(link->conn, NULL);
}

/* A connect handler that gets called when a connection to another node
 * gets established.
 */
void clusterLinkConnectHandler(connection *conn) {
    clusterLink *link = connGetPrivateData(conn);
    clusterNode *node = link->node;

    /* Check if connection succeeded */
    if (connGetState(conn) != CONN_STATE_CONNECTED) {
        serverLog(LL_VERBOSE, "Connection with Node %.40s at %s:%d failed: %s",
                node->name, node->ip, node->cport,
                connGetLastError(conn));
        freeClusterLink(link);
        return;
    }

    /* Register a read handler from now on */
    connSetReadHandler(conn, clusterReadHandler);

    /* 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
     * of a PING one, to force the receiver to add us in its node
     * table. */
    mstime_t old_ping_sent = node->ping_sent;
    clusterSendPing(link, node->flags & CLUSTER_NODE_MEET ?
            CLUSTERMSG_TYPE_MEET : CLUSTERMSG_TYPE_PING);
    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;
    }
    /* 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. */
    node->flags &= ~CLUSTER_NODE_MEET;

    serverLog(LL_DEBUG,"Connecting with Node %.40s at %s:%d",
            node->name, node->ip, node->cport);
A
antirez 已提交
2247 2248 2249 2250 2251
}

/* 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. */
2252
void clusterReadHandler(connection *conn) {
O
Oran Agra 已提交
2253
    clusterMsg buf[1];
A
antirez 已提交
2254 2255
    ssize_t nread;
    clusterMsg *hdr;
2256
    clusterLink *link = connGetPrivateData(conn);
2257
    unsigned int readlen, rcvbuflen;
A
antirez 已提交
2258

2259 2260
    while(1) { /* Read as long as there is data to read. */
        rcvbuflen = sdslen(link->rcvbuf);
2261 2262
        if (rcvbuflen < 8) {
            /* First, obtain the first 8 bytes to get the full message
2263
             * length. */
2264
            readlen = 8 - rcvbuflen;
2265 2266 2267
        } else {
            /* Finally read the full message. */
            hdr = (clusterMsg*) link->rcvbuf;
2268 2269 2270 2271 2272 2273
            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 已提交
2274
                    serverLog(LL_WARNING,
2275 2276
                        "Bad message length or signature received "
                        "from Cluster bus.");
2277 2278 2279
                    handleLinkIOError(link);
                    return;
                }
2280
            }
2281 2282
            readlen = ntohl(hdr->totlen) - rcvbuflen;
            if (readlen > sizeof(buf)) readlen = sizeof(buf);
2283
        }
A
antirez 已提交
2284

2285 2286
        nread = connRead(conn,buf,readlen);
        if (nread == -1 && (connGetState(conn) == CONN_STATE_CONNECTED)) return; /* No more data ready. */
A
antirez 已提交
2287

2288 2289
        if (nread <= 0) {
            /* I/O error... */
A
antirez 已提交
2290
            serverLog(LL_DEBUG,"I/O error reading from node link: %s",
2291
                (nread == 0) ? "connection closed" : connGetLastError(conn));
2292 2293 2294 2295 2296 2297 2298 2299
            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 已提交
2300

2301
        /* Total length obtained? Process this packet. */
2302
        if (rcvbuflen >= 8 && rcvbuflen == ntohl(hdr->totlen)) {
2303 2304 2305 2306 2307 2308
            if (clusterProcessPacket(link)) {
                sdsfree(link->rcvbuf);
                link->rcvbuf = sdsempty();
            } else {
                return; /* Link no longer valid. */
            }
A
antirez 已提交
2309 2310 2311 2312
        }
    }
}

2313 2314 2315 2316 2317
/* 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 已提交
2318 2319
void clusterSendMessage(clusterLink *link, unsigned char *msg, size_t msglen) {
    if (sdslen(link->sndbuf) == 0 && msglen != 0)
2320
        connSetWriteHandlerWithBarrier(link->conn, clusterWriteHandler, 1);
A
antirez 已提交
2321 2322

    link->sndbuf = sdscatlen(link->sndbuf, msg, msglen);
2323 2324 2325 2326 2327 2328

    /* 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 已提交
2329 2330
}

2331
/* Send a message to all the nodes that are part of the cluster having
2332
 * a connected link.
2333
 *
2334 2335 2336
 * 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. */
2337 2338 2339 2340
void clusterBroadcastMessage(void *buf, size_t len) {
    dictIterator *di;
    dictEntry *de;

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

        if (!node->link) continue;
A
antirez 已提交
2346
        if (node->flags & (CLUSTER_NODE_MYSELF|CLUSTER_NODE_HANDSHAKE))
2347
            continue;
2348 2349 2350 2351 2352
        clusterSendMessage(node->link,buf,len);
    }
    dictReleaseIterator(di);
}

2353 2354
/* Build the message header. hdr must point to a buffer at least
 * sizeof(clusterMsg) in bytes. */
A
antirez 已提交
2355
void clusterBuildMessageHdr(clusterMsg *hdr, int type) {
2356
    int totlen = 0;
2357
    uint64_t offset;
2358
    clusterNode *master;
2359 2360 2361 2362 2363

    /* 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. */
2364
    master = (nodeIsSlave(myself) && myself->slaveof) ?
2365
              myself->slaveof : myself;
A
antirez 已提交
2366 2367

    memset(hdr,0,sizeof(*hdr));
2368
    hdr->ver = htons(CLUSTER_PROTO_VER);
2369 2370
    hdr->sig[0] = 'R';
    hdr->sig[1] = 'C';
2371
    hdr->sig[2] = 'm';
2372
    hdr->sig[3] = 'b';
A
antirez 已提交
2373
    hdr->type = htons(type);
A
antirez 已提交
2374
    memcpy(hdr->sender,myself->name,CLUSTER_NAMELEN);
2375

2376 2377 2378 2379 2380 2381 2382 2383 2384 2385
    /* 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. */
2386
    int port = server.tls_cluster ? server.tls_port : server.port;
2387
    int announced_port = server.cluster_announce_port ?
2388
                         server.cluster_announce_port : port;
2389 2390
    int announced_cport = server.cluster_announce_bus_port ?
                          server.cluster_announce_bus_port :
2391
                          (port + CLUSTER_PORT_INCR);
2392

2393
    memcpy(hdr->myslots,master->slots,sizeof(hdr->myslots));
A
antirez 已提交
2394
    memset(hdr->slaveof,0,CLUSTER_NAMELEN);
2395
    if (myself->slaveof != NULL)
A
antirez 已提交
2396
        memcpy(hdr->slaveof,myself->slaveof->name, CLUSTER_NAMELEN);
2397 2398
    hdr->port = htons(announced_port);
    hdr->cport = htons(announced_cport);
2399
    hdr->flags = htons(myself->flags);
2400
    hdr->state = server.cluster->state;
A
antirez 已提交
2401

2402
    /* Set the currentEpoch and configEpochs. */
2403
    hdr->currentEpoch = htonu64(server.cluster->currentEpoch);
2404
    hdr->configEpoch = htonu64(master->configEpoch);
2405

2406
    /* Set the replication offset. */
2407 2408 2409
    if (nodeIsSlave(myself))
        offset = replicationGetSlaveOffset();
    else
2410 2411 2412
        offset = server.master_repl_offset;
    hdr->offset = htonu64(offset);

2413 2414 2415 2416
    /* Set the message flags. */
    if (nodeIsMaster(myself) && server.cluster->mf_end)
        hdr->mflags[0] |= CLUSTERMSG_FLAG0_PAUSED;

2417 2418
    /* Compute the message length for certain messages. For other messages
     * this is up to the caller. */
A
antirez 已提交
2419 2420 2421
    if (type == CLUSTERMSG_TYPE_FAIL) {
        totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
        totlen += sizeof(clusterMsgDataFail);
2422 2423 2424
    } else if (type == CLUSTERMSG_TYPE_UPDATE) {
        totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
        totlen += sizeof(clusterMsgDataUpdate);
A
antirez 已提交
2425 2426
    }
    hdr->totlen = htonl(totlen);
2427
    /* For PING, PONG, and MEET, fixing the totlen field is up to the caller. */
A
antirez 已提交
2428 2429
}

2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456
/* 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 已提交
2457 2458 2459
/* Send a PING or PONG packet to the specified node, making sure to add enough
 * gossip informations. */
void clusterSendPing(clusterLink *link, int type) {
2460 2461 2462 2463 2464 2465 2466 2467 2468
    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. */
2469
    int freshnodes = dictSize(server.cluster->nodes)-2;
A
antirez 已提交
2470

2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494
    /* 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
2495
     * to feature our node, we set the number of entries per packet as
2496
     * 10% of the total nodes we have. */
2497
    wanted = floor(dictSize(server.cluster->nodes)/10);
2498
    if (wanted < 3) wanted = 3;
2499
    if (wanted > freshnodes) wanted = freshnodes;
2500

2501 2502 2503 2504
    /* 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;

2505 2506 2507 2508
    /* 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);
2509
    totlen += (sizeof(clusterMsgDataGossip)*(wanted+pfail_wanted));
2510 2511 2512 2513 2514 2515 2516
    /* 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 已提交
2517
    if (link->node && type == CLUSTERMSG_TYPE_PING)
2518
        link->node->ping_sent = mstime();
A
antirez 已提交
2519
    clusterBuildMessageHdr(hdr,type);
2520

A
antirez 已提交
2521
    /* Populate the gossip fields */
2522
    int maxiterations = wanted*3;
2523
    while(freshnodes > 0 && gossipcount < wanted && maxiterations--) {
A
antirez 已提交
2524
        dictEntry *de = dictGetRandomKey(server.cluster->nodes);
2525
        clusterNode *this = dictGetVal(de);
A
antirez 已提交
2526

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

2531 2532
        /* PFAIL nodes will be added later. */
        if (this->flags & CLUSTER_NODE_PFAIL) continue;
2533

2534
        /* In the gossip section don't include:
2535
         * 1) Nodes in HANDSHAKE state.
2536 2537 2538
         * 3) Nodes with the NOADDR flag set.
         * 4) Disconnected nodes if they don't have configured slots.
         */
A
antirez 已提交
2539
        if (this->flags & (CLUSTER_NODE_HANDSHAKE|CLUSTER_NODE_NOADDR) ||
2540
            (this->link == NULL && this->numslots == 0))
2541
        {
2542 2543
            freshnodes--; /* Tecnically not correct, but saves CPU. */
            continue;
A
antirez 已提交
2544 2545
        }

2546 2547
        /* Do not add a node we already have. */
        if (clusterNodeIsInGossipSection(hdr,gossipcount,this)) continue;
A
antirez 已提交
2548 2549

        /* Add it */
2550
        clusterSetGossipEntry(hdr,gossipcount,this);
A
antirez 已提交
2551 2552 2553
        freshnodes--;
        gossipcount++;
    }
2554

2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576
    /* 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);
    }

2577 2578
    /* Ready to send... fix the totlen fiend and queue the message in the
     * output buffer. */
A
antirez 已提交
2579 2580 2581 2582 2583
    totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
    totlen += (sizeof(clusterMsgDataGossip)*gossipcount);
    hdr->count = htons(gossipcount);
    hdr->totlen = htonl(totlen);
    clusterSendMessage(link,buf,totlen);
2584
    zfree(buf);
A
antirez 已提交
2585 2586
}

2587 2588
/* Send a PONG packet to every connected node that's not in handshake state
 * and for which we have a valid link.
2589
 *
2590 2591
 * In Redis Cluster pongs are not used just for failure detection, but also
 * to carry important configuration information. So broadcasting a pong is
2592
 * useful when something changes in the configuration and we want to make
2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603
 * 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) {
2604 2605 2606
    dictIterator *di;
    dictEntry *de;

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

2611
        if (!node->link) continue;
2612
        if (node == myself || nodeInHandshake(node)) continue;
2613 2614
        if (target == CLUSTER_BROADCAST_LOCAL_SLAVES) {
            int local_slave =
2615
                nodeIsSlave(node) && node->slaveof &&
2616 2617 2618
                (node->slaveof == myself || node->slaveof == myself->slaveof);
            if (!local_slave) continue;
        }
2619 2620 2621 2622 2623
        clusterSendPing(node->link,CLUSTERMSG_TYPE_PONG);
    }
    dictReleaseIterator(di);
}

2624 2625 2626 2627
/* 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) {
O
Oran Agra 已提交
2628 2629
    unsigned char *payload;
    clusterMsg buf[1];
2630 2631 2632
    clusterMsg *hdr = (clusterMsg*) buf;
    uint32_t totlen;
    uint32_t channel_len, message_len;
A
antirez 已提交
2633

2634 2635 2636 2637
    channel = getDecodedObject(channel);
    message = getDecodedObject(message);
    channel_len = sdslen(channel->ptr);
    message_len = sdslen(message->ptr);
A
antirez 已提交
2638

2639 2640
    clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_PUBLISH);
    totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
2641
    totlen += sizeof(clusterMsgDataPublish) - 8 + channel_len + message_len;
2642 2643 2644 2645 2646 2647 2648

    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)) {
O
Oran Agra 已提交
2649
        payload = (unsigned char*)buf;
2650 2651
    } else {
        payload = zmalloc(totlen);
2652
        memcpy(payload,hdr,sizeof(*hdr));
2653
        hdr = (clusterMsg*) payload;
A
antirez 已提交
2654
    }
2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665
    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);
O
Oran Agra 已提交
2666
    if (payload != (unsigned char*)buf) zfree(payload);
A
antirez 已提交
2667 2668 2669 2670
}

/* 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 已提交
2671 2672
 * (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 已提交
2673 2674
 * nodes to do the same ASAP. */
void clusterSendFail(char *nodename) {
O
Oran Agra 已提交
2675
    clusterMsg buf[1];
A
antirez 已提交
2676 2677 2678
    clusterMsg *hdr = (clusterMsg*) buf;

    clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_FAIL);
A
antirez 已提交
2679
    memcpy(hdr->data.fail.about.nodename,nodename,CLUSTER_NAMELEN);
A
antirez 已提交
2680 2681 2682
    clusterBroadcastMessage(buf,ntohl(hdr->totlen));
}

2683 2684 2685 2686
/* 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) {
O
Oran Agra 已提交
2687
    clusterMsg buf[1];
2688 2689
    clusterMsg *hdr = (clusterMsg*) buf;

2690
    if (link == NULL) return;
2691
    clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_UPDATE);
A
antirez 已提交
2692
    memcpy(hdr->data.update.nodecfg.nodename,node->name,CLUSTER_NAMELEN);
2693 2694
    hdr->data.update.nodecfg.configEpoch = htonu64(node->configEpoch);
    memcpy(hdr->data.update.nodecfg.slots,node->slots,sizeof(node->slots));
O
Oran Agra 已提交
2695
    clusterSendMessage(link,(unsigned char*)buf,ntohl(hdr->totlen));
2696 2697
}

2698 2699 2700 2701 2702
/* 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) {
O
Oran Agra 已提交
2703 2704
    unsigned char *heapbuf;
    clusterMsg buf[1];
2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718
    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)) {
O
Oran Agra 已提交
2719
        heapbuf = (unsigned char*)buf;
2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731
    } 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);

O
Oran Agra 已提交
2732
    if (heapbuf != (unsigned char*)buf) zfree(heapbuf);
2733 2734 2735 2736 2737 2738 2739 2740
}

/* 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. */
2741
int clusterSendModuleMessageToTarget(const char *target, uint64_t module_id, uint8_t type, unsigned char *payload, uint32_t len) {
2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753
    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;
}

2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764
/* -----------------------------------------------------------------------------
 * 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);
}

2765 2766 2767 2768
/* -----------------------------------------------------------------------------
 * SLAVE node specific functions
 * -------------------------------------------------------------------------- */

2769 2770 2771 2772 2773 2774 2775
/* 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) {
O
Oran Agra 已提交
2776
    clusterMsg buf[1];
2777 2778 2779 2780
    clusterMsg *hdr = (clusterMsg*) buf;
    uint32_t totlen;

    clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_FAILOVER_AUTH_REQUEST);
2781 2782 2783 2784
    /* 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;
2785 2786
    totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
    hdr->totlen = htonl(totlen);
2787
    clusterBroadcastMessage(buf,totlen);
2788 2789
}

2790 2791
/* Send a FAILOVER_AUTH_ACK message to the specified node. */
void clusterSendFailoverAuth(clusterNode *node) {
O
Oran Agra 已提交
2792
    clusterMsg buf[1];
2793 2794 2795 2796 2797 2798 2799
    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);
O
Oran Agra 已提交
2800
    clusterSendMessage(node->link,(unsigned char*)buf,totlen);
2801 2802
}

2803 2804
/* Send a MFSTART message to the specified node. */
void clusterSendMFStart(clusterNode *node) {
O
Oran Agra 已提交
2805
    clusterMsg buf[1];
2806 2807 2808 2809 2810 2811 2812
    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);
O
Oran Agra 已提交
2813
    clusterSendMessage(node->link,(unsigned char*)buf,totlen);
2814 2815
}

2816
/* Vote for the node asking for our vote if there are the conditions. */
2817
void clusterSendFailoverAuthIfNeeded(clusterNode *node, clusterMsg *request) {
2818
    clusterNode *master = node->slaveof;
2819 2820 2821
    uint64_t requestCurrentEpoch = ntohu64(request->currentEpoch);
    uint64_t requestConfigEpoch = ntohu64(request->configEpoch);
    unsigned char *claimed_slots = request->myslots;
2822
    int force_ack = request->mflags[0] & CLUSTERMSG_FLAG0_FORCEACK;
2823
    int j;
2824 2825 2826

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

2831 2832 2833 2834
    /* 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. */
2835
    if (requestCurrentEpoch < server.cluster->currentEpoch) {
A
antirez 已提交
2836
        serverLog(LL_WARNING,
2837 2838 2839 2840 2841 2842
            "Failover auth denied to %.40s: reqEpoch (%llu) < curEpoch(%llu)",
            node->name,
            (unsigned long long) requestCurrentEpoch,
            (unsigned long long) server.cluster->currentEpoch);
        return;
    }
2843

2844
    /* I already voted for this epoch? Return ASAP. */
2845
    if (server.cluster->lastVoteEpoch == server.cluster->currentEpoch) {
A
antirez 已提交
2846
        serverLog(LL_WARNING,
2847 2848 2849 2850 2851
                "Failover auth denied to %.40s: already voted for epoch %llu",
                node->name,
                (unsigned long long) server.cluster->currentEpoch);
        return;
    }
2852

2853 2854 2855 2856
    /* 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 ||
2857 2858 2859
        (!nodeFailed(master) && !force_ack))
    {
        if (nodeIsMaster(node)) {
A
antirez 已提交
2860
            serverLog(LL_WARNING,
2861 2862 2863
                    "Failover auth denied to %.40s: it is a master node",
                    node->name);
        } else if (master == NULL) {
A
antirez 已提交
2864
            serverLog(LL_WARNING,
2865 2866 2867
                    "Failover auth denied to %.40s: I don't know its master",
                    node->name);
        } else if (!nodeFailed(master)) {
A
antirez 已提交
2868
            serverLog(LL_WARNING,
2869 2870 2871 2872 2873
                    "Failover auth denied to %.40s: its master is up",
                    node->name);
        }
        return;
    }
2874

2875 2876 2877
    /* 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. */
2878
    if (mstime() - node->slaveof->voted_time < server.cluster_node_timeout * 2)
2879
    {
A
antirez 已提交
2880
        serverLog(LL_WARNING,
2881 2882
                "Failover auth denied to %.40s: "
                "can't vote about this master before %lld milliseconds",
2883
                node->name,
2884 2885
                (long long) ((server.cluster_node_timeout*2)-
                             (mstime() - node->slaveof->voted_time)));
2886
        return;
2887
    }
2888

2889 2890 2891
    /* 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 已提交
2892
    for (j = 0; j < CLUSTER_SLOTS; j++) {
2893 2894
        if (bitmapTestBit(claimed_slots, j) == 0) continue;
        if (server.cluster->slots[j] == NULL ||
A
antirez 已提交
2895 2896 2897 2898
            server.cluster->slots[j]->configEpoch <= requestConfigEpoch)
        {
            continue;
        }
2899 2900 2901
        /* 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 已提交
2902
        serverLog(LL_WARNING,
2903 2904 2905 2906 2907
                "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);
2908 2909 2910
        return;
    }

2911
    /* We can vote for this slave. */
2912
    server.cluster->lastVoteEpoch = server.cluster->currentEpoch;
2913
    node->slaveof->voted_time = mstime();
2914 2915
    clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|CLUSTER_TODO_FSYNC_CONFIG);
    clusterSendFailoverAuth(node);
A
antirez 已提交
2916
    serverLog(LL_WARNING, "Failover auth granted to %.40s for epoch %llu",
2917
        node->name, (unsigned long long) server.cluster->currentEpoch);
2918 2919
}

2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936
/* 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 已提交
2937
    serverAssert(nodeIsSlave(myself));
2938 2939 2940 2941 2942 2943
    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 &&
2944
            !nodeCantFailover(master->slaves[j]) &&
2945 2946 2947 2948
            master->slaves[j]->repl_offset > myoffset) rank++;
    return rank;
}

2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961
/* 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 已提交
2962
 *    CLUSTER_CANT_FAILOVER_RELOG_PERIOD seconds elapsed.
2963 2964 2965 2966 2967
 * 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 已提交
2968
 * which is one of the integer macros CLUSTER_CANT_FAILOVER_*.
2969 2970 2971 2972 2973 2974 2975 2976 2977
 *
 * 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 已提交
2978
        time(NULL)-lastlog_time < CLUSTER_CANT_FAILOVER_RELOG_PERIOD)
2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990
        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 已提交
2991
    case CLUSTER_CANT_FAILOVER_DATA_AGE:
2992
        msg = "Disconnected from master for longer than allowed. "
2993
              "Please check the 'cluster-replica-validity-factor' configuration "
2994
              "option.";
2995
        break;
A
antirez 已提交
2996
    case CLUSTER_CANT_FAILOVER_WAITING_DELAY:
2997 2998
        msg = "Waiting the delay before I can start a new failover.";
        break;
A
antirez 已提交
2999
    case CLUSTER_CANT_FAILOVER_EXPIRED:
3000 3001
        msg = "Failover attempt expired.";
        break;
A
antirez 已提交
3002
    case CLUSTER_CANT_FAILOVER_WAITING_VOTES:
3003 3004 3005 3006 3007 3008 3009
        msg = "Waiting for votes, but majority still not reached.";
        break;
    default:
        msg = "Unknown reason code.";
        break;
    }
    lastlog_time = time(NULL);
A
antirez 已提交
3010
    serverLog(LL_WARNING,"Currently unable to failover: %s", msg);
3011 3012
}

3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029
/* 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 已提交
3030
    for (j = 0; j < CLUSTER_SLOTS; j++) {
3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048
        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();
}

3049
/* This function is called if we are a slave node and our master serving
3050
 * a non-zero amount of hash slots is in FAIL state.
3051 3052 3053
 *
 * The gaol of this function is:
 * 1) To check if we are able to perform a failover, is our data updated?
3054
 * 2) Try to get elected by masters.
3055
 * 3) Perform the failover informing all the other nodes.
3056 3057
 */
void clusterHandleSlaveFailover(void) {
3058
    mstime_t data_age;
3059
    mstime_t auth_age = mstime() - server.cluster->failover_auth_time;
3060
    int needed_quorum = (server.cluster->size / 2) + 1;
3061 3062
    int manual_failover = server.cluster->mf_end != 0 &&
                          server.cluster->mf_can_start;
3063 3064
    mstime_t auth_timeout, auth_retry_time;

3065 3066
    server.cluster->todo_before_sleep &= ~CLUSTER_TODO_HANDLE_FAILOVER;

3067 3068
    /* 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
3069
     * before trying to get voted again).
3070
     *
A
andyli 已提交
3071
     * Timeout is MAX(NODE_TIMEOUT*2,2000) milliseconds.
3072 3073 3074 3075 3076
     * 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;
3077

3078 3079
    /* Pre conditions to run the function, that must be met both in case
     * of an automatic or manual failover:
3080
     * 1) We are a slave.
3081
     * 2) Our master is flagged as FAIL, or this is a manual failover.
3082 3083 3084
     * 3) We don't have the no failover configuration set, and this is
     *    not a manual failover.
     * 4) It is serving slots. */
3085
    if (nodeIsMaster(myself) ||
3086
        myself->slaveof == NULL ||
3087
        (!nodeFailed(myself->slaveof) && !manual_failover) ||
3088
        (server.cluster_slave_no_failover && !manual_failover) ||
3089 3090 3091 3092
        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 已提交
3093
        server.cluster->cant_failover_reason = CLUSTER_CANT_FAILOVER_NONE;
3094 3095
        return;
    }
3096

3097 3098
    /* Set data_age to the number of seconds we are disconnected from
     * the master. */
A
antirez 已提交
3099
    if (server.repl_state == REPL_STATE_CONNECTED) {
3100 3101
        data_age = (mstime_t)(server.unixtime - server.master->lastinteraction)
                   * 1000;
3102
    } else {
3103
        data_age = (mstime_t)(server.unixtime - server.repl_down_since) * 1000;
3104 3105
    }

3106 3107 3108 3109 3110 3111
    /* 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;

3112 3113
    /* Check if our data is recent enough according to the slave validity
     * factor configured by the user.
3114 3115
     *
     * Check bypassed for manual failovers. */
3116 3117 3118 3119
    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)))
3120
    {
3121
        if (!manual_failover) {
A
antirez 已提交
3122
            clusterLogCantFailover(CLUSTER_CANT_FAILOVER_DATA_AGE);
3123 3124
            return;
        }
3125
    }
3126

3127 3128 3129
    /* If the previous failover attempt timedout and the retry time has
     * elapsed, we can setup a new one. */
    if (auth_age > auth_retry_time) {
3130 3131 3132
        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. */
3133
        server.cluster->failover_auth_count = 0;
3134
        server.cluster->failover_auth_sent = 0;
3135 3136 3137 3138 3139 3140
        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;
3141 3142 3143 3144
        /* 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;
C
chendianqiang 已提交
3145
	    clusterDoBeforeSleep(CLUSTER_TODO_HANDLE_FAILOVER);
3146
        }
A
antirez 已提交
3147
        serverLog(LL_WARNING,
3148 3149
            "Start of election delayed for %lld milliseconds "
            "(rank #%d, offset %lld).",
3150
            server.cluster->failover_auth_time - mstime(),
3151 3152
            server.cluster->failover_auth_rank,
            replicationGetSlaveOffset());
3153 3154 3155 3156
        /* 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);
3157 3158 3159 3160 3161
        return;
    }

    /* It is possible that we received more updated offsets from other
     * slaves for the same master since we computed our election delay.
3162 3163 3164
     * Update the delay if our rank changed.
     *
     * Not performed if this is a manual failover. */
3165 3166 3167
    if (server.cluster->failover_auth_sent == 0 &&
        server.cluster->mf_end == 0)
    {
3168 3169 3170 3171 3172 3173
        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 已提交
3174
            serverLog(LL_WARNING,
3175
                "Replica rank updated to #%d, added %lld milliseconds of delay.",
3176 3177
                newrank, added_delay);
        }
3178 3179 3180
    }

    /* Return ASAP if we can't still start the election. */
3181
    if (mstime() < server.cluster->failover_auth_time) {
A
antirez 已提交
3182
        clusterLogCantFailover(CLUSTER_CANT_FAILOVER_WAITING_DELAY);
3183 3184
        return;
    }
3185 3186

    /* Return ASAP if the election is too old to be valid. */
3187
    if (auth_age > auth_timeout) {
A
antirez 已提交
3188
        clusterLogCantFailover(CLUSTER_CANT_FAILOVER_EXPIRED);
3189 3190
        return;
    }
3191 3192 3193 3194 3195

    /* 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 已提交
3196
        serverLog(LL_WARNING,"Starting a failover election for epoch %llu.",
3197
            (unsigned long long) server.cluster->currentEpoch);
3198
        clusterRequestFailoverAuth();
3199
        server.cluster->failover_auth_sent = 1;
A
antirez 已提交
3200 3201 3202
        clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|
                             CLUSTER_TODO_UPDATE_STATE|
                             CLUSTER_TODO_FSYNC_CONFIG);
3203 3204 3205 3206
        return; /* Wait for replies. */
    }

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

A
antirez 已提交
3210
        serverLog(LL_WARNING,
A
antirez 已提交
3211
            "Failover election won: I'm the new master.");
A
antirez 已提交
3212

3213
        /* Update my configEpoch to the epoch of the election. */
3214
        if (myself->configEpoch < server.cluster->failover_auth_epoch) {
3215
            myself->configEpoch = server.cluster->failover_auth_epoch;
A
antirez 已提交
3216
            serverLog(LL_WARNING,
3217 3218 3219
                "configEpoch set to %llu after successful failover",
                (unsigned long long) myself->configEpoch);
        }
3220

J
Jack Drogon 已提交
3221
        /* Take responsibility for the cluster slots. */
3222
        clusterFailoverReplaceYourMaster();
3223
    } else {
A
antirez 已提交
3224
        clusterLogCantFailover(CLUSTER_CANT_FAILOVER_WAITING_VOTES);
3225
    }
3226 3227
}

3228 3229 3230 3231 3232 3233
/* -----------------------------------------------------------------------------
 * 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.
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

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

3264 3265
    /* Step 2: Don't migrate if my master will not be left with at least
     *         'migration-barrier' slaves after my migration. */
3266 3267 3268 3269
    if (mymaster == NULL) return;
    for (j = 0; j < mymaster->numslaves; j++)
        if (!nodeFailed(mymaster->slaves[j]) &&
            !nodeTimedOut(mymaster->slaves[j])) okslaves++;
3270
    if (okslaves <= server.cluster_migration_barrier) return;
3271

J
Jack Drogon 已提交
3272
    /* Step 3: Identify a candidate for migration, and check if among the
3273
     * masters with the greatest number of ok slaves, I'm the one with the
A
antirez 已提交
3274
     * smallest node ID (the "candidate slave").
3275
     *
J
Jack Drogon 已提交
3276
     * Note: this means that eventually a replica migration will occur
3277
     * since slaves that are reachable again always have their FAIL flag
A
antirez 已提交
3278 3279 3280 3281
     * 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. */
3282 3283 3284 3285
    candidate = myself;
    di = dictGetSafeIterator(server.cluster->nodes);
    while((de = dictNext(di)) != NULL) {
        clusterNode *node = dictGetVal(de);
A
antirez 已提交
3286
        int okslaves = 0, is_orphaned = 1;
3287

A
antirez 已提交
3288 3289 3290 3291 3292 3293
        /* 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;
3294

A
antirez 已提交
3295 3296 3297
        /* Check number of working slaves. */
        if (nodeIsMaster(node)) okslaves = clusterCountNonFailingSlaves(node);
        if (okslaves > 0) is_orphaned = 0;
A
antirez 已提交
3298

A
antirez 已提交
3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311
        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. */
3312 3313 3314 3315
        if (okslaves == max_slaves) {
            for (j = 0; j < node->numslaves; j++) {
                if (memcmp(node->slaves[j]->name,
                           candidate->name,
A
antirez 已提交
3316
                           CLUSTER_NAMELEN) < 0)
3317 3318 3319 3320 3321 3322
                {
                    candidate = node->slaves[j];
                }
            }
        }
    }
M
Matt Stancliff 已提交
3323
    dictReleaseIterator(di);
3324 3325

    /* Step 4: perform the migration if there is a target, and if I'm the
A
antirez 已提交
3326 3327 3328 3329 3330
     * 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 &&
3331 3332
        (mstime()-target->orphaned_time) > CLUSTER_SLAVE_MIGRATION_DELAY &&
       !(server.cluster_module_flags & CLUSTER_MODULE_FLAG_NO_FAILOVER))
A
antirez 已提交
3333
    {
A
antirez 已提交
3334
        serverLog(LL_WARNING,"Migrating to orphaned master %.40s",
3335 3336 3337 3338 3339
            target->name);
        clusterSetMaster(target);
    }
}

3340 3341 3342 3343 3344 3345 3346 3347
/* -----------------------------------------------------------------------------
 * 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 已提交
3348
 *    for two times the manual failover timeout CLUSTER_MF_TIMEOUT.
3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386
 *    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) {
3387
    if (server.cluster->mf_end && server.cluster->mf_end < mstime()) {
A
antirez 已提交
3388
        serverLog(LL_WARNING,"Manual failover timed out.");
3389 3390 3391 3392 3393 3394 3395 3396 3397 3398
        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;

3399
    /* If mf_can_start is non-zero, the failover was already triggered so the
3400 3401 3402 3403 3404 3405 3406 3407 3408
     * 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 已提交
3409
        serverLog(LL_WARNING,
A
antirez 已提交
3410 3411
            "All master replication stream processed, "
            "manual failover can start.");
3412 3413 3414
    }
}

A
antirez 已提交
3415 3416 3417 3418
/* -----------------------------------------------------------------------------
 * CLUSTER cron job
 * -------------------------------------------------------------------------- */

3419
/* This is executed 10 times every second */
A
antirez 已提交
3420 3421 3422
void clusterCron(void) {
    dictIterator *di;
    dictEntry *de;
3423 3424 3425 3426
    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). */
3427
    mstime_t min_pong = 0, now = mstime();
3428
    clusterNode *min_pong_node = NULL;
3429
    static unsigned long long iteration = 0;
3430
    mstime_t handshake_timeout;
3431 3432

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

3434 3435 3436 3437 3438 3439 3440 3441 3442
    /* 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;
3443 3444
        else if (prev_ip != NULL && curr_ip == NULL) changed = 1;
        else if (prev_ip && curr_ip && strcmp(prev_ip,curr_ip)) changed = 1;
3445 3446

        if (changed) {
3447 3448
            if (prev_ip) zfree(prev_ip);
            prev_ip = curr_ip;
3449

3450
            if (curr_ip) {
3451 3452 3453
                /* We always take a copy of the previous IP address, by
                 * duplicating the string. This way later we can check if
                 * the address really changed. */
3454
                prev_ip = zstrdup(prev_ip);
3455 3456 3457 3458 3459 3460 3461 3462
                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. */
            }
        }
    }

3463
    /* The handshake timeout is the time after which a handshake node that was
3464 3465 3466 3467 3468 3469
     * 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;

3470 3471 3472
    /* Update myself flags. */
    clusterUpdateMyselfFlags();

3473 3474 3475
    /* 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. */
3476
    di = dictGetSafeIterator(server.cluster->nodes);
3477
    server.cluster->stats_pfail_nodes = 0;
A
antirez 已提交
3478
    while((de = dictNext(di)) != NULL) {
3479
        clusterNode *node = dictGetVal(de);
A
antirez 已提交
3480

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

3485 3486 3487
        if (node->flags & CLUSTER_NODE_PFAIL)
            server.cluster->stats_pfail_nodes++;

3488 3489
        /* A Node in HANDSHAKE state has a limited lifespan equal to the
         * configured node timeout. */
3490
        if (nodeInHandshake(node) && now - node->ctime > handshake_timeout) {
3491
            clusterDelNode(node);
3492 3493 3494
            continue;
        }

A
antirez 已提交
3495
        if (node->link == NULL) {
3496 3497 3498 3499 3500
            clusterLink *link = createClusterLink(node);
            link->conn = server.tls_cluster ? connCreateTLS() : connCreateSocket();
            connSetPrivateData(link->conn, link);
            if (connConnect(link->conn, node->ip, node->cport, NET_FIRST_BIND_ADDR,
                        clusterLinkConnectHandler) == -1) {
3501 3502 3503 3504 3505 3506
                /* 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 已提交
3507
                serverLog(LL_DEBUG, "Unable to connect to "
3508
                    "Cluster Node [%s]:%d -> %s", node->ip,
3509
                    node->cport, server.neterr);
3510 3511

                freeClusterLink(link);
3512 3513
                continue;
            }
A
antirez 已提交
3514 3515 3516 3517 3518
            node->link = link;
        }
    }
    dictReleaseIterator(di);

3519 3520 3521
    /* Ping some random node 1 time every 10 iterations, so that we usually ping
     * one random node every second. */
    if (!(iteration % 10)) {
3522 3523
        int j;

3524 3525 3526 3527 3528 3529 3530 3531
        /* 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 已提交
3532
            if (this->flags & (CLUSTER_NODE_MYSELF|CLUSTER_NODE_HANDSHAKE))
A
antirez 已提交
3533
                continue;
3534 3535 3536 3537 3538 3539
            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 已提交
3540
            serverLog(LL_DEBUG,"Pinging node %.40s", min_pong_node->name);
3541
            clusterSendPing(min_pong_node->link, CLUSTERMSG_TYPE_PING);
A
antirez 已提交
3542 3543 3544
        }
    }

3545 3546 3547 3548 3549 3550 3551 3552 3553
    /* 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;
3554
    di = dictGetSafeIterator(server.cluster->nodes);
A
antirez 已提交
3555
    while((de = dictNext(di)) != NULL) {
3556
        clusterNode *node = dictGetVal(de);
3557
        now = mstime(); /* Use an updated time at every iteration. */
A
antirez 已提交
3558 3559

        if (node->flags &
A
antirez 已提交
3560
            (CLUSTER_NODE_MYSELF|CLUSTER_NODE_NOADDR|CLUSTER_NODE_HANDSHAKE))
3561
                continue;
3562

3563 3564 3565 3566 3567
        /* 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);

3568 3569
            /* 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
3570 3571 3572 3573
             * slave, or failed over a master that used to have slaves. */
            if (okslaves == 0 && node->numslots > 0 &&
                node->flags & CLUSTER_NODE_MIGRATE_TO)
            {
3574
                orphaned_masters++;
3575
            }
3576 3577 3578 3579 3580
            if (okslaves > max_slaves) max_slaves = okslaves;
            if (nodeIsSlave(myself) && myself->slaveof == node)
                this_slaves = okslaves;
        }

3581
        /* If we are not receiving any data for more than half the cluster
3582 3583
         * timeout, reconnect the link: maybe there is a connection
         * issue even if the node is alive. */
3584 3585
        mstime_t ping_delay = now - node->ping_sent;
        mstime_t data_delay = now - node->data_received;
3586
        if (node->link && /* is connected */
3587
            now - node->link->ctime >
3588
            server.cluster_node_timeout && /* was not already reconnected */
3589 3590 3591
            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 */
3592
            ping_delay > server.cluster_node_timeout/2 &&
3593
            /* and in such interval we are not seeing any traffic at all. */
3594
            data_delay > server.cluster_node_timeout/2)
3595 3596 3597 3598 3599 3600 3601 3602 3603
        {
            /* 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. */
3604
        if (node->link &&
3605 3606
            node->ping_sent == 0 &&
            (now - node->pong_received) > server.cluster_node_timeout/2)
3607 3608 3609 3610 3611
        {
            clusterSendPing(node->link, CLUSTERMSG_TYPE_PING);
            continue;
        }

3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622
        /* 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;
        }

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

3626 3627 3628 3629 3630 3631
        /* Check if this node looks unreachable.
         * Note that if we already received the PONG, then node->ping_sent
         * is zero, so can't reach this code at all, so we don't risk of
         * checking for a PONG delay if we didn't sent the PING.
         *
         * We also consider every incoming data as proof of liveness, since
3632 3633
         * our cluster bus link is also used for data: under heavy data
         * load pong delays are possible. */
3634 3635
        mstime_t node_delay = (ping_delay < data_delay) ? ping_delay :
                                                          data_delay;
3636

3637
        if (node_delay > server.cluster_node_timeout) {
G
guiquanz 已提交
3638
            /* Timeout reached. Set the node as possibly failing if it is
3639
             * not already in this state. */
A
antirez 已提交
3640
            if (!(node->flags & (CLUSTER_NODE_PFAIL|CLUSTER_NODE_FAIL))) {
A
antirez 已提交
3641
                serverLog(LL_DEBUG,"*** NODE %.40s possibly failing",
A
antirez 已提交
3642
                    node->name);
A
antirez 已提交
3643
                node->flags |= CLUSTER_NODE_PFAIL;
3644
                update_state = 1;
A
antirez 已提交
3645 3646 3647 3648
            }
        }
    }
    dictReleaseIterator(di);
3649 3650 3651 3652

    /* 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. */
3653
    if (nodeIsSlave(myself) &&
3654
        server.masterhost == NULL &&
3655
        myself->slaveof &&
3656
        nodeHasAddr(myself->slaveof))
3657
    {
3658
        replicationSetMaster(myself->slaveof->ip, myself->slaveof->port);
3659
    }
3660

3661 3662 3663
    /* Abourt a manual failover if the timeout is reached. */
    manualFailoverCheckTimeout();

3664
    if (nodeIsSlave(myself)) {
3665
        clusterHandleManualFailover();
3666 3667
        if (!(server.cluster_module_flags & CLUSTER_MODULE_FLAG_NO_FAILOVER))
            clusterHandleSlaveFailover();
3668 3669 3670 3671 3672 3673 3674 3675 3676
        /* 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 已提交
3677
    if (update_state || server.cluster->state == CLUSTER_FAIL)
3678
        clusterUpdateState();
3679 3680 3681 3682 3683
}

/* 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 已提交
3684 3685
 * handlers, or to perform potentially expansive tasks that we need to do
 * a single time before replying to clients. */
3686
void clusterBeforeSleep(void) {
A
antirez 已提交
3687 3688 3689
    /* 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)
3690
        clusterHandleSlaveFailover();
A
antirez 已提交
3691 3692 3693 3694 3695 3696 3697

    /* 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 已提交
3698 3699
        int fsync = server.cluster->todo_before_sleep &
                    CLUSTER_TODO_FSYNC_CONFIG;
A
antirez 已提交
3700
        clusterSaveConfigOrDie(fsync);
3701
    }
A
antirez 已提交
3702

3703 3704
    /* Reset our flags (not strictly needed since every single function
     * called for flags set should be able to clear its flag). */
A
antirez 已提交
3705 3706 3707 3708 3709
    server.cluster->todo_before_sleep = 0;
}

void clusterDoBeforeSleep(int flags) {
    server.cluster->todo_before_sleep |= flags;
A
antirez 已提交
3710 3711 3712 3713 3714 3715
}

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

3716
/* Test bit 'pos' in a generic bitmap. Return 1 if the bit is set,
3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737
 * 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);
}

3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754
/* 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 已提交
3755 3756
/* Set the slot bit and return the old value. */
int clusterNodeSetSlotBit(clusterNode *n, int slot) {
3757 3758
    int old = bitmapTestBit(n->slots,slot);
    bitmapSetBit(n->slots,slot);
3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776
    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 已提交
3777 3778 3779 3780 3781
    return old;
}

/* Clear the slot bit and return the old value. */
int clusterNodeClearSlotBit(clusterNode *n, int slot) {
3782 3783
    int old = bitmapTestBit(n->slots,slot);
    bitmapClearBit(n->slots,slot);
3784
    if (old) n->numslots--;
A
antirez 已提交
3785 3786 3787 3788 3789
    return old;
}

/* Return the slot bit from the cluster node structure. */
int clusterNodeGetSlotBit(clusterNode *n, int slot) {
3790
    return bitmapTestBit(n->slots,slot);
A
antirez 已提交
3791 3792 3793
}

/* Add the specified slot to the list of slots that node 'n' will
3794
 * serve. Return C_OK if the operation ended with success.
A
antirez 已提交
3795
 * If the slot is already assigned to another instance this is considered
3796
 * an error and C_ERR is returned. */
A
antirez 已提交
3797
int clusterAddSlot(clusterNode *n, int slot) {
3798
    if (server.cluster->slots[slot]) return C_ERR;
3799
    clusterNodeSetSlotBit(n,slot);
3800
    server.cluster->slots[slot] = n;
3801
    return C_OK;
A
antirez 已提交
3802 3803
}

A
antirez 已提交
3804
/* Delete the specified slot marking it as unassigned.
3805 3806
 * Returns C_OK if the slot was assigned, otherwise if the slot was
 * already unassigned C_ERR is returned. */
A
antirez 已提交
3807
int clusterDelSlot(int slot) {
3808
    clusterNode *n = server.cluster->slots[slot];
A
antirez 已提交
3809

3810
    if (!n) return C_ERR;
A
antirez 已提交
3811
    serverAssert(clusterNodeClearSlotBit(n,slot) == 1);
3812
    server.cluster->slots[slot] = NULL;
3813
    return C_OK;
A
antirez 已提交
3814 3815
}

3816 3817 3818 3819 3820
/* 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 已提交
3821
    for (j = 0; j < CLUSTER_SLOTS; j++) {
3822 3823 3824 3825
        if (clusterNodeGetSlotBit(node,j)) {
            clusterDelSlot(j);
            deleted++;
        }
3826 3827 3828 3829
    }
    return deleted;
}

A
antirez 已提交
3830 3831 3832 3833 3834 3835 3836 3837 3838
/* 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 已提交
3839 3840 3841
/* -----------------------------------------------------------------------------
 * Cluster state evaluation function
 * -------------------------------------------------------------------------- */
3842

3843
/* The following are defines that are only used in the evaluation function
J
Jack Drogon 已提交
3844
 * and are based on heuristics. Actually the main point about the rejoin and
3845 3846
 * writable delay is that they should be a few orders of magnitude larger
 * than the network latency. */
A
antirez 已提交
3847 3848 3849
#define CLUSTER_MAX_REJOIN_DELAY 5000
#define CLUSTER_MIN_REJOIN_DELAY 500
#define CLUSTER_WRITABLE_DELAY 2000
3850

A
antirez 已提交
3851
void clusterUpdateState(void) {
3852
    int j, new_state;
3853
    int reachable_masters = 0;
3854
    static mstime_t among_minority_time;
3855 3856
    static mstime_t first_call_time = 0;

3857 3858
    server.cluster->todo_before_sleep &= ~CLUSTER_TODO_UPDATE_STATE;

3859 3860 3861 3862 3863 3864 3865
    /* 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();
3866
    if (nodeIsMaster(myself) &&
A
antirez 已提交
3867 3868
        server.cluster->state == CLUSTER_FAIL &&
        mstime() - first_call_time < CLUSTER_WRITABLE_DELAY) return;
A
antirez 已提交
3869

3870 3871
    /* Start assuming the state is OK. We'll turn it into FAIL if there
     * are the right conditions. */
A
antirez 已提交
3872
    new_state = CLUSTER_OK;
3873

3874
    /* Check if all the slots are covered. */
3875
    if (server.cluster_require_full_coverage) {
A
antirez 已提交
3876
        for (j = 0; j < CLUSTER_SLOTS; j++) {
3877
            if (server.cluster->slots[j] == NULL ||
A
antirez 已提交
3878
                server.cluster->slots[j]->flags & (CLUSTER_NODE_FAIL))
3879
            {
A
antirez 已提交
3880
                new_state = CLUSTER_FAIL;
3881 3882
                break;
            }
A
antirez 已提交
3883 3884
        }
    }
3885

3886
    /* Compute the cluster size, that is the number of master nodes
3887 3888
     * serving at least a single slot.
     *
3889 3890
     * At the same time count the number of reachable masters having
     * at least one slot. */
3891 3892 3893 3894 3895
    {
        dictIterator *di;
        dictEntry *de;

        server.cluster->size = 0;
3896
        di = dictGetSafeIterator(server.cluster->nodes);
3897 3898 3899
        while((de = dictNext(di)) != NULL) {
            clusterNode *node = dictGetVal(de);

3900
            if (nodeIsMaster(node) && node->numslots) {
3901
                server.cluster->size++;
A
antirez 已提交
3902
                if ((node->flags & (CLUSTER_NODE_FAIL|CLUSTER_NODE_PFAIL)) == 0)
3903
                    reachable_masters++;
3904
            }
3905 3906 3907
        }
        dictReleaseIterator(di);
    }
3908

3909 3910
    /* If we are in a minority partition, change the cluster state
     * to FAIL. */
3911 3912
    {
        int needed_quorum = (server.cluster->size / 2) + 1;
3913

3914
        if (reachable_masters < needed_quorum) {
A
antirez 已提交
3915
            new_state = CLUSTER_FAIL;
3916 3917
            among_minority_time = mstime();
        }
3918 3919
    }

3920
    /* Log a state change */
3921 3922 3923 3924 3925 3926 3927
    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 已提交
3928 3929 3930 3931
        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;
3932

A
antirez 已提交
3933
        if (new_state == CLUSTER_OK &&
3934
            nodeIsMaster(myself) &&
3935 3936 3937 3938 3939 3940
            mstime() - among_minority_time < rejoin_delay)
        {
            return;
        }

        /* Change the state and log the event. */
A
antirez 已提交
3941
        serverLog(LL_WARNING,"Cluster state changed: %s",
A
antirez 已提交
3942
            new_state == CLUSTER_OK ? "ok" : "fail");
3943 3944
        server.cluster->state = new_state;
    }
A
antirez 已提交
3945 3946
}

3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957
/* 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.
3958
 * 2) If we find data in a DB different than DB0 we return C_ERR to
3959 3960 3961
 *    signal the caller it should quit the server with an error message
 *    or take other actions.
 *
3962
 * The function always returns C_OK even if it will try to correct
3963
 * the error described in "1". However if data is found in DB different
3964
 * from DB0, C_ERR is returned.
3965 3966 3967 3968 3969
 *
 * 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) {
3970 3971 3972
    int j;
    int update_config = 0;

3973 3974 3975 3976 3977
    /* Return ASAP if a module disabled cluster redirections. In that case
     * every master can store keys about every possible hash slot. */
    if (server.cluster_module_flags & CLUSTER_MODULE_FLAG_NO_REDIRECTION)
        return C_OK;

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

3982 3983
    /* Make sure we only have keys in DB0. */
    for (j = 1; j < server.dbnum; j++) {
3984
        if (dictSize(server.db[j].dict)) return C_ERR;
3985 3986 3987 3988
    }

    /* Check that all the slots we see populated memory have a corresponding
     * entry in the cluster table. Otherwise fix the table. */
A
antirez 已提交
3989
    for (j = 0; j < CLUSTER_SLOTS; j++) {
3990 3991 3992 3993
        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. */
3994
        if (server.cluster->slots[j] == myself ||
3995 3996 3997 3998 3999 4000 4001
            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++;
4002
        /* Case A: slot is unassigned. Take responsibility for it. */
4003
        if (server.cluster->slots[j] == NULL) {
A
antirez 已提交
4004
            serverLog(LL_WARNING, "I have keys for unassigned slot %d. "
4005
                                    "Taking responsibility for it.",j);
4006
            clusterAddSlot(myself,j);
4007
        } else {
A
antirez 已提交
4008
            serverLog(LL_WARNING, "I have keys for slot %d, but the slot is "
4009 4010
                                    "assigned to another node. "
                                    "Setting it to importing state.",j);
4011 4012 4013
            server.cluster->importing_slots_from[j] = server.cluster->slots[j];
        }
    }
A
antirez 已提交
4014
    if (update_config) clusterSaveConfigOrDie(1);
4015
    return C_OK;
4016 4017
}

4018 4019 4020 4021
/* -----------------------------------------------------------------------------
 * SLAVE nodes handling
 * -------------------------------------------------------------------------- */

4022 4023
/* Set the specified node 'n' as master for this node.
 * If this node is currently a master, it is turned into a slave. */
4024
void clusterSetMaster(clusterNode *n) {
A
antirez 已提交
4025 4026
    serverAssert(n != myself);
    serverAssert(myself->numslots == 0);
4027

4028
    if (nodeIsMaster(myself)) {
4029
        myself->flags &= ~(CLUSTER_NODE_MASTER|CLUSTER_NODE_MIGRATE_TO);
A
antirez 已提交
4030
        myself->flags |= CLUSTER_NODE_SLAVE;
4031
        clusterCloseAllSlots();
4032 4033 4034
    } else {
        if (myself->slaveof)
            clusterNodeRemoveSlave(myself->slaveof,myself);
4035 4036
    }
    myself->slaveof = n;
4037
    clusterNodeAddSlave(n,myself);
4038
    replicationSetMaster(n->ip, n->port);
4039
    resetManualFailover();
4040 4041
}

A
antirez 已提交
4042
/* -----------------------------------------------------------------------------
4043
 * Nodes to string representation functions.
A
antirez 已提交
4044 4045
 * -------------------------------------------------------------------------- */

4046 4047 4048 4049 4050 4051
struct redisNodeFlags {
    uint16_t flag;
    char *name;
};

static struct redisNodeFlags redisNodeFlagsTable[] = {
4052 4053 4054 4055 4056 4057
    {CLUSTER_NODE_MYSELF,       "myself,"},
    {CLUSTER_NODE_MASTER,       "master,"},
    {CLUSTER_NODE_SLAVE,        "slave,"},
    {CLUSTER_NODE_PFAIL,        "fail?,"},
    {CLUSTER_NODE_FAIL,         "fail,"},
    {CLUSTER_NODE_HANDSHAKE,    "handshake,"},
4058 4059
    {CLUSTER_NODE_NOADDR,       "noaddr,"},
    {CLUSTER_NODE_NOFAILOVER,   "nofailover,"}
4060 4061 4062 4063
};

/* Concatenate the comma separated list of node flags to the given SDS
 * string 'ci'. */
4064
sds representClusterNodeFlags(sds ci, uint16_t flags) {
4065 4066 4067 4068 4069 4070 4071 4072
    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,");
4073 4074 4075 4076
    sdsIncrLen(ci,-1); /* Remove trailing comma. */
    return ci;
}

4077 4078 4079
/* Generate a csv-alike representation of the specified cluster node.
 * See clusterGenNodesDescription() top comment for more information.
 *
4080 4081
 * The function returns the string representation as an SDS string. */
sds clusterGenNodeDescription(clusterNode *node) {
4082
    int j, start;
4083
    sds ci;
4084 4085

    /* Node coordinates */
4086
    ci = sdscatprintf(sdsempty(),"%.40s %s:%d@%d ",
4087 4088
        node->name,
        node->ip,
4089 4090
        node->port,
        node->cport);
4091 4092

    /* Flags */
4093
    ci = representClusterNodeFlags(ci, node->flags);
4094 4095

    /* Slave of... or just "-" */
4096 4097 4098
    if (node->slaveof)
        ci = sdscatprintf(ci," %.40s ",node->slaveof->name);
    else
4099
        ci = sdscatlen(ci," - ",3);
4100

A
antirez 已提交
4101
    /* Latency from the POV of this node, config epoch, link status */
4102
    ci = sdscatprintf(ci,"%lld %lld %llu %s",
4103 4104 4105
        (long long) node->ping_sent,
        (long long) node->pong_received,
        (unsigned long long) node->configEpoch,
A
antirez 已提交
4106
        (node->link || node->flags & CLUSTER_NODE_MYSELF) ?
4107 4108 4109 4110
                    "connected" : "disconnected");

    /* Slots served by this instance */
    start = -1;
A
antirez 已提交
4111
    for (j = 0; j < CLUSTER_SLOTS; j++) {
4112 4113 4114 4115 4116
        int bit;

        if ((bit = clusterNodeGetSlotBit(node,j)) != 0) {
            if (start == -1) start = j;
        }
A
antirez 已提交
4117 4118
        if (start != -1 && (!bit || j == CLUSTER_SLOTS-1)) {
            if (bit && j == CLUSTER_SLOTS-1) j++;
4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131

            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 已提交
4132 4133
    if (node->flags & CLUSTER_NODE_MYSELF) {
        for (j = 0; j < CLUSTER_SLOTS; j++) {
4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145
            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;
}

4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158
/* 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) {
4159
    sds ci = sdsempty(), ni;
A
antirez 已提交
4160 4161 4162
    dictIterator *di;
    dictEntry *de;

4163
    di = dictGetSafeIterator(server.cluster->nodes);
A
antirez 已提交
4164
    while((de = dictNext(di)) != NULL) {
4165
        clusterNode *node = dictGetVal(de);
A
antirez 已提交
4166

4167
        if (node->flags & filter) continue;
4168 4169 4170
        ni = clusterGenNodeDescription(node);
        ci = sdscatsds(ci,ni);
        sdsfree(ni);
4171
        ci = sdscatlen(ci,"\n",1);
A
antirez 已提交
4172 4173 4174 4175 4176
    }
    dictReleaseIterator(di);
    return ci;
}

4177 4178 4179 4180
/* -----------------------------------------------------------------------------
 * CLUSTER command
 * -------------------------------------------------------------------------- */

4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191
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";
4192
    case CLUSTERMSG_TYPE_MODULE: return "module";
4193 4194 4195 4196
    }
    return "unknown";
}

4197
int getSlotOrReply(client *c, robj *o) {
4198 4199
    long long slot;

4200
    if (getLongLongFromObject(o,&slot) != C_OK ||
A
antirez 已提交
4201
        slot < 0 || slot >= CLUSTER_SLOTS)
4202 4203 4204 4205 4206 4207 4208
    {
        addReplyError(c,"Invalid or out of range slot");
        return -1;
    }
    return (int) slot;
}

4209
void clusterReplyMultiBulkSlots(client *c) {
4210 4211 4212 4213
    /* Format: 1) 1) start slot
     *            2) end slot
     *            3) 1) master IP
     *               2) master port
4214
     *               3) node ID
4215 4216
     *            4) 1) replica IP
     *               2) replica port
4217
     *               3) node ID
4218 4219 4220
     *           ... continued until done
     */

4221
    int num_masters = 0;
4222
    void *slot_replylen = addReplyDeferredLen(c);
4223 4224 4225 4226 4227 4228

    dictEntry *de;
    dictIterator *di = dictGetSafeIterator(server.cluster->nodes);
    while((de = dictNext(di)) != NULL) {
        clusterNode *node = dictGetVal(de);
        int j = 0, start = -1;
Y
yanhui13 已提交
4229
        int i, nested_elements = 0;
4230

4231 4232 4233
        /* 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;
4234

Y
yanhui13 已提交
4235 4236 4237 4238 4239
        for(i = 0; i < node->numslaves; i++) {
            if (nodeFailed(node->slaves[i])) continue;
            nested_elements++;
        }

A
antirez 已提交
4240
        for (j = 0; j < CLUSTER_SLOTS; j++) {
4241
            int bit, i;
4242 4243 4244 4245

            if ((bit = clusterNodeGetSlotBit(node,j)) != 0) {
                if (start == -1) start = j;
            }
A
antirez 已提交
4246
            if (start != -1 && (!bit || j == CLUSTER_SLOTS-1)) {
Y
yanhui13 已提交
4247
                addReplyArrayLen(c, nested_elements + 3); /* slots (2) + master addr (1). */
4248

A
antirez 已提交
4249
                if (bit && j == CLUSTER_SLOTS-1) j++;
4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262

                /* 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 */
4263
                addReplyArrayLen(c, 3);
4264 4265
                addReplyBulkCString(c, node->ip);
                addReplyLongLong(c, node->port);
4266
                addReplyBulkCBuffer(c, node->name, CLUSTER_NAMELEN);
4267 4268 4269 4270 4271

                /* 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 */
4272
                    if (nodeFailed(node->slaves[i])) continue;
4273
                    addReplyArrayLen(c, 3);
4274 4275
                    addReplyBulkCString(c, node->slaves[i]->ip);
                    addReplyLongLong(c, node->slaves[i]->port);
4276
                    addReplyBulkCBuffer(c, node->slaves[i]->name, CLUSTER_NAMELEN);
4277
                }
4278
                num_masters++;
4279 4280 4281 4282
            }
        }
    }
    dictReleaseIterator(di);
4283
    setDeferredArrayLen(c, slot_replylen, num_masters);
4284 4285
}

4286
void clusterCommand(client *c) {
A
antirez 已提交
4287 4288 4289 4290 4291
    if (server.cluster_enabled == 0) {
        addReplyError(c,"This instance has cluster support disabled");
        return;
    }

I
Itamar Haber 已提交
4292 4293
    if (c->argc == 2 && !strcasecmp(c->argv[1]->ptr,"help")) {
        const char *help[] = {
4294 4295 4296 4297 4298
"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.",
4299
"FAILOVER [force|takeover] -- Promote current replica node to being a master.",
4300 4301 4302
"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.",
H
hwware 已提交
4303
"INFO - Return information about the cluster.",
4304 4305 4306 4307
"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:",
4308
"    <id> <ip:port> <flags> <master> <pings> <pongs> <epoch> <link> <slot> ... <slot>",
4309
"REPLICATE <node-id> -- Configure current node as replica to <node-id>.",
4310 4311 4312
"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.",
4313
"REPLICAS <node-id> -- Return <node-id> replicas.",
H
hwware 已提交
4314
"SAVECONFIG - Force saving cluster configuration on disk.",
4315
"SLOTS -- Return information about slots range mappings. Each range is made of:",
4316 4317
"    start, end, master and replicas IP addresses, ports and ids",
NULL
I
Itamar Haber 已提交
4318 4319 4320
        };
        addReplyHelp(c, help);
    } else if (!strcasecmp(c->argv[1]->ptr,"meet") && (c->argc == 4 || c->argc == 5)) {
4321 4322
        /* CLUSTER MEET <ip> <port> [cport] */
        long long port, cport;
A
antirez 已提交
4323

4324
        if (getLongLongFromObject(c->argv[3], &port) != C_OK) {
4325
            addReplyErrorFormat(c,"Invalid TCP base port specified: %s",
4326
                                (char*)c->argv[3]->ptr);
A
antirez 已提交
4327 4328 4329
            return;
        }

4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340
        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 &&
4341 4342
            errno == EINVAL)
        {
4343 4344
            addReplyErrorFormat(c,"Invalid node address specified: %s:%s",
                            (char*)c->argv[2]->ptr, (char*)c->argv[3]->ptr);
4345 4346 4347
        } else {
            addReply(c,shared.ok);
        }
A
antirez 已提交
4348
    } else if (!strcasecmp(c->argv[1]->ptr,"nodes") && c->argc == 2) {
4349
        /* CLUSTER NODES */
4350 4351 4352
        sds nodes = clusterGenNodesDescription(0);
        addReplyVerbatim(c,nodes,sdslen(nodes),"txt");
        sdsfree(nodes);
M
Michel Martens 已提交
4353 4354
    } else if (!strcasecmp(c->argv[1]->ptr,"myid") && c->argc == 2) {
        /* CLUSTER MYID */
A
antirez 已提交
4355
        addReplyBulkCBuffer(c,myself->name, CLUSTER_NAMELEN);
4356 4357 4358
    } else if (!strcasecmp(c->argv[1]->ptr,"slots") && c->argc == 2) {
        /* CLUSTER SLOTS */
        clusterReplyMultiBulkSlots(c);
4359 4360 4361 4362 4363 4364
    } 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;
        }
4365
        clusterDelNodeSlots(myself);
A
antirez 已提交
4366
        clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
4367
        addReply(c,shared.ok);
A
antirez 已提交
4368
    } else if ((!strcasecmp(c->argv[1]->ptr,"addslots") ||
A
antirez 已提交
4369 4370 4371 4372
               !strcasecmp(c->argv[1]->ptr,"delslots")) && c->argc >= 3)
    {
        /* CLUSTER ADDSLOTS <slot> [slot] ... */
        /* CLUSTER DELSLOTS <slot> [slot] ... */
4373
        int j, slot;
A
antirez 已提交
4374
        unsigned char *slots = zmalloc(CLUSTER_SLOTS);
A
antirez 已提交
4375
        int del = !strcasecmp(c->argv[1]->ptr,"delslots");
A
antirez 已提交
4376

A
antirez 已提交
4377
        memset(slots,0,CLUSTER_SLOTS);
4378
        /* Check that all the arguments are parseable and that all the
A
antirez 已提交
4379 4380
         * slots are not already busy. */
        for (j = 2; j < c->argc; j++) {
4381
            if ((slot = getSlotOrReply(c,c->argv[j])) == -1) {
A
antirez 已提交
4382 4383 4384
                zfree(slots);
                return;
            }
4385
            if (del && server.cluster->slots[slot] == NULL) {
4386
                addReplyErrorFormat(c,"Slot %d is already unassigned", slot);
A
antirez 已提交
4387 4388
                zfree(slots);
                return;
4389
            } else if (!del && server.cluster->slots[slot]) {
4390
                addReplyErrorFormat(c,"Slot %d is already busy", slot);
A
antirez 已提交
4391 4392 4393 4394 4395 4396 4397 4398 4399 4400
                zfree(slots);
                return;
            }
            if (slots[slot]++ == 1) {
                addReplyErrorFormat(c,"Slot %d specified multiple times",
                    (int)slot);
                zfree(slots);
                return;
            }
        }
A
antirez 已提交
4401
        for (j = 0; j < CLUSTER_SLOTS; j++) {
A
antirez 已提交
4402
            if (slots[j]) {
4403 4404
                int retval;

4405
                /* If this slot was set as importing we can clear this
4406
                 * state as now we are the real owner of the slot. */
4407 4408
                if (server.cluster->importing_slots_from[j])
                    server.cluster->importing_slots_from[j] = NULL;
4409 4410

                retval = del ? clusterDelSlot(j) :
4411
                               clusterAddSlot(myself,j);
4412
                serverAssertWithInfo(c,NULL,retval == C_OK);
A
antirez 已提交
4413 4414 4415
            }
        }
        zfree(slots);
A
antirez 已提交
4416
        clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
A
antirez 已提交
4417
        addReply(c,shared.ok);
4418
    } else if (!strcasecmp(c->argv[1]->ptr,"setslot") && c->argc >= 4) {
A
antirez 已提交
4419 4420
        /* SETSLOT 10 MIGRATING <node ID> */
        /* SETSLOT 10 IMPORTING <node ID> */
4421
        /* SETSLOT 10 STABLE */
A
antirez 已提交
4422
        /* SETSLOT 10 NODE <node ID> */
4423
        int slot;
4424 4425
        clusterNode *n;

4426 4427 4428 4429 4430
        if (nodeIsSlave(myself)) {
            addReplyError(c,"Please use SETSLOT only with masters.");
            return;
        }

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

4433
        if (!strcasecmp(c->argv[3]->ptr,"migrating") && c->argc == 5) {
4434
            if (server.cluster->slots[slot] != myself) {
4435 4436 4437
                addReplyErrorFormat(c,"I'm not the owner of hash slot %u",slot);
                return;
            }
4438 4439 4440 4441 4442
            if ((n = clusterLookupNode(c->argv[4]->ptr)) == NULL) {
                addReplyErrorFormat(c,"I don't know about node %s",
                    (char*)c->argv[4]->ptr);
                return;
            }
4443
            server.cluster->migrating_slots_to[slot] = n;
4444
        } else if (!strcasecmp(c->argv[3]->ptr,"importing") && c->argc == 5) {
4445
            if (server.cluster->slots[slot] == myself) {
4446 4447 4448 4449
                addReplyErrorFormat(c,
                    "I'm already the owner of hash slot %u",slot);
                return;
            }
4450 4451
            if ((n = clusterLookupNode(c->argv[4]->ptr)) == NULL) {
                addReplyErrorFormat(c,"I don't know about node %s",
L
Leon Chen 已提交
4452
                    (char*)c->argv[4]->ptr);
4453 4454
                return;
            }
4455
            server.cluster->importing_slots_from[slot] = n;
4456
        } else if (!strcasecmp(c->argv[3]->ptr,"stable") && c->argc == 4) {
4457
            /* CLUSTER SETSLOT <SLOT> STABLE */
4458 4459
            server.cluster->importing_slots_from[slot] = NULL;
            server.cluster->migrating_slots_to[slot] = NULL;
4460
        } else if (!strcasecmp(c->argv[3]->ptr,"node") && c->argc == 5) {
4461 4462 4463
            /* CLUSTER SETSLOT <SLOT> NODE <NODE ID> */
            clusterNode *n = clusterLookupNode(c->argv[4]->ptr);

4464 4465 4466 4467 4468
            if (!n) {
                addReplyErrorFormat(c,"Unknown node %s",
                    (char*)c->argv[4]->ptr);
                return;
            }
4469 4470
            /* If this hash slot was served by 'myself' before to switch
             * make sure there are no longer local keys for this hash slot. */
4471
            if (server.cluster->slots[slot] == myself && n != myself) {
4472
                if (countKeysInSlot(slot) != 0) {
A
antirez 已提交
4473 4474 4475
                    addReplyErrorFormat(c,
                        "Can't assign hashslot %d to a different node "
                        "while I still hold keys for this hash slot.", slot);
4476 4477 4478
                    return;
                }
            }
4479 4480
            /* If this slot is in migrating status but we have no keys
             * for it assigning the slot to another node will clear
4481
             * the migratig status. */
4482
            if (countKeysInSlot(slot) == 0 &&
4483 4484
                server.cluster->migrating_slots_to[slot])
                server.cluster->migrating_slots_to[slot] = NULL;
4485

4486 4487
            /* If this node was importing this slot, assigning the slot to
             * itself also clears the importing status. */
4488
            if (n == myself &&
4489
                server.cluster->importing_slots_from[slot])
4490 4491
            {
                /* This slot was manually migrated, set this node configEpoch
4492 4493 4494
                 * to a new epoch so that the new version can be propagated
                 * by the cluster.
                 *
4495 4496 4497 4498 4499
                 * 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. */
4500
                if (clusterBumpConfigEpochWithoutConsensus() == C_OK) {
A
antirez 已提交
4501
                    serverLog(LL_WARNING,
4502
                        "configEpoch updated after importing slot %d", slot);
4503
                }
4504
                server.cluster->importing_slots_from[slot] = NULL;
4505
            }
4506 4507
            clusterDelSlot(slot);
            clusterAddSlot(n,slot);
4508
        } else {
A
antirez 已提交
4509
            addReplyError(c,
4510
                "Invalid CLUSTER SETSLOT action or number of arguments. Try CLUSTER HELP");
4511
            return;
4512
        }
4513
        clusterDoBeforeSleep(CLUSTER_TODO_SAVE_CONFIG|CLUSTER_TODO_UPDATE_STATE);
4514
        addReply(c,shared.ok);
4515 4516 4517 4518 4519 4520 4521
    } 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 已提交
4522
    } else if (!strcasecmp(c->argv[1]->ptr,"info") && c->argc == 2) {
4523
        /* CLUSTER INFO */
A
antirez 已提交
4524 4525
        char *statestr[] = {"ok","fail","needhelp"};
        int slots_assigned = 0, slots_ok = 0, slots_pfail = 0, slots_fail = 0;
4526
        uint64_t myepoch;
A
antirez 已提交
4527 4528
        int j;

A
antirez 已提交
4529
        for (j = 0; j < CLUSTER_SLOTS; j++) {
4530
            clusterNode *n = server.cluster->slots[j];
A
antirez 已提交
4531 4532 4533

            if (n == NULL) continue;
            slots_assigned++;
4534
            if (nodeFailed(n)) {
A
antirez 已提交
4535
                slots_fail++;
4536
            } else if (nodeTimedOut(n)) {
A
antirez 已提交
4537 4538 4539 4540 4541 4542
                slots_pfail++;
            } else {
                slots_ok++;
            }
        }

4543 4544 4545
        myepoch = (nodeIsSlave(myself) && myself->slaveof) ?
                  myself->slaveof->configEpoch : myself->configEpoch;

A
antirez 已提交
4546 4547 4548 4549 4550 4551
        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"
4552
            "cluster_known_nodes:%lu\r\n"
4553
            "cluster_size:%d\r\n"
4554
            "cluster_current_epoch:%llu\r\n"
4555
            "cluster_my_epoch:%llu\r\n"
4556
            , statestr[server.cluster->state],
A
antirez 已提交
4557 4558 4559
            slots_assigned,
            slots_ok,
            slots_pfail,
4560
            slots_fail,
4561
            dictSize(server.cluster->nodes),
4562
            server.cluster->size,
4563
            (unsigned long long) server.cluster->currentEpoch,
4564
            (unsigned long long) myepoch
A
antirez 已提交
4565
        );
4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593

        /* 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. */
4594 4595
        addReplyVerbatim(c,info,sdslen(info),"txt");
        sdsfree(info);
4596
    } else if (!strcasecmp(c->argv[1]->ptr,"saveconfig") && c->argc == 2) {
A
antirez 已提交
4597
        int retval = clusterSaveConfig(1);
4598 4599 4600 4601 4602 4603

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

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

4613
        if (getLongLongFromObjectOrReply(c,c->argv[2],&slot,NULL) != C_OK)
4614
            return;
A
antirez 已提交
4615
        if (slot < 0 || slot >= CLUSTER_SLOTS) {
4616 4617 4618
            addReplyError(c,"Invalid slot");
            return;
        }
4619
        addReplyLongLong(c,countKeysInSlot(slot));
A
antirez 已提交
4620
    } else if (!strcasecmp(c->argv[1]->ptr,"getkeysinslot") && c->argc == 4) {
4621
        /* CLUSTER GETKEYSINSLOT <slot> <count> */
A
antirez 已提交
4622
        long long maxkeys, slot;
4623
        unsigned int numkeys, j;
A
antirez 已提交
4624 4625
        robj **keys;

4626
        if (getLongLongFromObjectOrReply(c,c->argv[2],&slot,NULL) != C_OK)
A
antirez 已提交
4627
            return;
A
antirez 已提交
4628
        if (getLongLongFromObjectOrReply(c,c->argv[3],&maxkeys,NULL)
4629
            != C_OK)
A
antirez 已提交
4630
            return;
A
antirez 已提交
4631
        if (slot < 0 || slot >= CLUSTER_SLOTS || maxkeys < 0) {
A
antirez 已提交
4632 4633 4634 4635
            addReplyError(c,"Invalid slot or number of keys");
            return;
        }

4636 4637 4638 4639 4640
        /* 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 已提交
4641
        keys = zmalloc(sizeof(robj*)*maxkeys);
4642
        numkeys = getKeysInSlot(slot, keys, maxkeys);
4643
        addReplyArrayLen(c,numkeys);
4644 4645 4646 4647
        for (j = 0; j < numkeys; j++) {
            addReplyBulk(c,keys[j]);
            decrRefCount(keys[j]);
        }
A
antirez 已提交
4648
        zfree(keys);
A
antirez 已提交
4649 4650 4651 4652
    } else if (!strcasecmp(c->argv[1]->ptr,"forget") && c->argc == 3) {
        /* CLUSTER FORGET <NODE ID> */
        clusterNode *n = clusterLookupNode(c->argv[2]->ptr);

4653
        if (!n) {
A
antirez 已提交
4654 4655
            addReplyErrorFormat(c,"Unknown node %s", (char*)c->argv[2]->ptr);
            return;
4656
        } else if (n == myself) {
4657 4658
            addReplyError(c,"I tried hard but I can't forget myself...");
            return;
4659
        } else if (nodeIsSlave(myself) && myself->slaveof == n) {
4660 4661
            addReplyError(c,"Can't forget my master!");
            return;
A
antirez 已提交
4662
        }
4663
        clusterBlacklistAddNode(n);
A
antirez 已提交
4664
        clusterDelNode(n);
A
antirez 已提交
4665 4666
        clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|
                             CLUSTER_TODO_SAVE_CONFIG);
A
antirez 已提交
4667
        addReply(c,shared.ok);
4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678
    } 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. */
4679
        if (n == myself) {
4680 4681 4682 4683 4684
            addReplyError(c,"Can't replicate myself");
            return;
        }

        /* Can't replicate a slave. */
4685
        if (nodeIsSlave(n)) {
4686
            addReplyError(c,"I can only replicate a master, not a replica.");
4687 4688 4689
            return;
        }

4690 4691 4692
        /* 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. */
4693 4694
        if (nodeIsMaster(myself) &&
            (myself->numslots != 0 || dictSize(server.db[0].dict) != 0)) {
A
antirez 已提交
4695 4696 4697
            addReplyError(c,
                "To set a master the node must be empty and "
                "without assigned slots.");
4698 4699 4700 4701 4702
            return;
        }

        /* Set the master. */
        clusterSetMaster(n);
A
antirez 已提交
4703
        clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
4704
        addReply(c,shared.ok);
4705 4706
    } else if ((!strcasecmp(c->argv[1]->ptr,"slaves") ||
                !strcasecmp(c->argv[1]->ptr,"replicas")) && c->argc == 3) {
4707 4708 4709 4710 4711 4712 4713 4714 4715 4716
        /* 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;
        }

4717
        if (nodeIsSlave(n)) {
4718 4719 4720 4721
            addReplyError(c,"The specified node is not a master");
            return;
        }

4722
        addReplyArrayLen(c,n->numslaves);
4723
        for (j = 0; j < n->numslaves; j++) {
4724
            sds ni = clusterGenNodeDescription(n->slaves[j]);
4725 4726 4727
            addReplyBulkCString(c,ni);
            sdsfree(ni);
        }
4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739
    } 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 已提交
4740 4741 4742
    } else if (!strcasecmp(c->argv[1]->ptr,"failover") &&
               (c->argc == 2 || c->argc == 3))
    {
4743 4744
        /* CLUSTER FAILOVER [FORCE|TAKEOVER] */
        int force = 0, takeover = 0;
A
antirez 已提交
4745 4746 4747 4748

        if (c->argc == 3) {
            if (!strcasecmp(c->argv[2]->ptr,"force")) {
                force = 1;
4749 4750 4751
            } else if (!strcasecmp(c->argv[2]->ptr,"takeover")) {
                takeover = 1;
                force = 1; /* Takeover also implies force. */
A
antirez 已提交
4752 4753 4754 4755 4756 4757
            } else {
                addReply(c,shared.syntaxerr);
                return;
            }
        }

4758
        /* Check preconditions. */
4759
        if (nodeIsMaster(myself)) {
4760
            addReplyError(c,"You should send CLUSTER FAILOVER to a replica");
4761
            return;
4762
        } else if (myself->slaveof == NULL) {
4763
            addReplyError(c,"I'm a replica but my master is unknown to me");
4764
            return;
A
antirez 已提交
4765
        } else if (!force &&
4766 4767
                   (nodeFailed(myself->slaveof) ||
                    myself->slaveof->link == NULL))
4768 4769 4770 4771 4772 4773
        {
            addReplyError(c,"Master is down or failed, "
                            "please use CLUSTER FAILOVER FORCE");
            return;
        }
        resetManualFailover();
A
antirez 已提交
4774
        server.cluster->mf_end = mstime() + CLUSTER_MF_TIMEOUT;
A
antirez 已提交
4775

4776 4777 4778 4779 4780
        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 已提交
4781
            serverLog(LL_WARNING,"Taking over the master (user request).");
4782 4783 4784 4785 4786 4787
            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 已提交
4788
            serverLog(LL_WARNING,"Forced failover user request accepted.");
A
antirez 已提交
4789 4790
            server.cluster->mf_can_start = 1;
        } else {
A
antirez 已提交
4791
            serverLog(LL_WARNING,"Manual failover user request accepted.");
A
antirez 已提交
4792 4793
            clusterSendMFStart(myself->slaveof);
        }
4794
        addReply(c,shared.ok);
A
antirez 已提交
4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805
    } 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;

4806
        if (getLongLongFromObjectOrReply(c,c->argv[2],&epoch,NULL) != C_OK)
A
antirez 已提交
4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817
            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 已提交
4818
            serverLog(LL_WARNING,
4819 4820 4821
                "configEpoch set to %llu via CLUSTER SET-CONFIG-EPOCH",
                (unsigned long long) myself->configEpoch);

4822
            if (server.cluster->currentEpoch < (uint64_t)epoch)
4823
                server.cluster->currentEpoch = epoch;
A
antirez 已提交
4824 4825 4826 4827 4828 4829 4830
            /* 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 已提交
4831 4832 4833 4834 4835 4836 4837 4838 4839 4840
    } 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;
4841
            } else if (!strcasecmp(c->argv[2]->ptr,"soft")) {
A
antirez 已提交
4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857
                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 已提交
4858
    } else {
4859
        addReplySubcommandSyntaxError(c);
I
Itamar Haber 已提交
4860
        return;
A
antirez 已提交
4861 4862 4863 4864
    }
}

/* -----------------------------------------------------------------------------
4865
 * DUMP, RESTORE and MIGRATE commands
A
antirez 已提交
4866 4867
 * -------------------------------------------------------------------------- */

4868 4869
/* Generates a DUMP-format representation of the object 'o', adding it to the
 * io stream pointed by 'rio'. This function can't fail. */
4870
void createDumpPayload(rio *payload, robj *o, robj *key) {
4871 4872
    unsigned char buf[2];
    uint64_t crc;
4873 4874 4875 4876

    /* 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 已提交
4877
    serverAssert(rdbSaveObjectType(payload,o));
4878
    serverAssert(rdbSaveObject(payload,o,key));
4879 4880

    /* Write the footer, this is how it looks like:
4881 4882 4883 4884 4885
     * ----------------+---------------------+---------------+
     * ... RDB payload | 2 bytes RDB version | 8 bytes CRC64 |
     * ----------------+---------------------+---------------+
     * RDB version and CRC are both in little endian.
     */
4886 4887

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

4892
    /* CRC64 */
4893
    crc = crc64(0,(unsigned char*)payload->io.buffer.ptr,
4894 4895 4896
                sdslen(payload->io.buffer.ptr));
    memrev64ifbe(&crc);
    payload->io.buffer.ptr = sdscatlen(payload->io.buffer.ptr,&crc,8);
4897 4898 4899
}

/* Verify that the RDB version of the dump payload matches the one of this Redis
4900
 * instance and that the checksum is ok.
4901
 * If the DUMP payload looks valid C_OK is returned, otherwise C_ERR
4902 4903
 * is returned. */
int verifyDumpPayload(unsigned char *p, size_t len) {
4904
    unsigned char *footer;
4905
    uint16_t rdbver;
4906
    uint64_t crc;
4907

4908
    /* At least 2 bytes of RDB version and 8 of CRC64 should be present. */
4909
    if (len < 10) return C_ERR;
4910
    footer = p+(len-10);
4911 4912

    /* Verify RDB version */
4913
    rdbver = (footer[1] << 8) | footer[0];
4914
    if (rdbver > RDB_VERSION) return C_ERR;
4915

4916
    /* Verify CRC64 */
4917
    crc = crc64(0,p,len-8);
4918
    memrev64ifbe(&crc);
4919
    return (memcmp(&crc,footer+2,8) == 0) ? C_OK : C_ERR;
4920 4921 4922 4923 4924
}

/* 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. */
4925
void dumpCommand(client *c) {
4926
    robj *o;
4927 4928 4929 4930
    rio payload;

    /* Check if the key is here. */
    if ((o = lookupKeyRead(c->db,c->argv[1])) == NULL) {
A
antirez 已提交
4931
        addReplyNull(c);
4932 4933 4934 4935
        return;
    }

    /* Create the DUMP encoded representation. */
4936
    createDumpPayload(&payload,o,c->argv[1]);
4937 4938

    /* Transfer to the client */
4939
    addReplyBulkSds(c,payload.io.buffer.ptr);
4940 4941 4942
    return;
}

A
antirez 已提交
4943
/* RESTORE key ttl serialized-value [REPLACE] */
4944
void restoreCommand(client *c) {
4945
    long long ttl, lfu_freq = -1, lru_idle = -1, lru_clock = -1;
4946
    rio payload;
4947
    int j, type, replace = 0, absttl = 0;
4948
    robj *obj;
A
antirez 已提交
4949

A
antirez 已提交
4950 4951
    /* Parse additional options */
    for (j = 4; j < c->argc; j++) {
4952
        int additional = c->argc-j-1;
A
antirez 已提交
4953 4954
        if (!strcasecmp(c->argv[j]->ptr,"replace")) {
            replace = 1;
4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977
        } 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 已提交
4978 4979 4980 4981 4982 4983
        } else {
            addReply(c,shared.syntaxerr);
            return;
        }
    }

A
antirez 已提交
4984
    /* Make sure this key does not already exist here... */
A
antirez 已提交
4985
    if (!replace && lookupKeyWrite(c->db,c->argv[1]) != NULL) {
4986
        addReply(c,shared.busykeyerr);
A
antirez 已提交
4987 4988 4989 4990
        return;
    }

    /* Check if the TTL value makes sense */
4991
    if (getLongLongFromObjectOrReply(c,c->argv[2],&ttl,NULL) != C_OK) {
A
antirez 已提交
4992 4993 4994 4995 4996 4997
        return;
    } else if (ttl < 0) {
        addReplyError(c,"Invalid TTL value, must be >= 0");
        return;
    }

4998
    /* Verify RDB version and data checksum. */
4999
    if (verifyDumpPayload(c->argv[3]->ptr,sdslen(c->argv[3]->ptr)) == C_ERR)
5000
    {
5001 5002 5003 5004
        addReplyError(c,"DUMP payload version or checksum are wrong");
        return;
    }

5005
    rioInitWithBuffer(&payload,c->argv[3]->ptr);
5006
    if (((type = rdbLoadObjectType(&payload)) == -1) ||
5007
        ((obj = rdbLoadObject(type,&payload,c->argv[1]->ptr)) == NULL))
5008
    {
5009
        addReplyError(c,"Bad data format");
A
antirez 已提交
5010 5011 5012
        return;
    }

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

A
antirez 已提交
5016
    /* Create the key and set the TTL if any */
5017
    dbAdd(c->db,c->argv[1],obj);
5018 5019 5020 5021
    if (ttl) {
        if (!absttl) ttl+=mstime();
        setExpire(c,c->db,c->argv[1],ttl);
    }
5022
    objectSetLRUOrLFU(obj,lfu_freq,lru_idle,lru_clock,1000);
5023
    signalModifiedKey(c,c->db,c->argv[1]);
5024
    notifyKeyspaceEvent(NOTIFY_GENERIC,"restore",c->argv[1],c->db->id);
A
antirez 已提交
5025
    addReply(c,shared.ok);
5026
    server.dirty++;
A
antirez 已提交
5027 5028
}

A
antirez 已提交
5029 5030 5031 5032 5033 5034 5035
/* 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. */
5036
#define MIGRATE_SOCKET_CACHE_TTL 10 /* close cached sockets after 10 sec. */
A
antirez 已提交
5037 5038

typedef struct migrateCachedSocket {
5039
    connection *conn;
5040
    long last_dbid;
A
antirez 已提交
5041 5042 5043
    time_t last_use_time;
} migrateCachedSocket;

5044 5045
/* Return a migrateCachedSocket containing a TCP socket connected with the
 * target instance, possibly returning a cached one.
A
antirez 已提交
5046 5047 5048 5049 5050 5051 5052
 *
 * 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()
5053
 * should be called so that the connection will be created from scratch
A
antirez 已提交
5054
 * the next time. */
5055
migrateCachedSocket* migrateGetSocket(client *c, robj *host, robj *port, long timeout) {
5056
    connection *conn;
A
antirez 已提交
5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067
    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;
5068
        return cs;
A
antirez 已提交
5069 5070 5071 5072 5073 5074 5075
    }

    /* 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);
5076
        connClose(cs->conn);
A
antirez 已提交
5077 5078 5079 5080 5081
        zfree(cs);
        dictDelete(server.migrate_cached_sockets,dictGetKey(de));
    }

    /* Create the socket */
5082 5083 5084
    conn = server.tls_cluster ? connCreateTLS() : connCreateSocket();
    if (connBlockingConnect(conn, c->argv[1]->ptr, atoi(c->argv[2]->ptr), timeout)
            != C_OK) {
A
antirez 已提交
5085 5086
        addReplySds(c,
            sdsnew("-IOERR error or timeout connecting to the client\r\n"));
5087 5088
        connClose(conn);
        sdsfree(name);
5089
        return NULL;
A
antirez 已提交
5090
    }
5091
    connEnableTcpNoDelay(conn);
A
antirez 已提交
5092 5093 5094

    /* Add to the cache and return it to the caller. */
    cs = zmalloc(sizeof(*cs));
5095 5096
    cs->conn = conn;

5097
    cs->last_dbid = -1;
A
antirez 已提交
5098 5099
    cs->last_use_time = server.unixtime;
    dictAdd(server.migrate_cached_sockets,name,cs);
5100
    return cs;
A
antirez 已提交
5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116
}

/* 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;
    }

5117
    connClose(cs->conn);
A
antirez 已提交
5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130
    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) {
5131
            connClose(cs->conn);
A
antirez 已提交
5132 5133 5134 5135 5136 5137 5138
            zfree(cs);
            dictDelete(server.migrate_cached_sockets,dictGetKey(de));
        }
    }
    dictReleaseIterator(di);
}

A
antirez 已提交
5139 5140
/* MIGRATE host port key dbid timeout [COPY | REPLACE | AUTH password |
 *         AUTH2 username password]
A
antirez 已提交
5141 5142 5143
 *
 * On in the multiple keys form:
 *
A
antirez 已提交
5144 5145
 * MIGRATE host port "" dbid timeout [COPY | REPLACE | AUTH password |
 *         AUTH2 username password] KEYS key1 key2 ... keyN */
5146
void migrateCommand(client *c) {
5147
    migrateCachedSocket *cs;
A
antirez 已提交
5148
    int copy = 0, replace = 0, j;
A
antirez 已提交
5149
    char *username = NULL;
A
antirez 已提交
5150
    char *password = NULL;
A
antirez 已提交
5151 5152
    long timeout;
    long dbid;
A
antirez 已提交
5153 5154 5155
    robj **ov = NULL; /* Objects to migrate. */
    robj **kv = NULL; /* Key names. */
    robj **newargv = NULL; /* Used to rewrite the command as DEL ... keys ... */
5156
    rio cmd, payload;
5157
    int may_retry = 1;
A
antirez 已提交
5158
    int write_error = 0;
5159
    int argv_rewritten = 0;
A
antirez 已提交
5160 5161 5162 5163

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

A
antirez 已提交
5165 5166
    /* Parse additional options */
    for (j = 6; j < c->argc; j++) {
A
antirez 已提交
5167
        int moreargs = (c->argc-1) - j;
A
antirez 已提交
5168 5169 5170 5171
        if (!strcasecmp(c->argv[j]->ptr,"copy")) {
            copy = 1;
        } else if (!strcasecmp(c->argv[j]->ptr,"replace")) {
            replace = 1;
A
antirez 已提交
5172 5173 5174 5175 5176 5177 5178
        } else if (!strcasecmp(c->argv[j]->ptr,"auth")) {
            if (!moreargs) {
                addReply(c,shared.syntaxerr);
                return;
            }
            j++;
            password = c->argv[j]->ptr;
A
antirez 已提交
5179 5180 5181 5182 5183 5184 5185
        } else if (!strcasecmp(c->argv[j]->ptr,"auth2")) {
            if (moreargs < 2) {
                addReply(c,shared.syntaxerr);
                return;
            }
            username = c->argv[++j]->ptr;
            password = c->argv[++j]->ptr;
A
antirez 已提交
5186 5187 5188 5189 5190 5191 5192 5193 5194 5195
        } 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 已提交
5196 5197 5198 5199 5200 5201
        } else {
            addReply(c,shared.syntaxerr);
            return;
        }
    }

A
antirez 已提交
5202
    /* Sanity check */
5203 5204 5205
    if (getLongFromObjectOrReply(c,c->argv[5],&timeout,NULL) != C_OK ||
        getLongFromObjectOrReply(c,c->argv[4],&dbid,NULL) != C_OK)
    {
A
antirez 已提交
5206
        return;
5207
    }
5208
    if (timeout <= 0) timeout = 1000;
A
antirez 已提交
5209

A
antirez 已提交
5210 5211 5212 5213 5214
    /* 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 已提交
5215 5216
    ov = zrealloc(ov,sizeof(robj*)*num_keys);
    kv = zrealloc(kv,sizeof(robj*)*num_keys);
A
antirez 已提交
5217
    int oi = 0;
A
antirez 已提交
5218

A
antirez 已提交
5219 5220 5221 5222 5223 5224 5225 5226 5227
    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);
5228
        addReplySds(c,sdsnew("+NOKEY\r\n"));
A
antirez 已提交
5229 5230
        return;
    }
5231

A
antirez 已提交
5232 5233 5234
try_again:
    write_error = 0;

A
antirez 已提交
5235
    /* Connect */
5236
    cs = migrateGetSocket(c,c->argv[1],c->argv[2],timeout);
5237 5238 5239 5240
    if (cs == NULL) {
        zfree(ov); zfree(kv);
        return; /* error sent to the client by migrateGetSocket() */
    }
A
antirez 已提交
5241

5242
    rioInitWithBuffer(&cmd,sdsempty());
5243

A
antirez 已提交
5244 5245
    /* Authentication */
    if (password) {
A
antirez 已提交
5246 5247
        int arity = username ? 3 : 2;
        serverAssertWithInfo(c,NULL,rioWriteBulkCount(&cmd,'*',arity));
A
antirez 已提交
5248
        serverAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,"AUTH",4));
A
antirez 已提交
5249 5250 5251 5252
        if (username) {
            serverAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,username,
                                 sdslen(username)));
        }
A
antirez 已提交
5253 5254 5255 5256
        serverAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,password,
            sdslen(password)));
    }

A
antirez 已提交
5257 5258 5259
    /* 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 已提交
5260 5261 5262
        serverAssertWithInfo(c,NULL,rioWriteBulkCount(&cmd,'*',2));
        serverAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,"SELECT",6));
        serverAssertWithInfo(c,NULL,rioWriteBulkLongLong(&cmd,dbid));
5263
    }
A
antirez 已提交
5264

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

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

A
antirez 已提交
5275 5276
        if (expireat != -1) {
            ttl = expireat-mstime();
5277 5278 5279
            if (ttl < 0) {
                continue;
            }
A
antirez 已提交
5280 5281
            if (ttl < 1) ttl = 1;
        }
5282 5283 5284 5285

        /* Relocate valid (non expired) keys into the array in successive
         * positions to remove holes created by the keys that were present
         * in the first lookup but are now expired after the second lookup. */
5286 5287
        kv[non_expired++] = kv[j];

A
antirez 已提交
5288 5289 5290
        serverAssertWithInfo(c,NULL,
            rioWriteBulkCount(&cmd,'*',replace ? 5 : 4));

A
antirez 已提交
5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302
        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. */
5303
        createDumpPayload(&payload,ov[j],kv[j]);
A
antirez 已提交
5304
        serverAssertWithInfo(c,NULL,
A
antirez 已提交
5305 5306 5307 5308 5309 5310 5311 5312 5313
            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));
    }
5314 5315

    /* Fix the actual number of keys we are migrating. */
5316
    num_keys = non_expired;
A
antirez 已提交
5317

G
guiquanz 已提交
5318
    /* Transfer the query to the other node in 64K chunks. */
A
antirez 已提交
5319
    errno = 0;
A
antirez 已提交
5320
    {
5321 5322
        sds buf = cmd.io.buffer.ptr;
        size_t pos = 0, towrite;
5323
        int nwritten = 0;
5324 5325 5326

        while ((towrite = sdslen(buf)-pos) > 0) {
            towrite = (towrite > (64*1024) ? (64*1024) : towrite);
5327
            nwritten = connSyncWrite(cs->conn,buf+pos,towrite,timeout);
A
antirez 已提交
5328 5329 5330 5331
            if (nwritten != (signed)towrite) {
                write_error = 1;
                goto socket_err;
            }
5332
            pos += nwritten;
A
antirez 已提交
5333 5334 5335
        }
    }

A
antirez 已提交
5336
    char buf0[1024]; /* Auth reply. */
A
antirez 已提交
5337 5338
    char buf1[1024]; /* Select reply. */
    char buf2[1024]; /* Restore reply. */
A
antirez 已提交
5339

A
antirez 已提交
5340
    /* Read the AUTH reply if needed. */
5341
    if (password && connSyncReadLine(cs->conn, buf0, sizeof(buf0), timeout) <= 0)
A
antirez 已提交
5342 5343
        goto socket_err;

A
antirez 已提交
5344
    /* Read the SELECT reply if needed. */
5345
    if (select && connSyncReadLine(cs->conn, buf1, sizeof(buf1), timeout) <= 0)
A
antirez 已提交
5346 5347 5348 5349
        goto socket_err;

    /* Read the RESTORE replies. */
    int error_from_target = 0;
5350
    int socket_error = 0;
5351 5352
    int del_idx = 1; /* Index of the key argument for the replicated DEL op. */

5353 5354 5355 5356
    /* 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. */
5357
    if (!copy) newargv = zmalloc(sizeof(robj*)*(num_keys+1));
5358

5359
    for (j = 0; j < num_keys; j++) {
5360
        if (connSyncReadLine(cs->conn, buf2, sizeof(buf2), timeout) <= 0) {
5361 5362 5363
            socket_error = 1;
            break;
        }
5364 5365 5366 5367
        if ((password && buf0[0] == '-') ||
            (select && buf1[0] == '-') ||
            buf2[0] == '-')
        {
A
antirez 已提交
5368
            /* On error assume that last_dbid is no longer valid. */
5369 5370
            if (!error_from_target) {
                cs->last_dbid = -1;
A
antirez 已提交
5371
                char *errbuf;
5372
                if (password && buf0[0] == '-') errbuf = buf0;
A
antirez 已提交
5373 5374 5375
                else if (select && buf1[0] == '-') errbuf = buf1;
                else errbuf = buf2;

5376
                error_from_target = 1;
A
antirez 已提交
5377 5378
                addReplyErrorFormat(c,"Target instance replied with error: %s",
                    errbuf+1);
5379
            }
A
antirez 已提交
5380
        } else {
A
antirez 已提交
5381 5382
            if (!copy) {
                /* No COPY option: remove the local key, signal the change. */
A
antirez 已提交
5383
                dbDelete(c->db,kv[j]);
5384
                signalModifiedKey(c,c->db,kv[j]);
5385
                notifyKeyspaceEvent(NOTIFY_GENERIC,"del",kv[j],c->db->id);
A
antirez 已提交
5386
                server.dirty++;
5387

5388 5389
                /* Populate the argument vector to replace the old one. */
                newargv[del_idx++] = kv[j];
5390
                incrRefCount(kv[j]);
5391
            }
A
antirez 已提交
5392 5393 5394
        }
    }

5395 5396 5397 5398 5399 5400 5401 5402 5403
    /* 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.*/
    }

5404 5405 5406 5407 5408
    /* 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]);

5409
    if (!copy) {
5410 5411 5412
        /* 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. */
5413 5414
        if (del_idx > 1) {
            newargv[0] = createStringObject("DEL",3);
5415
            /* Note that the following call takes ownership of newargv. */
5416
            replaceClientCommandVector(c,del_idx,newargv);
5417
            argv_rewritten = 1;
5418 5419 5420 5421
        } else {
            /* No key transfer acknowledged, no need to rewrite as DEL. */
            zfree(newargv);
        }
5422 5423 5424 5425
        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.
5426 5427
     * 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. */
5428 5429 5430
    if (!error_from_target && socket_error) {
        may_retry = 0;
        goto socket_err;
5431 5432
    }

A
antirez 已提交
5433
    if (!error_from_target) {
A
antirez 已提交
5434
        /* Success! Update the last_dbid in migrateCachedSocket, so that we can
5435 5436 5437 5438 5439
         * 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 已提交
5440 5441 5442
        cs->last_dbid = dbid;
        addReply(c,shared.ok);
    } else {
5443
        /* On error we already sent it in the for loop above, and set
A
antirez 已提交
5444
         * the currently selected socket to -1 to force SELECT the next time. */
A
antirez 已提交
5445
    }
A
antirez 已提交
5446

5447
    sdsfree(cmd.io.buffer.ptr);
5448
    zfree(ov); zfree(kv); zfree(newargv);
5449
    return;
A
antirez 已提交
5450

A
antirez 已提交
5451 5452 5453 5454
/* 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 已提交
5455 5456
    /* Cleanup we want to perform in both the retry and no retry case.
     * Note: Closing the migrate socket will also force SELECT next time. */
5457
    sdsfree(cmd.io.buffer.ptr);
5458 5459 5460 5461 5462 5463

    /* 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 已提交
5464 5465 5466 5467 5468
    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). */
5469 5470 5471 5472
    if (errno != ETIMEDOUT && may_retry) {
        may_retry = 0;
        goto try_again;
    }
A
antirez 已提交
5473 5474 5475

    /* Cleanup we want to do if no retry is attempted. */
    zfree(ov); zfree(kv);
A
antirez 已提交
5476
    addReplySds(c,
A
antirez 已提交
5477 5478 5479
        sdscatprintf(sdsempty(),
            "-IOERR error or timeout %s to target instance\r\n",
            write_error ? "writing" : "reading"));
5480 5481 5482
    return;
}

5483 5484 5485 5486
/* -----------------------------------------------------------------------------
 * Cluster functions related to serving / redirecting clients
 * -------------------------------------------------------------------------- */

5487
/* The ASKING command is required after a -ASK redirection.
G
guiquanz 已提交
5488
 * The client should issue ASKING before to actually send the command to
5489 5490
 * the target instance. See the Redis Cluster specification for more
 * information. */
5491
void askingCommand(client *c) {
5492 5493 5494 5495
    if (server.cluster_enabled == 0) {
        addReplyError(c,"This instance has cluster support disabled");
        return;
    }
A
antirez 已提交
5496
    c->flags |= CLIENT_ASKING;
5497 5498 5499
    addReply(c,shared.ok);
}

5500
/* The READONLY command is used by clients to enter the read-only mode.
5501 5502
 * 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. */
5503
void readonlyCommand(client *c) {
5504 5505 5506 5507
    if (server.cluster_enabled == 0) {
        addReplyError(c,"This instance has cluster support disabled");
        return;
    }
A
antirez 已提交
5508
    c->flags |= CLIENT_READONLY;
5509 5510 5511 5512
    addReply(c,shared.ok);
}

/* The READWRITE command just clears the READONLY command state. */
5513
void readwriteCommand(client *c) {
A
antirez 已提交
5514
    c->flags &= ~CLIENT_READONLY;
5515 5516
    addReply(c,shared.ok);
}
A
antirez 已提交
5517

5518
/* Return the pointer to the cluster node that is able to serve the command.
5519
 * For the function to succeed the command should only target either:
A
antirez 已提交
5520
 *
5521 5522 5523
 * 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).
5524
 *
5525 5526 5527
 * 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 已提交
5528 5529
 * 'error_code', which will be set to CLUSTER_REDIR_ASK or
 * CLUSTER_REDIR_MOVED.
5530
 *
A
antirez 已提交
5531
 * When the node is 'myself' 'error_code' is set to CLUSTER_REDIR_NONE.
5532 5533 5534 5535
 *
 * 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 已提交
5536
 * CLUSTER_REDIR_CROSS_SLOT if the request contains multiple keys that
5537 5538
 * don't belong to the same hash slot.
 *
A
antirez 已提交
5539
 * CLUSTER_REDIR_UNSTABLE if the request contains multiple keys
5540
 * belonging to the same slot, but the slot is not stable (in migration or
5541 5542
 * importing state, likely because a resharding is in progress).
 *
A
antirez 已提交
5543
 * CLUSTER_REDIR_DOWN_UNBOUND if the request addresses a slot which is
5544 5545
 * 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,
5546 5547
 * so we also handle it here.
 *
5548
 * CLUSTER_REDIR_DOWN_STATE and CLUSTER_REDIR_DOWN_RO_STATE if the cluster is
5549
 * down but the user attempts to execute a command that addresses one or more keys. */
5550
clusterNode *getNodeByQuery(client *c, struct redisCommand *cmd, robj **argv, int argc, int *hashslot, int *error_code) {
A
antirez 已提交
5551
    clusterNode *n = NULL;
5552
    robj *firstkey = NULL;
5553
    int multiple_keys = 0;
A
antirez 已提交
5554 5555
    multiState *ms, _ms;
    multiCmd mc;
5556 5557
    int i, slot = 0, migrating_slot = 0, importing_slot = 0, missing_keys = 0;

5558 5559 5560 5561
    /* Allow any key to be set if a module disabled cluster redirections. */
    if (server.cluster_module_flags & CLUSTER_MODULE_FLAG_NO_REDIRECTION)
        return myself;

5562
    /* Set error code optimistically for the base case. */
A
antirez 已提交
5563
    if (error_code) *error_code = CLUSTER_REDIR_NONE;
A
antirez 已提交
5564

5565 5566 5567 5568
    /* Modules can turn off Redis Cluster redirection: this is useful
     * when writing a module that implements a completely different
     * distributed system. */

A
antirez 已提交
5569 5570 5571
    /* 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 已提交
5572
        /* If CLIENT_MULTI flag is not set EXEC is just going to return an
A
antirez 已提交
5573
         * error. */
A
antirez 已提交
5574
        if (!(c->flags & CLIENT_MULTI)) return myself;
A
antirez 已提交
5575 5576
        ms = &c->mstate;
    } else {
5577 5578 5579
        /* 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 已提交
5580 5581 5582 5583 5584 5585 5586 5587
        ms = &_ms;
        _ms.commands = &mc;
        _ms.count = 1;
        mc.argv = argv;
        mc.argc = argc;
        mc.cmd = cmd;
    }

5588 5589
    /* Check that all the keys are in the same hash slot, and obtain this
     * slot and the node associated. */
A
antirez 已提交
5590 5591 5592 5593 5594 5595 5596 5597 5598
    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;

5599
        keyindex = getKeysFromCommand(mcmd,margv,margc,&numkeys);
A
antirez 已提交
5600
        for (j = 0; j < numkeys; j++) {
5601 5602 5603 5604
            robj *thiskey = margv[keyindex[j]];
            int thisslot = keyHashSlot((char*)thiskey->ptr,
                                       sdslen(thiskey->ptr));

5605 5606 5607
            if (firstkey == NULL) {
                /* This is the first key we see. Check what is the slot
                 * and node. */
5608 5609
                firstkey = thiskey;
                slot = thisslot;
5610
                n = server.cluster->slots[slot];
5611 5612 5613 5614 5615 5616 5617 5618

                /* 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 已提交
5619
                        *error_code = CLUSTER_REDIR_DOWN_UNBOUND;
5620 5621 5622
                    return NULL;
                }

5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634
                /* 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 已提交
5635
            } else {
5636 5637
                /* If it is not the first key, make sure it is exactly
                 * the same key as the first we saw. */
5638 5639 5640 5641 5642
                if (!equalStringObjects(firstkey,thiskey)) {
                    if (slot != thisslot) {
                        /* Error: multiple keys from different slots. */
                        getKeysFreeResult(keyindex);
                        if (error_code)
A
antirez 已提交
5643
                            *error_code = CLUSTER_REDIR_CROSS_SLOT;
5644 5645 5646 5647 5648 5649
                        return NULL;
                    } else {
                        /* Flag this request as one with multiple different
                         * keys. */
                        multiple_keys = 1;
                    }
5650
                }
A
antirez 已提交
5651
            }
5652 5653 5654 5655 5656 5657 5658

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

5663
    /* No key at all in command? then we can serve the request
5664
     * without redirections or errors in all the cases. */
5665
    if (n == NULL) return myself;
5666

5667 5668
    /* Cluster is globally down but we got keys? We only serve the request
     * if it is a read command and when allow_reads_when_down is enabled. */
5669 5670
    if (server.cluster->state != CLUSTER_OK) {
        if (!server.cluster_allow_reads_when_down) {
A
antirez 已提交
5671 5672
            /* The cluster is configured to block commands when the
             * cluster is down. */
5673 5674
            if (error_code) *error_code = CLUSTER_REDIR_DOWN_STATE;
            return NULL;
A
antirez 已提交
5675 5676 5677 5678 5679 5680
        } else if (!(cmd->flags & CMD_READONLY) && !(cmd->proc == evalCommand)
                && !(cmd->proc == evalShaCommand))
        {
            /* The cluster is configured to allow read only commands
             * but this command is neither readonly, nor EVAL or
             * EVALSHA. */
5681 5682
            if (error_code) *error_code = CLUSTER_REDIR_DOWN_RO_STATE;
            return NULL;
A
antirez 已提交
5683 5684 5685 5686
        } else {
            /* Fall through and allow the command to be executed:
             * this happens when server.cluster_allow_reads_when_down is
             * true and the command is a readonly command or EVAL / EVALSHA. */
5687
        }
5688 5689
    }

5690
    /* Return the hashslot by reference. */
5691
    if (hashslot) *hashslot = slot;
5692

5693 5694 5695 5696 5697
    /* 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;
5698 5699

    /* If we don't have all the keys and we are migrating the slot, send
5700 5701
     * an ASK redirection. */
    if (migrating_slot && missing_keys) {
A
antirez 已提交
5702
        if (error_code) *error_code = CLUSTER_REDIR_ASK;
5703 5704 5705
        return server.cluster->migrating_slots_to[slot];
    }

5706 5707 5708 5709
    /* 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. */
5710
    if (importing_slot &&
A
antirez 已提交
5711
        (c->flags & CLIENT_ASKING || cmd->flags & CMD_ASKING))
5712
    {
5713
        if (multiple_keys && missing_keys) {
A
antirez 已提交
5714
            if (error_code) *error_code = CLUSTER_REDIR_UNSTABLE;
5715 5716 5717 5718
            return NULL;
        } else {
            return myself;
        }
5719
    }
5720

5721 5722 5723
    /* 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 已提交
5724
    if (c->flags & CLIENT_READONLY &&
5725 5726
        (cmd->flags & CMD_READONLY || cmd->proc == evalCommand ||
         cmd->proc == evalShaCommand) &&
5727
        nodeIsSlave(myself) &&
5728
        myself->slaveof == n)
5729
    {
5730
        return myself;
5731
    }
5732 5733 5734

    /* 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 已提交
5735
    if (n != myself && error_code) *error_code = CLUSTER_REDIR_MOVED;
5736
    return n;
A
antirez 已提交
5737
}
5738 5739

/* Send the client the right redirection code, according to error_code
A
antirez 已提交
5740
 * that should be set to one of CLUSTER_REDIR_* macros.
5741
 *
A
antirez 已提交
5742
 * If CLUSTER_REDIR_ASK or CLUSTER_REDIR_MOVED error codes
5743 5744 5745
 * 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. */
5746
void clusterRedirectClient(client *c, clusterNode *n, int hashslot, int error_code) {
A
antirez 已提交
5747
    if (error_code == CLUSTER_REDIR_CROSS_SLOT) {
5748
        addReplySds(c,sdsnew("-CROSSSLOT Keys in request don't hash to the same slot\r\n"));
A
antirez 已提交
5749
    } else if (error_code == CLUSTER_REDIR_UNSTABLE) {
J
Jack Drogon 已提交
5750
        /* The request spawns multiple keys in the same slot,
5751 5752 5753
         * 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 已提交
5754
    } else if (error_code == CLUSTER_REDIR_DOWN_STATE) {
5755
        addReplySds(c,sdsnew("-CLUSTERDOWN The cluster is down\r\n"));
5756 5757
    } else if (error_code == CLUSTER_REDIR_DOWN_RO_STATE) {
        addReplySds(c,sdsnew("-CLUSTERDOWN The cluster is down and only accepts read commands\r\n"));
A
antirez 已提交
5758
    } else if (error_code == CLUSTER_REDIR_DOWN_UNBOUND) {
5759
        addReplySds(c,sdsnew("-CLUSTERDOWN Hash slot not served\r\n"));
A
antirez 已提交
5760 5761
    } else if (error_code == CLUSTER_REDIR_MOVED ||
               error_code == CLUSTER_REDIR_ASK)
5762 5763 5764
    {
        addReplySds(c,sdscatprintf(sdsempty(),
            "-%s %d %s:%d\r\n",
A
antirez 已提交
5765
            (error_code == CLUSTER_REDIR_ASK) ? "ASK" : "MOVED",
5766 5767
            hashslot,n->ip,n->port));
    } else {
A
antirez 已提交
5768
        serverPanic("getNodeByQuery() unknown error.");
5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782
    }
}

/* 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. */
5783
int clusterRedirectBlockedClientIfNeeded(client *c) {
5784 5785 5786 5787 5788
    if (c->flags & CLIENT_BLOCKED &&
        (c->btype == BLOCKED_LIST ||
         c->btype == BLOCKED_ZSET ||
         c->btype == BLOCKED_STREAM))
    {
5789 5790 5791
        dictEntry *de;
        dictIterator *di;

5792 5793 5794 5795
        /* If the cluster is down, unblock the client with the right error.
         * If the cluster is configured to allow reads on cluster down, we
         * still want to emit this error since a write will be required
         * to unblock them which may never come.  */
A
antirez 已提交
5796 5797
        if (server.cluster->state == CLUSTER_FAIL) {
            clusterRedirectClient(c,NULL,0,CLUSTER_REDIR_DOWN_STATE);
5798 5799 5800
            return 1;
        }

5801
        /* All keys must belong to the same slot, so check first key only. */
5802
        di = dictGetIterator(c->bpop.keys);
5803
        if ((de = dictNext(di)) != NULL) {
5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815
            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 已提交
5816
                        CLUSTER_REDIR_DOWN_UNBOUND);
5817 5818
                } else {
                    clusterRedirectClient(c,node,slot,
A
antirez 已提交
5819
                        CLUSTER_REDIR_MOVED);
5820
                }
5821
                dictReleaseIterator(di);
5822 5823 5824 5825 5826 5827 5828
                return 1;
            }
        }
        dictReleaseIterator(di);
    }
    return 0;
}