Zookeeper Principle analysis-election

Source: Internet
Author: User

1) Quorumpeermain Load

The zookeeper cluster-initiated ingress class is quorumpeermain to load the configuration to start the Quorumpeer thread. First we look at Quorumpeer, Google Translate quorum is a quorum, the meaning of quotas, peer is the equivalent of the meaning, So the quorum representative in Quorumpeer means that each zookeeper cluster starts when the number of zookeeper services in the cluster has been determined, and all the machines in the cluster are configured in each zookeeper configuration file

server.1=127.0.0.1:2886:3886

server.2=127.0.0.1:2887:3887

server.3=127.0.0.1:2888:3888

In fact, it is also determined that the zookeeper in the operation is not dynamic expansion, you must stop the service to modify the configuration can be, Quorumpeer in the peer is the focus of each zookeeper role is the equivalent of no master and slave points, Each zookeeper service can become leader, Follower,observer.

1. Quorumpeermain Loading

1) quorumpeerconfig Read the configuration file, such as the following zoo.cfg file

ticktime=2000

initlimit=10

Synclimit=5

Datadir=d:/workspace_zookeeper/data1

clientport=2181

server.1=127.0.0.1:2886:3886

server.2=127.0.0.1:2887:3887

server.3=127.0.0.1:2888:3888

Each server in the configuration as above. The X record represents a service in the cluster, and Quorumpeerconfig builds a Quorumserver object with the server. X in x represents the SID of Zookpeer, each zookeeper edits its own SID in the myID file under DataDir, sid marks each service, works in fast elections

Server. The value after x represents the Zookeeper service address IP and the port where zookeeper is connected

2) Start the Scheduled Cleanup service task Datadircleanupmanager.start () to purge expired Txtlog and snapshot files

3) Build Quorumpeer Task Object

3.1) Set the port address for client connections

3.2) Set the operands of Txtlog and snapshot Filetxnsnaplog

3.3) Set the myID (SID) of this zookeeper

3.4) Setting up the Client connection factory

3.5) Set up an election algorithm

3.6) Various time settings, etc.

4) Quorumpeer.start () Start task thread

2) Election process

Uorumpeer's Run method is mainly used for elections, and after the election into various roles, the role is broken re-election, the general process

2.1.1 Basic Concepts

Logicalclock, Currentepoch,acceptedepoch Epoch Zxid

2.2.2 Election algorithm creation

When zookeeper starts, the Quorumpeer thread's Start method calls the Startleaderelection method to create an election algorithm, which is created as follows:

1) Create an election algorithm before you create a quorumcnxmanager,quorumcnxmanager using the TCP protocol for leader elections, each pair of servers maintains a TCP link, and each zookeeper opens a tcp/ IPJ listens to other servers in the cluster.

1.1) Receiveconnection (socket) method to establish a connection

1.1.1) Read request connection Zookeeperserver sid (myID)

1.1.2) Each other SID less than their SID, immediately shut down the connection, their client to the other request to establish a connection, note that zookeeper services are configured myID as a client connection myID small as the server side.

1.1.3) The other SID is larger than its SID, creating the server-side send thread task and the receive thread task, and initiating the task preparing to send and receive client-side data

1.2) ConnectOne (SID): This zookeeper initiates a link request to the zookeeper of the SID (myID) as a client

1.2.1) writes a native SID to the other zookeeper

1.2.2) Each other SID is larger than the native, close the socket link, note that the Zookeeper service is configured myID large as the client connection myID small as the server side.

1.2.3) The other SID is smaller than the native, creating the client side of the send thread task and the receive thread task, and the start task prepares to send and receive server-side data

1.3) Sendworker: As its name the Run method takes data from the blocked send queue

1.4) Recvworker: As the name of the Run method will receive the data into the blocking queue for fastleaderelection. Workerreceiver Thread Task consumption

2) QuorumCnxManager.listener.start ()

Listener thread task, bind address open ServerSocket service, used to listen to other server connections, to conduct inter-group elections, polling, data synchronization. The number of server links is limited and is a long connection based on bio.

Socketclient = Serversocket.accept ();

Receiveconnection (client);//processing Establish connection request

3) Fastleaderelection: Create an election object

3.1) Build the Send queue Linkedblockingqueue<tosend>sendqueue

3.2) Build the Receive queue Linekdblockingqueue<notification>recvqueue

3.2) Create a message Processing object Messenger, which has Workerreceiver and Workersender two line Cheng Zi type objects, this two thread object acts as its name

3.2.1) Workerreceiver

3.2.2) Workersender

2.2.3 Election process:

1) logicalclock++

2) Initialization proposal:

2.1) proposed election of leader himself Proposedleader=myid

2.2) Proposedzxid=lastloggedzxid the last transaction ID recorded in Datatree

2.3) Proposedepoch=currentepoch the value stored in the current local file Currentepoch

3) Send notification messages to other services:

Traverse all servers in the cluster to build a proposal for an election proposal

Tosend notmsg = Newtosend (ToSend.mType.notification,

Proposedleader,

Proposedzxid,

Logicalclock,

QuorumPeer.ServerState.LOOKING,

Sid

Proposedepoch);

Joins the message to the send queue.

4) Looking State loop:

4.1) Get the message from the Accept queue n

4.2) n is empty

4.2.1) Send queue is empty, traverse all the servers in the cluster, build an election proposal to join the Send queue

4.2.1) Send queue is not empty, connectall view all services if no connection established.

4.3) n is not empty to determine the service status

4.3.1) Looking: The votes received have not yet been elected leader

4.3.1.1) If N.electionepoch>logicalclock

The election time to receive messages is greater than the native calculator, updating the local logicalclock,

Clears the collection of votes received,

Then you will receive the message N compare yourself to what kind of proposal to use, the rule of judgement is as follows: the same situation to see the next

Newepoch > Curepoch

Newzxid > Curzxid

NewId > Curid

Updating the election proposal

Send an election proposal message to another server, first join the Send queue to send asynchronously

4.3.1.2) n.electionepoch< Logicalclock The other election era expired, abandoned, break re-circulation

4.3.1.3) n.electionepoch== Logicalclock decision-making proposal rules the following are equal cases

Newepoch > Curepoch

Newzxid> Curzxid

NewId > Curid

If you use the proposal, update the local proposal and send the election proposal message to the other server, first join the Send queue to send asynchronously

4.3.1.4) Build the proposal into a voting object vote, save to receive the voting collection, here the proposal information of this machine should be up to date

4.3.1.5) termpredicate (recvset,new Vote (Proposedleader, Proposedzxid, Logicallock, Proposedepoch)) compares the received proposal with his own proposal, Greater than General set.size () > Number of clusters/2

If there is no greater than half, jump out of this cycle

If it is greater than half, fetch the message from the receiving queue, if there is a message to determine whether the vote proposal has an update that has an update to join the message to the receiving collection, if there are no new messages in the receive queue then set the native role according to the latest poll

4.3.2) Observing:

Election process, observing not participate, only print debug logs

4.3.3) following or leading

The voting information received has been leader elected.

4.3.3.1) n.electionepoch== Logicalclock received a message picking up leader and the machine was in an election era

Joins a message to a collection of votes received Recvset

Determine if the Recvset collection is not the majority of the leader specified by a n message

Add a message to an external election collection outofelection used to hold externally elected leader messages.

Determine if the follower in most outofelection collections is accompanied by a leader

2.2 Observing this machine is the Observer

2.2.1) Establish a socket link with leader server

2.2.2) registers the Oberser service with leader server, and the registration process submits its own Acceptedepoch to leader in addition to the role of the server to leader. Leader to judge the update and then to self-feedback the latest Acceptedepoch

2.2.3) synchronizing data from leader

2.2.4) Start while loop, receive leader instruction

PING: Receives a heartbeat message and returns the session it holds as a heartbeat content

Proposal,commit,uptodate: Logging, no action

Sync: Viewer synchronizes data

Revalidate: Re-establish session

INFORM: The Observer submits the data by this type of message (for follower first proposal in commit)

2.3 Following native in follower state

2.3.1) Establish a socket link with leader server

2.3.2) Register the follower service with Leaderserver, the registration process will also submit its Acceptedepoch to leader in addition to the role of the server to leader. Leader to judge the update and then to self-feedback the latest Acceptedepoch

2.3.3) do a check leader return the epoch is less than the native Accpetedepoch should never appear

2.3.4) synchronizing data from leader

2.3.5) Start while loop, receive leader instruction

PING: Receives a heartbeat message and returns the session it holds as a heartbeat content

Proposal:leader submitted a change operation proposal to follower.

Commit:leader confirm change operation to follower

Uptodate:follower should not accept this operation after startup

Revalidate: Re-establish session

Sync: Synchronizing Data

2.4 Leading native in the lead state

One but the election leader if this machine is leader, then quorumpeer.run into the leading branch for the initialization of the leader role and the work to enter the leader role, executed by Leader.lead (), Let's take a look at the execution process:

2.4.1) loaddata load data, zookeeperserver load to memory using snapshot and txtlog recovery data

2.4.2) Get the Epoch,lastprocessedzxid of leader

2.4.3) Build the Learnercnxacceptor thread task and start

Learnercnxacceptor is used to listen for learner (Follower&observer) in the cluster and to establish a connection with them. Leader the connection to each learner will build Learnerhandler thread task to communicate with learner one on one

2.4.4) Get the latest reception of the epoch of the electoral epoch

This is done by receiving all (here and not all, through the policy, by default greater than the general, otherwise blocking waits) The Lastacceptedepoch of the zookeeper cluster compares the largest one in addition to one,

2.4.5) created new ZXID according to the latest epoch, high 32 bits is epoch, low 32 bits is ID count

2.4.6) constructs leader, the epoch information object Quorumpacket, sends to learner in the cluster, learner the Acceptedepoch after receiving the epoch greater than its learner Acceptedepoch

Add yourself to the Newleaderproposal.ackset collection

Then receive each learner feedback (default is greater than half otherwise it will block wait)

Set Currentepoch, serialize to local file

2.4.7) leader interacts with each learner through Learnerhandler, and after leader sends learner to each newleaderproposal, after each learner feedback, Each learner will be based on the latest EPOCH,ZXID to synchronize data with the leader, after the completion of the synchronization will send an ACK message to leader, leader received after the ACK message added to the Newleaderproposal.ackset, So the next step of leader is to cycle to determine whether the number of Newleaderproposal.ackset is more than half

2.4.8) initiates a while loop to send a heartbeat to the learner at timed intervals, and if the active server in the decision cluster is greater than half, if not the exit loop will re-

3) Data synchronization

1. Zookeeper Cluster once the election leader, leader and Follower,observer will have a number of columns of interaction between the epoch, data synchronization operations, as well as the subsequent operation of the voting processing decision-making operations, these interactions are actually very complex, Zookeeper code personal feel of not tidy up very clear lead to the details of the time looks very laborious, below I will be the interaction between them as a whole and as much as possible detailed introduction

3.1) if the Leader.lead () method is created and started Learnercnxacceptor thread is used to listen for Follower.followleader () or Observer.observerleader () by Connecttoleader (addr) to connect the leader, each connection constructs a Learnerhandler thread object that is specifically handled.

Since the difference between follower and observer is that observer do not participate in the voting, the other is similar, so I will explain the interaction between leader and follower.

3.2) leader by voting to get a sever Lastaccpetepoch decision out the latest

3.2.1) leader build Learnercnxacceptor, listen learner link

3.2.2) Learner connection on Leader,leader for learner build Learnerhandler processor

3.2.3) leader joins its SID into the connectingfollowers set to wait for the decision

More than half Notifyall

No more than half wait

3.2.4) learner sends its own Lastaccpetepoch to leader if Learner Lastaccpetepoch is greater leader leader Learner 1, add learner SID to Connectingfollowers set wait for decision

More than half Notifyall

No more than half wait

Note: 3.2.3 and 3.2.4 multi-Threading not successively, 3.2.4 will have a lot

3.2.5) hold, wait for connectingfollowers more than half, get the latest epoch

3.2.6) write to Learner Leaderinfo that is, leader get to do the next epoch

3.2.7) Learner read leader information, update their Lastaccpetepoch

and update the information to leader feedback

3.2.8) leader Get learner feedback, more than half the decision, return to the latest epoch

is to get a stereo interaction of the epoch

3.3) Data synchronization

Leader decision after the epoch, zookeeper into a new era, zookeeper before the external pick-up needs to be synchronized with the leader, data synchronization is not an independent component, the code is immediately above the epoch.

3.3.1)

The relationship difference between tobeapplied Commitlog outstandingproposals set

Zookeeper Principle analysis-election

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.