Redis奇幻之旅(四)3.哨兵机制

3.哨兵机制

​ 在《4.1 集群设计绕不开的话题》中我们提到了单点故障的问题,在《4.2 主从复制》中我们又提到了使用从库来做主库的备份,保证数据尽量不丢失。不过问题来了,如果主库挂掉了,我们如何知道呢?而且每次主库挂掉我们都让运维人员来将从库手动改成主库吗?如果代码里已经将主库连接写死了,是不是还得把所有影响到的项目都重新发布呢?这样显然不合理,所以,就有了哨兵机制。

​ 哨兵机制(Redis Sentinel)有两个主要任务:

  • 监控:定时给被监控的Redis实例做心跳检测,看看是否在正常工作
  • 自动故障转移:当主Redis挂掉了,Sentinel会将从服务器升级为主服务器,并且给客户端提供新的主服务器地址。

3.1 Sentinel 启动初始化

​ 当一个Sentinel启动时,它会执行以下步骤:

  • 初始化服务器

    这里的初始化服务器并不会像《3.1.2.1 Redis服务启动流程》中描述的那样完整的初始化Redis服务器,比如它不会载入RDB或AOF文件。

  • 将普通Redis服务器的代码替换成Sentinel代码

    Redis服务器启动的时候会载入命令表,而Sentinel启动载入的命令表和正常的不太一样,所以它只支持PING、SENTINEL、INFO、SUBSCRIBE、UNSUBSCRIBE、PSUBSCRIBE和PUNSUBSCRIBE这七个命令。除了这个以外还有一些其他的代码替换。

  • 初始化Sentinel状态

    这里会初始化一个sentinelState结构体,如下:

    /* Main state. */
    struct sentinelState {
        char myid[CONFIG_RUN_ID_SIZE+1]; /* This sentinel ID. */
        uint64_t current_epoch;         /* Current epoch. */
        dict *masters;      /* Dictionary of master sentinelRedisInstances.
                               Key is the instance name, value is the
                               sentinelRedisInstance structure pointer. */
        int tilt;           /* Are we in TILT mode? */
        int running_scripts;    /* Number of scripts in execution right now. */
        mstime_t tilt_start_time;       /* When TITL started. */
        mstime_t previous_time;         /* Last time we ran the time handler. */
        list *scripts_queue;            /* Queue of user scripts to execute. */
        char *announce_ip;  /* IP addr that is gossiped to other sentinels if
                               not NULL. */
        int announce_port;  /* Port that is gossiped to other sentinels if
                               non zero. */
        unsigned long simfailure_flags; /* Failures simulation. */
        int deny_scripts_reconfig; /* Allow SENTINEL SET ... to change script
                                      paths at runtime? */
    } sentinel;
    
  • 根据给定的配置文件,初始化Sentinel的监视主服务器列表

    上述sentinelState结构体中的masters字典记录了所有被Sentinel监视的主服务器相关信息。其中key是被监视主服务器的名字,value是Redis服务器实例,用sentinelRedisInstance来保存信息,如下:

    typedef struct sentinelRedisInstance {
        int flags;      /* See SRI_... defines */
        char *name;     /* Master name from the point of view of this sentinel. */
        char *runid;    /* Run ID of this instance, or unique ID if is a Sentinel.*/
        uint64_t config_epoch;  /* Configuration epoch. */
        sentinelAddr *addr; /* Master host. */
        instanceLink *link; /* Link to the instance, may be shared for Sentinels. */
        mstime_t last_pub_time;   /* Last time we sent hello via Pub/Sub. */
        mstime_t last_hello_time; /* Only used if SRI_SENTINEL is set. Last time
                                     we received a hello from this Sentinel
                                     via Pub/Sub. */
        mstime_t last_master_down_reply_time; /* Time of last reply to
                                                 SENTINEL is-master-down command. */
        mstime_t s_down_since_time; /* Subjectively down since time. */
        mstime_t o_down_since_time; /* Objectively down since time. */
        mstime_t down_after_period; /* Consider it down after that period. */
        mstime_t info_refresh;  /* Time at which we received INFO output from it. */
        dict *renamed_commands;     /* Commands renamed in this instance:
                                       Sentinel will use the alternative commands
                                       mapped on this table to send things like
                                       SLAVEOF, CONFING, INFO, ... */
    
        /* Role and the first time we observed it.
         * This is useful in order to delay replacing what the instance reports
         * with our own configuration. We need to always wait some time in order
         * to give a chance to the leader to report the new configuration before
         * we do silly things. */
        int role_reported;
        mstime_t role_reported_time;
        mstime_t slave_conf_change_time; /* Last time slave master addr changed. */
    
        /* Master specific. */
        dict *sentinels;    /* Other sentinels monitoring the same master. */
        dict *slaves;       /* Slaves for this master instance. */
        unsigned int quorum;/* Number of sentinels that need to agree on failure. */
        int parallel_syncs; /* How many slaves to reconfigure at same time. */
        char *auth_pass;    /* Password to use for AUTH against master & replica. */
        char *auth_user;    /* Username for ACLs AUTH against master & replica. */
    
        /* Slave specific. */
        mstime_t master_link_down_time; /* Slave replication link down time. */
        int slave_priority; /* Slave priority according to its INFO output. */
        mstime_t slave_reconf_sent_time; /* Time at which we sent SLAVE OF <new> */
        struct sentinelRedisInstance *master; /* Master instance if it's slave. */
        char *slave_master_host;    /* Master host as reported by INFO */
        int slave_master_port;      /* Master port as reported by INFO */
        int slave_master_link_status; /* Master link status as reported by INFO */
        unsigned long long slave_repl_offset; /* Slave replication offset. */
        /* Failover */
        char *leader;       /* If this is a master instance, this is the runid of
                               the Sentinel that should perform the failover. If
                               this is a Sentinel, this is the runid of the Sentinel
                               that this Sentinel voted as leader. */
        uint64_t leader_epoch; /* Epoch of the 'leader' field. */
        uint64_t failover_epoch; /* Epoch of the currently started failover. */
        int failover_state; /* See SENTINEL_FAILOVER_STATE_* defines. */
        mstime_t failover_state_change_time;
        mstime_t failover_start_time;   /* Last failover attempt start time. */
        mstime_t failover_timeout;      /* Max time to refresh failover state. */
        mstime_t failover_delay_logged; /* For what failover_start_time value we
                                           logged the failover delay. */
        struct sentinelRedisInstance *promoted_slave; /* Promoted slave instance. */
        /* Scripts executed to notify admin or reconfigure clients: when they
         * are set to NULL no script is executed. */
        char *notification_script;
        char *client_reconfig_script;
        sds info; /* cached INFO output */
    } sentinelRedisInstance;
    
  • 创建连向主服务器的网络连接

    Sentinel会和被监视的主服务器创建两个异步网络连接,一个是用来向Redis服务器发送命令和接收命令用的,另一个是用来订阅_sentinel_:hello频道用的。

3.2 监视流程

​ Sentinel默认以十秒一次的频率给主服务器发送INFO命令,并通过分析INFO命令来获取主服务器的当前信息。这里除了获得主服务器信息以外,还会取到从服务器的一些信息,并且Sentinel会给每个从服务器构建一个sentinelRedisInstance结构体来保存从服务器信息。

​ 当每次有新的从服务器被加入进来,Sentinel还会构建和从服务器的命令连接和订阅连接,并且也是十秒一次向从服务器发送INFO命令。

​ 除了发送INFO命令以外,Sentinel还会以两秒一次的频率向所有被监视的服务器发送PUBLISH命令,这样就能保证所有订阅了这个服务器的Sentinel都接收到相关的信息,除此之外,Sentinel还可以互相知晓彼此的存在。sentinelRedisInstance结构体中的sentinels字典就是用来保存其他Sentinel的地方。每个Sentinel还会互相建立命令连接来相互交换信息,不过Sentinel不会互相建立订阅连接。

​ Sentinel会以每秒一次,向所有建立了命令连接的机器发送PING命令,如果有机器在down-after-milliseconds时间范围内未响应的话,这个机器会被Sentinel标记成主观下线(Sentinel自己认为这个服务器不可用了)。当有机器被Sentinel认为主观下线之后,Sentinel会询问其他监视这个机器的Sentinel,如果返回的信息表示这个机器确实不能提供服务了,这时,所有Sentinel会将其标记为客观下线。被标记成下线并不意味着不被Sentinel监视了,Sentinel会定时监听这个机器,如果他又可以PING通了,Sentinel还是会重新将其标记为在线状态。如果是master节点不可用,那么当新的master被选出来之后,老的master就会被当做新master的从服务器。

​ master节点不可用的情况下,Sentinel会做一次故障转移。但是毕竟一台服务器可能有多个master,不可能所有Sentinel都做故障转移,所以在做故障转移之前,Sentinel会选举出一个领头的Sentinel来做这件事情,选举的规则就是每个Sentinel都向其他Sentinel发送一个SENTINEL is-master-down-by-addr命令,如果其他Sentinel有半数都通过了某个Sentinel,那么就由这个有个Sentinel作为领头有个Sentinel来执行故障转移(这里使用了raft算法)。

​ 故障转移的时候需要做两步,一是选举一个新的master,新master会在所有正常的从节点中选取一个偏移量最大的节点作为新master,这里可能会涉及到一部分的数据丢失,不过这不可避免(可参阅《4.1 集群设计绕不开的话题》)。二是其他从服务器SLAVEOF这个新的master。

思考:

​ 常规我们都是配置三台Sentinel来处理,如果Sentinel有一台挂了,刚好master服务器也挂了。Sentinel机制需要选举一台领头Sentinel处理故障转移,但是两台Sentinel会出现脑裂情况,所以这个时候Redis服务就不可用了。

©著作权归作者所有,转载或内容合作请联系作者
禁止转载,如需转载请通过简信或评论联系作者。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,509评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,806评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,875评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,441评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,488评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,365评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,190评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,062评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,500评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,706评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,834评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,559评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,167评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,779评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,912评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,958评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,779评论 2 354

推荐阅读更多精彩内容