提到zookeeper选举算法,就不得不提Paxos算法,因为zookeeper选举算法是Paxos算法的一个变种;

Paxos要解决的问题是:在一个分布式网络环境中有众多的参与者,但是每个参与者都不可靠,可能随时掉线等,这时这些参与者如何针对某个看法达成一致;

类似的问题现实生活中有很多,比如一个团队要组织团建,团队中有10个人,每个人都有自己想去的地方,如何就团建的目的地达成一致?

最简单的方式是把团队全体叫到会议室开会,很快就可以根据少数服从多数的原则,确定一个大多数人都满意的目的地;

如果将问题改为:团队10个人分别在世界的10个地方出差,作息时间各不相同,并且只能通过邮件联系,这时如何确定团建的目的地?

1 Paxos算法

https://en.wikipedia.org/wiki/Paxos_(computer_science)

https://zh.wikipedia.org/zh-cn/Paxos%E7%AE%97%E6%B3%95

Paxos is a family of protocols for solving consensus in a network of unreliable processors. Consensus is the process of agreeing on one result among a group of participants. This problem becomes difficult when the participants or their communication medium may experience failures.

1.1 Roles

Paxos describes the actions of the processors by their roles in the protocol: client, acceptor, proposer, learner, and leader. In typical implementations, a single processor may play one or more roles at the same time. This does not affect the correctness of the protocol—it is usual to coalesce roles to improve the latency and/or number of messages in the protocol.

  • Client

    • The Client issues a request to the distributed system, and waits for a response. For instance, a write request on a file in a distributed file server.
  • Acceptor (Voters) 
    • The Acceptors act as the fault-tolerant "memory" of the protocol. Acceptors are collected into groups called Quorums. Any message sent to an Acceptor must be sent to a Quorum of Acceptors. Any message received from an Acceptor is ignored unless a copy is received from each Acceptor in a Quorum.
  • Proposer 
    • A Proposer advocates a client request, attempting to convince the Acceptors to agree on it, and acting as a coordinator to move the protocol forward when conflicts occur.
  • Learner 
    • Learners act as the replication factor for the protocol. Once a Client request has been agreed on by the Acceptors, the Learner may take action (i.e.: execute the request and send a response to the client). To improve availability of processing, additional Learners can be added.
  • Leader 
    • Paxos requires a distinguished Proposer (called the leader) to make progress. Many processes may believe they are leaders, but the protocol only guarantees progress if one of them is eventually chosen. If two processes believe they are leaders, they may stall the protocol by continuously proposing conflicting updates. However, the safety properties are still preserved in that case.

client有很多个,并且每个client都有很多idea,但是只有一个client的一个idea最终会被大家接受;client想让一个idea被接收,首先会把idea告诉proposor,proposor收到一个idea之后会提交给多个acceptor进行表决,如果超过半数的acceptor表决通过,则表示idea被大家接受;learner会及时收到acceptor的表决结果;

由于实际表决过程是并发的,所以表决过程分为多个阶段,并且增加版本version的概念,这里有点类似于乐观锁;

一个形象的例子是在某个腐败的国家里,政府有一个项目要招标,然后有很多公司(client)都想拿到该项目(idea),决定该项目给谁的是有一个政府内部高层人士(acceptor)小组讨论决定,但是他们深藏不漏,公司需要通过一些政商通吃的中介(proposor),给高层人士输送贿赂(version),每个高层人士收到一个贿赂之后会表示不再接受不高于这个贿赂的其他贿赂并且支持当前这个贿赂的公司,如果一个公司能够成功贿赂小组中多数高层人士,那么这个公司可以拿到这个项目;

1.2 Basic Paxos

  • Phase 1a: Prepare

  • Phase 1b: Promise

  • Phase 2a: Accept Request

  • Phase 2b: Accepted

首先将议员的角色分为 proposers,acceptors,和 learners(允许身兼数职)。proposers 提出提案,提案信息包括提案编号和提议的 value;acceptor 收到提案后可以接受(accept)提案,若提案获得多数 acceptors 的接受,则称该提案被批准(chosen);learners 只能“学习”被批准的提案。划分角色后,就可以更精确的定义问题:

  1. 决议(value)只有在被 proposers 提出后才能被批准(未经批准的决议称为“提案(proposal)”);
  2. 在一次 Paxos 算法的执行实例中,只批准(chosen)一个 value;
  3. learners 只能获得被批准(chosen)的 value。

作者通过不断加强上述3个约束(主要是第二个)获得了 Paxos 算法。

P1:一个 acceptor 必须接受(accept)第一次收到的提案。
P1a:当且仅当acceptor没有回应过编号大于n的prepare请求时,acceptor接受(accept)编号为n的提案。
P2:一旦一个具有 value v 的提案被批准(chosen),那么之后批准(chosen)的提案必须具有 value v。
P2a:一旦一个具有 value v 的提案被批准(chosen),那么之后任何 acceptor 再次接受(accept)的提案必须具有 value v。
P2b:一旦一个具有 value v 的提案被批准(chosen),那么以后任何 proposer 提出的提案必须具有 value v。
P2c:如果一个编号为 n 的提案具有 value v,那么存在一个多数派,要么他们中所有人都没有接受(accept)编号小于 n
的任何提案,要么他们已经接受(accept)的所有编号小于 n 的提案中编号最大的那个提案具有 value v。

2 Zookeeper Leader Election

每个zookeeper服务器都相当于client+proposor+acceptor+learner

Vote(提案编号、提议的 value):myid、zxid、epoch

初始值:

currentVote = new Vote(myid, getLastLoggedZxid(), getCurrentEpoch());

其他人的Vote:

HashMap<Long, Vote> recvset = new HashMap<Long, Vote>();

zookeeper的选举算法做了很多简化,将Paxos的value和version合并成Vote,是为了保证能够在最短的时间内选举出新的leader,同时避免数据丢失和数据同步,来看以下几种情况:

  • 集群第一次启动,所有服务器的zxid和epoch一样,在集群的半数服务器启动后谁的myid最大,谁将会成为leader;比如5台服务器,id分别为1/2/3/4/5,当你顺序启动1/2/3/4/5的时候,3启动后3将会成为leader,4/5启动后会成为follower;当你顺序启动5/4/3/2/1的时候,3启动后5将会成为leader;
  • 集群重启,在集群的半数服务器启动后,谁的epoch最大(每次选举成功后leader会将epoch+1),谁将会成为leader,如果大家的epoch相同,谁的zxid最大(即谁拥有最新的数据),谁将会成为leader;

选举核心类及调用流程:

org.apache.zookeeper.server.quorum.Election

org.apache.zookeeper.server.quorum.FastLeaderElection implements Election

lookForLeader

sendNotifications

totalOrderPredicate

termPredicate

org.apache.zookeeper.server.quorum.flexible.QuorumMaj

containsQuorum

QuorumPeer.setPeerState

是否超过半数判断

    public boolean containsQuorum(HashSet<Long> set){

        return (set.size() > half);

    }

Vote大小判断

    protected boolean totalOrderPredicate(long newId, long newZxid, long newEpoch, long curId, long curZxid, long curEpoch) {

        LOG.debug("id: " + newId + ", proposed id: " + curId + ", zxid: 0x" +

                Long.toHexString(newZxid) + ", proposed zxid: 0x" + Long.toHexString(curZxid));

        if(self.getQuorumVerifier().getWeight(newId) == 0){

            return false;

        }

        /*

         * We return true if one of the following three cases hold:

         * 1- New epoch is higher

         * 2- New epoch is the same as current epoch, but new zxid is higher

         * 3- New epoch is the same as current epoch, new zxid is the same

         *  as current zxid, but server id is higher.

         */

        return ((newEpoch > curEpoch) ||

                ((newEpoch == curEpoch) &&

                ((newZxid > curZxid) || ((newZxid == curZxid) && (newId > curId)))));

    }

【原创】大数据基础之Zookeeper(3)选举算法的更多相关文章

  1. 【原创】大数据基础之Zookeeper(2)源代码解析

    核心枚举 public enum ServerState { LOOKING, FOLLOWING, LEADING, OBSERVING; } zookeeper服务器状态:刚启动LOOKING,f ...

  2. 【原创】大数据基础之Zookeeper(1)介绍、安装及使用

    zookeeper3.4.11 http://zookeeper.apache.org/ 一 简介 ZooKeeper is a centralized service for maintaining ...

  3. 【原创】大数据基础之Zookeeper(4)应用场景

    1 集群配置管理 应用服务器的配置通常会放到properties文件中,格式为: system1.module2.prop3=value4 然后启动的时候加载,这样带来的问题是启动后无法修改,想修改必 ...

  4. 大数据篇:Zookeeper

    Zookeeper 1 Zookeeper概念 Zookeeper是什么 是一个基于观察者设计模式的分布式服务管理框架,它负责和管理需要关心的数据,然后接受观察者的注册,一旦这些数据的状态发生变化,Z ...

  5. 决战大数据之三-Apache ZooKeeper Standalone及复制模式安装及测试

    决战大数据之三-Apache ZooKeeper Standalone及复制模式安装及测试 [TOC] Apache ZooKeeper 单机模式安装 创建hadoop用户&赋予sudo权限, ...

  6. 图解zookeeper FastLeader选举算法

    zookeeper当配置为群集模式,在启动或异常情况将被选举为的例子Leader.默认选择算法FastLeaderElection. 不知道zookeeper够考虑这样一个问题:某个服务能够配置为多个 ...

  7. 图解zookeeper FastLeader选举算法【转】

    转自:http://codemacro.com/2014/10/19/zk-fastleaderelection/ zookeeper配置为集群模式时,在启动或异常情况时会选举出一个实例作为Leade ...

  8. 读&lt;大数据日知录:架构与算法&gt;有感

    前一段时间, 一个老师建议我能够学学 '大数据' 和 '机器学习', 他说这必定是今后的热点, 学会了, 你就是香饽饽.在此之前, 我对大数据, 机器学习并没有非常深的认识, 总觉得它们是那么的缥缈, ...

  9. 【原创】大数据基础之Impala(1)简介、安装、使用

    impala2.12 官方:http://impala.apache.org/ 一 简介 Apache Impala is the open source, native analytic datab ...

随机推荐

  1. [Oracle维护工程师手记]为什么flashback 的时候既需要 flashback log ,又需要 archive log?

    为什么flashback 的时候既需要 flashback log ,又需要 archive log 呢? 如果数据库的活动不是很频繁,可以看到,其flashback log 是比较小的.那么是通过怎 ...

  2. whereis、which、find的区别

    which用于查找可执行文件的目录,我们平时执行的命令实际上是一个可执行文件,如ls命令实际上是/usr/bin/目录下的一个可执行文件.它实际上是通过 PATH环境变量来查找的. whereis用于 ...

  3. 基于Flask 实现Web微信登陆

    网页版微信登陆网址 https://login.wx.qq.com/ 获取微信登陆的二维码 在浏览器中访问登陆接口 https://login.wx.qq.com/ 我们查找二维码的图片可以看到 其中 ...

  4. vue-cli的跨域配置(自己总结)

  5. python控制台输出带颜色的文字方法

    #格式: 设置颜色开始 :\033[显示方式;前景色;背景色m   注意:开头部分的三个参数:显示方式,前景色,背景色是可选参数,可以只写其中的某一个:另外由于表示三个参数不同含义的数值都是唯一的没有 ...

  6. 【XSY3147】子集计数 DFT 组合数学

    题目大意 给定一个集合 \(\{1,2,\ldots,n\}\),要求你从中选出 \(m\) 个数,且这 \(m\) 个数的和是 \(k\).问方案数 \(\bmod 998244353\) \(0\ ...

  7. 【XSY3141】哲学家 计算几何 线段树

    题目描述 有一个平面,最开始平面上没有任何点. 你要按顺序加入 \(n\) 个点,求加入每个点后有多少三角形严格包含原点(在边界上不算). \(n\leq 400000\),无重点. 题解 其实这题本 ...

  8. JPA的merge对联合唯一索引无效(代码库)

    问题 JPA的merge()操作 是合并的意思,就是当保存的实体时,根据主键id划分,如果已存在,那么就是更新操作,如果不存在,就是新增操作 但是这个仅针对 主键id 划分,对联合唯一索引 无效,两次 ...

  9. 并发容器学习—ConcurrentSkipListMap与ConcurrentSkipListSet 原

    一.ConcurrentSkipListMap并发容器 1.ConcurrentSkipListMap的底层数据结构     要学习ConcurrentSkipListMap,首先要知道什么是跳表或跳 ...

  10. CSS实现动画特效导航栏

    0 写在前面 今天用纯CSS编写了一种带有特效的导航栏,一方面巩固熟悉了导航栏的一般写法,另一方面练习了CSS3的一些新特性. 1 实现效果 当鼠标划过时,实现了一种动态百叶窗效果. 2 实现细节 2 ...