[Switch] ZooKeeper detailed introduction and use section 1, Section 1 of zookeeper
I. Distributed Coordination Technology
Before introducing ZooKeeper, we will introduce a technology-Distributed Coordination technology. So what is Distributed Coordination technology? So I will tell you, in fact, the Distributed Coordination technology is mainly used to solve synchronization control between multiple processes in a distributed environment, so that they can access a certain critical resource in an orderly manner, prevents "dirty data. At this time, some people may say this is simple, and it is easy to write a tuning algorithm. People who say this may not have a good understanding of distributed systems. If all these processes are running on a single machine, they are relatively easy to handle. The question is that they are in a distributed environment, and the question comes again, so what is distributed? I cannot clarify one or two sentences, but I have drawn a picture to help you understand the content, let's take a look at this figure, as shown in Figure 1.1.
Figure 1.1 distributed system diagram
Let's take a look at this figure. In this figure, there are three machines, each running an application. Then we connect these three machines through the network to form a system to provide services for users. For users, the system architecture is transparent, he doesn't feel what kind of architecture my system is. Then we can call this systemDistributed System.
Next, let's analyze how to schedule processes in this distributed system. I suppose a resource is attached to the first machine, then the three physical distribution processes will compete for this resource, but we do not want them to access it at the same time. At this time, we needCoordinatorTo allow them to access this resource in an orderly manner. This coordinator is the one we often mention.LockFor example, "process-1" gets the lock when using this resource, and "process 1" keeps the lock for this resource.ExclusiveIn this way, other processes will not be able to access this resource. After "process 1" runs out of this resource, the lock will be released to allow other processes to obtain the lock. Then, through this lock mechanism, we can ensure that multiple processes in the distributed system can access this critical resource in an orderly manner. So we call this lock in this distributed environmentDistributed Lock. This distributed lock is ours.Distributed Coordination TechnologyThe core content of implementation, so how to achieve this distributed, that is what we will talk about later.
II. Implementation of distributed locks
We know that to prevent mutual interference between multiple processes in a distributed system, we need a Distributed Coordination technology to schedule these processes. The core of this Distributed Coordination technology is to achieve this point.Cloth lock. How can this lock be implemented? This implementation is indeed relatively difficult.
1.1 Problems
After reading the distributed environment shown in Figure 1.1, some people may feel that this is not very difficult. It is nothing more than the original process scheduling primitive on the same machine, implemented in a distributed environment through the network. Yes, it can be said on the surface. But the problem lies in the network. In a distributed system, all the assumptions on the same machine do not exist because the network is unreliable.
For example, on the same machine, if you call a service successfully, the call is successful. If the call fails, for example, if an exception is thrown, the call fails. However, in a distributed environment, because the network is not available, if you fail to call a service, it does not necessarily mean a failure. It may be that the execution is successful, but the response fails. In addition, both A and B call the C service. In terms of time, A calls some services first and B calls them later. Is the final result certain that A's request will arrive before B? We have to rethink the assumptions on the same machine. We also need to think about the impact of these questions on our design and coding. In addition, in a distributed environment, to improve reliability, we will deploy multiple sets of services, but how can we achieve consistency among multiple sets of services, this is relatively easy to synchronize among multiple processes on the same machine, but it is indeed a big challenge in a distributed environment.
Therefore, Distributed Coordination is far more difficult than scheduling multiple processes on the same machine. If an independent coordination program is developed for each distributed application. On the one hand, it is difficult to form a common and scalable coordinator to repeatedly compile the Coordination Program. On the other hand, the Coordination Program overhead is relatively large, which will affect the original performance of the system. Therefore, a highly reliable and available universal coordination mechanism is urgently needed to coordinate distributed applications.
1.2 Distributed Lock implementer
At present, Google's Chubby and Apache's ZooKeeper have done a good job in Distributed Coordination technology. They are all real-time users of distributed locks. Some people may ask why we need to get a ZooKeeper with Chubby, isn't Chubby doing well? This is not the case. The main reason is that chlobby is non-open source and is used by Google. Later, Yahoo! developed ZooKeeper in imitation of Chubby and implemented a similar distributed lock function, and donated ZooKeeper to Apache as an open-source program, in this way, you can use the lock service provided by ZooKeeper. In addition, it has been tested for a long time in the distributed field, and its reliability and availability have all been verified by theory and practice. Therefore, when building some distributed systems, we can start with such systems to build our systems, which will save a lot of cost and reduce bugs.
Iii. Overview of ZooKeeper
ZooKeeper is a high-availability, high-performance, consistent open-source Coordination Service designed for distributed applications. It provides a basic service:Distributed Lock Service. Due to the open-source features of ZooKeeper, our developers developed other usage methods based on distributed locks:Configuration maintenance, group service, and distributed Message Queue,Distributed notification/coordination.
Note:ZooKeeper
Performance CharacteristicsIt determines that it can be used in large-scale, distributed systems. Slave
ReliabilityIt won't crash because of a node error. In addition, it
Strict sequential access controlThis means that complex control primitives can be applied on the client. ZooKeeper ensures consistency, availability, and fault tolerance. It is also the success of ZooKeeper. All its successes are inseparable from the Zab protocol, these contents will be described later.
As mentioned above, how do we implement so many services, such as distributed locks, configuration maintenance, and group services? I believe this is what everyone cares about. When ZooKeeper implements these services, it first designs a newData Structure -- ZnodeAnd then define somePrimitive, That is, some operations on the data structure. With these data structures and primitives, it is not enough because our ZooKeeper is working in a distributed environment, our service is a distributed application that sends messages to us in the form of a network.Notification Mechanism-- Watcher mechanism. To sum up, the services provided by ZooKeeper are mainly implemented through the data structure + primitive + watcher mechanism. So I will introduce ZooKeeper from these three aspects.
4. ZooKeeper Data Model 4.1 ZooKeeper Data Model Znode
ZooKeeper has a hierarchical namespace, which is very similar to the standard file system, as shown in Figure 3.1.
Figure 4.1 ZooKeeper data model and file system directory tree
We can see that the ZooKeeper data model is very similar in structure to the standard file system. It uses this tree-like hierarchy. each node in the ZooKeeper tree is called-Znode. Like the directory tree of the file system, each node in the ZooKeeper tree can have subnodes. But there are also differences:
(1) Reference Method
Zonde passedPath reference, Like the file path in Unix. The path must be absolute, so they must contain the slash charactersStart. In addition, they must be unique, that is, each path has only one representation, so these paths cannot be changed. In ZooKeeper, the path consists of Unicode strings and has some restrictions. String "/zookeeper" is used to save management information, such as key quota information.
(2) Znode Structure
Znode In the ZooKeeper namespace has two features: file and directory. Data structures such as data, metadata, ACL, and timestamp are maintained like files, and can be used as part of path identifiers like directories. Each node in the figure is called a Znode. Each Znode consists of three parts:
①Stat: status information, which describes the Znode version, permissions, and other information.
②Data: The data associated with the Znode.
③Children: subnode under the Znode
Although ZooKeeper can be associated with some data, it is not designed as a regular database or big data storage. On the contrary, it is usedManage scheduling dataSuch as configuration file information, status information, and collection location in a distributed application. The common feature of these data is that they are all very small data, usually measured in KB. ZooKeeper servers and clients are designed to strictly check and limit the data size of each Znode to 1 MB, but it should be much smaller than this value in general use.
(3) Data Access
The data stored by each node in ZooKeeper isAtomic operations. That is to say, the read operation will get all data related to the node, and the write operation will replace all data of the node. In addition, each node has its own ACL (Access Control List), which specifies the user's permissions, that is, the operations that a specific user can perform on the target node.
(4) node type
ZooKeeper has two types of nodes:Temporary NodeAndPermanent Node. The node type is determined at creation and cannot be changed.
① Temporary node:The lifecycle of a node depends on the sessions that are created. Once the Session ends, the temporary node is automatically deleted. You can also manually delete the node. Although each temporary Znode is bound to a client session, it is visible to all clients. In addition, temporary nodes of ZooKeeper cannot have subnodes.
② Permanent node:The lifecycle of a node does not depend on the session. The node can be deleted only when the client displays the deletion operation.
(5) Ordered Node
When creating a Znode, you can request to addIncremental count. This countFor the parent node of this nodeIt is unique. Its format is "% 10d" (10 digits. digits without a value are supplemented with 0, for example, "0000000001 "). When the Count value is greater than 232-1, the counter overflows.
(6) Observation
The client can set watch on the node, which is calledMonitor. When the node status changes (Znode addition, deletion, and modification), the Operation corresponding to watch is triggered. When watch is triggered, ZooKeeper will send only one notification to the client, because watch can only be triggered once, which can reduce network traffic.
4.2 time in ZooKeeper
ZooKeeper has multiple record time formats, including the following main attributes:
(1) Zxid
Every operation that changes the ZooKeeper node status will make the node receive a timestamp in Zxid format, and the timestamp is globally ordered. That is to say, each change to the node will generate a unique Zxid. If Zxid1 is less than Zxid2, the event corresponding to Zxid1 occurs before the event corresponding to zxid2. In reality, each node Maintainer of ZooKeeper has three Zxid values: cZxid, mZxid, and pZxid.
① CZxid: The Zxid format timestamp corresponding to the creation time of the node.
② MZxid: The Zxid format timestamp corresponding to the node modification time.
In the implementation, Zxid is a 64-bit number, and its 32-bit height is the epoch used to identify whether the leader relationship has changed. Each time a leader is selected, it will have a new epoch. Low 32-bit isIncremental count.(2) version number
Each operation on a node increases the version number of the node. Each node maintains three versions:
① Version: Node data version number
② Cversion: Sub-node version number
③ Aversion: The ACL version of the node
4.3 ZooKeeper node attributes
Based on the previous introduction, we can see that a node has many important attributes that indicate its status, as shown in.
Figure 4.2 Znode node attribute Structure
5. Operations in the ZooKeeper Service
There are nine basic operations in ZooKeeper, as shown in:
Figure 5.1 ZooKeeper class method description
There are restrictions on updating ZooKeeper. Delete or setData must specify the Znode version number to be updated. You can call exists to find the version number. If the version does not match, the update will fail.
The update ZooKeeper operation is non-blocking. Therefore, if the client loses an update (because another process updates this Znode at the same time), it can choose to retry or perform other operations without blocking other processes.
Although ZooKeeper can be viewed as a file system, ZooKeeper is convenient and discards some file system operation primitives. Because the file is very small and can be read and written as a whole, you do not need to open, close, or perform location-based operations.
Vi. Watch triggers
(1) watch Overview
ZooKeeper can beRead operationsSet watch. Read operations include exists (), getChildren (), and getData (). Watch event isOne-time triggerWhen the status of the watch object changes, the event corresponding to the watch object is triggered. The watch event will beAsynchronousAnd ZooKeeper provides an orderlyConsistency assurance. Theoretically, the client receives a watch event faster than the time when it sees the watch object state change.
(2) watch type
The watch managed by ZooKeeper can be divided into two types:
①Data watch (data watches ):GetDataAndExistsSet Data watch
②Child watch (child watches ):GetChildrenSets the Child watch
You canReturned dataTo set different watches:
① GetData and exists:Returns the data about the node.
② GetChildren:Back to children list
Therefore
①A successfulSetData operationWill trigger Znode's data watch
②A successfulCreate operationIt will trigger Znode's data watch and Child watch
③A successfulDelete operationIt will trigger Znode's data watch and Child watch
(3) watch Registration and triggering
Figure 6.1 watch settings and corresponding triggers:
①Watch on the exists operation, on the monitored ZnodeCreate,DeleteOrData UpdateIs triggered.
②Watch on the getData operation, on the monitored ZnodeDeleteOrData UpdateIs triggered. The getData operation is successful only when Znode exists.
③Watch on the getChildren operation, on the subnode of the monitored ZnodeCreateOrDeleteOr the Znode itself isDeleteIs triggered. You can check whether the watch event type is Znode or its subnode is deleted. NodeDelete indicates that Znode is deleted, and NodeDeletedChanged indicates that the subnode is deleted.
Watch is maintained locally by the ZooKeeper server connected to the client. Therefore, watch can be easily set, managed, and assigned. When the client connects to a new server, any session event may trigger watch. In addition, watch will not be received when the slave server is disconnected. However, when a client re-establishes a connection, any previously registered watch will be re-registered.
(4) Notes
The watch of Zookeeper actually processes two types of events:
① Connection status event(Type = None, path = null)
This type of event does not need to be registered or triggered consecutively. We only need to process it.
② Node events
Node creation, deletion, and data modification. It is a one-time trigger, and we need to register and trigger continuously, and the event may be lost.
The above two types of events are processed in Watch, that is, the reloadProcess (Event event)
To trigger a node event, the function exists, getData, or getChildren is used to process such functions:
① Registration trigger event
② Functions of the function itself
The functions of a function can be implemented by using asynchronous callback functions to process the function itself during processResult.
VII. Examples of ZooKeeper applications
To help you understand ZooKeeper, I would like to give you an example here to see how ZooKeeper implements its services. I use the basic services provided by ZooKeeperDistributed LockFor example.
7.1 Distributed Lock application scenarios
In the Distributed Lock service, one of the most typical application scenarios isMaster electionTo solveSingle point of failure. What is single point of failure in a distributed system? Generally, a distributed system uses the master-slave mode, that is, a master machine connects to multiple processing nodes. The master node is responsible for distributing tasks, and the slave node is responsible for processing tasks. When the master node fails, the entire system will be paralyzed. We call this fault a single point of failure. As shown in Figure 7.1 and 7.2:
Figure 7.1 master-slave distributed system diagram 7.2 single point of failure
7.2 traditional solutions
Traditionally, a slave node is used. The slave node periodically sends a ping packet to the current master node. After receiving the ping packet, the master node sends an Ack reply to the slave node, when the slave node receives a response, it will think that the current master node is still alive and ask him to continue providing services. 7.3:
Figure 7.3 traditional solution
When the master node fails, the slave node cannot receive a reply, and then he thinks that the master node is suspended and takes over to become the master node, as shown in Figure 7.4:
Figure 7.4 traditional solution
However, there is a hidden danger in this method, that is, network problems. Let's look at the consequences of a network problem, as shown in Figure 7.5:
Figure 7.5 network faults
That is to say, our master node is not suspended, but the network fails during the reply, so that our slave node cannot receive the reply, and the master node will be suspended, then the slave node starts his Master instance, so that two Master nodes exist in our distributed system ---Dual MasterAfter the emergence of the Master node, our slave node will report part of what it has done to the Master node, and part of the report to the slave node, so that the service is completely messy. To prevent this situation, we introduced ZooKeeper, which can ensure that there is only one Master at all times, although it cannot avoid network faults. Let me take a look at how ZooKeeper is implemented.
7.3 ZooKeeper Solution
(1) Master startup
After Zookeeper is introduced, we start two master nodes: "master node-A" and "master node-B". After they are started, they all register A node with ZooKeeper. Assume that "master-A" locks the Registry node to "master-00001", and "master-B" registers the node to "master-00002". After registration, the node is elected, the node with the smallest number will win in the election and get the lock to become the master node, that is, our "master node-A" will get the lock to become the master node, then, "master node-B" is blocked and becomes a slave node. In this way, the two Master processes are scheduled.
Figure 7.6 ZooKeeper Master election
(2) Master fault
If the "Master-A" node fails, the node registered with it will be automatically deleted, and ZooKeeper will automatically detect the node changes and send the election again, in this case, "master node-B" will win the election and replace "master node-A" to become the master node.
Figure 7.7 ZooKeeper Master election
(3) Master recovery
Figure 7.8 ZooKeeper Master election
If the master node recovers, it will register a node with ZooKeeper again. At this time, the registered node will be "master-00003", and ZooKeeper will detect node changes and initiate another election, at this time, "master node-B" will win again during the election and continue to serve as "master node", "master node-A" will serve as A slave node.
Source: http://www.cnblogs.com/wuxl360/p/5817471.html