ZooKeeper回调机制

ZooKeeper Watch机制

   一个ZooKeeper的节点可以被监控,包括这个目录中存储的数据的修改,子节点目录的变化,一旦变化可以通知设置监控的客户端。通过这个特性可以实现的功能包括配置的集中管理,集群管理,分布式锁等等。ZooKeeper Watch机制具有如下特性:

  • 一次性的触发器(one-time trigger)
      无论是服务端还是客户端,一旦一个Watcher被触发,ZooKeeper都会将其从相应的存储中移除。这样的设计有效地减轻了服务端的压力。如果注册一个Watcher之后一直有效,那么针对更新非常频繁的节点,服务端会不断地向客户端发送事件通知,这无论对于网络还是服务端性能的影响都非常大
  • 发送给客户端(Sent to the client)
      Watch的通知事件是从服务器发送给客户端的,是异步的,即不同的客户端收到的Watch的时间可能不同。Zookeeper 本身提供了保序性(ordering guarantee):即客户端只有首先看到了监视事件后,才会感知到它所设置监视的 znode 发生了变化。网络延迟或者其他因素可能导致不同的客户端在不同的时刻感知某一监视事件,但是不同的客户端所看到的一切具有一致的顺序。
  • 设置Watch的数据内容
      Znode改变有很多种方式,例如:节点创建,节点删除,节点改变,子节点改变等等。Zookeeper维护了两个Watch列表,一个节点数据Watch列表,另一个是子节点Watch列表。getData()和exists()设置数据Watch,getChildren()设置子节点Watch。两者选其一,可以让我们根据不同的返回结果选择不同的Watch方式,getData()和exists()返回节点的内容,getChildren()返回子节点列表。因此,setData()触发内容Watch,create()触发当前节点的内容Watch或者是其父节点的子节点Watch。delete()同时触发父节点的子节点Watch和内容Watch,以及子节点的内容Watch。

  接下来将从ZooKeeper客户端进行Watcher注册服务端处理Watcher以及客户端回调Wathcer三方面分阶段讲解了ZooKeeper的Watcher工作机制。

服务端处理Watcher

  客户端注册Watcher的过程中最终客户端并不会将Watcher对象真正传递到服务端。那么服务端究竟是如何完成客户端的Watcher注册,又是如何来处理这个Watcher的呢?

ServerCnxn存储

服务端处理Watcher的时序图:
在这里插入图片描述
服务端收到来自客户端的请求后,在FinalRequestProcessor.processRequest()中会判断当前请求是否需要注册Watcher:

case OpCode.getData:{
     ...
     byte b[] = zks.getZKDatabase().getData(getDataRequest.getPath(), stat, getDataRequest.getWatch()?cnxn:null);
      rsp = new GetDataResponse(b,stat);
      break;
}

getData请求的处理逻辑中,当getDataRequest.getWatch()为true的时候,ZooKeeper认为当前客户端请求需要进行Watcher注册,于是就会将当前的ServerCnxn对象和数据节点路径传入getData方法中去。对于标记了Watcher注册的请求,ZooKeeper会将其对应的ServerCnxn存储到WatchManager中。
  ServerCnxn是一个ZooKeeper客户端和服务器之间的连接接口,代表了一个客户端和服务器的连接,实现了Watcher的process接口,因此可以将ServerCnxn看作是一个Watcher对象。数据节点的节点路径和ServerCnxn最终会被存储在WatcherManager的watchTable和watch2Paths中。

  • WatchManager是ZooKeeper服务端Watcher的管理者,其内部管理的watchTable和watch2Pashs两个存储结构,分别从两个维度对Watcher进行存储
  • watchTable是从数据节点路径的粒度来托管Watcher
  • watch2Paths是从Watcher的粒度来控制事件触发需要触发的数据节点

服务端触发Watcher

  NodeDataChanged事件的触发条件是“Watcher监听的对应数据节点的数据内容发生变更”,其具体实现如下:

public Stat setData(String path, byte data[] ,int version,long zxid,long time)throws KeeperException.NoNodeException{
       Stat s = new Stat();
       DataNode n = nodes.get(path);
       if(n == null){
               throw new KeeperException.NoNodeException();
       }
        byte lastdata[] = null;
        synchronized(n){
               lastdata = n.data;
               n.data = data;
               n.stat.setMtime(time);
               n.stat.setMzxid(zxid);
               n.stat.setVersion(version);
               n.copyStat(s);
         }
         //...
          dataWatches.triggerWatch(path,EventType.NodeDataChanged);
          return s;
}

在对指定节点进行数据更新后,通过调用WatchManager的triggerWatch方法来触发相关的事件:

public Set<Watcher> triggerWatch(String path, EventType type){
        return triggerWatch(path,tyep,null);
}
 
public Set<Watcher> triggerWatch(String path, EventType type, Set<Watcher> supress){
      WatchedEvent e = new WatchedEvent(type,KeeperState.SyncConnected, path);
      HashSet<Watcher> watchers;
      synchronized(this){
            watchers = watchTable.remove(path);
            //...
            //如果不存在Watcher,直接返回
            for(Watcher w :watchers){
                   HashSet<String> paths = watch2Paths.get(w);
                   if(paths != null){
                         paths.remove(path);
                   }
            }
      }
      for(Watcher w : watches){
            if(supress != null && supress.contains(w)){
                  continue;
             }
             w.process(e);
      }
      return watches;
}

无论是dataWatches或是childWatches管理器,Watcher的触发逻辑都是一致的,基本步骤如下:

  1. 封装WatchedEvent。
    首先通知状态(KeeperState)、事件类型(EventType)以及节点路径(Path)封装成一个WatchedEvent对象
  2. 查询Watcher。
    根据数据节点的节点路径从watchTable中取出对应的Watcher。如果没有找到Watcher,说明没有任何客户端在该数据节点上注册过Watcher,直接退出。而如果找到了这个Watcher,会将其提取出来,同时会直接从watchTable和watch2Paths中将其删除——从这里我们也可以看出,Watcher在服务端是一次性的,即触发一次就失效了
  3. 调用process方法来触发Watcher。
    在这一步中,会逐个依次地调用从步骤2中找出的所有Water的process方法。那么这里的process方法究竟做了什么呢?在上文中我们已经提到,对于需要注册Watcher的请求,ZooKeeper会把当前请求对应的ServerCnxn作为一个Watcher进行存储,因此,这里的process方法,事实上就是ServerCnxn的对应方法:
public class NIOServerCnxn extends ServerCnxn{
     //...
     synchronized public void process(WatchedEvent evetn){
            ReplyHeader h = new ReplyHeader(-1,-1L,0);
            //...
            //Convert WatchedEvent to a type that can be sent over the wire
            WatcherEvent e = event.getWarpper();
            senResponse(h,e,"notification");
     }
}

从上面的代码片段中,我们可以看出在process方法中,主要逻辑如下:

  • 在请求头中标记“-1”,表明当前是一个通知
  • 将WawtchedEvent包装成WatcherEvent,以便进行网络传输序列化
  • 向客户端发送该通知

ServerCnxn的process方法本质上并不是处理客户端Watcher真正的业务逻辑,而是把当前客户端连接的ServerCnxn对象来实现对客户端的WatchedEvent传递,真正的客户端Watcher回调与业务逻辑执行都在客户端。Watcher触发的最终服务端会通过使用ServerCnxn对应的TCP连接来向客户端发送一个WatcherEvent事件

客户端回调Watcher

SendThread接收事件通知

ZooKeeper客户端接收客户端事件通知:

class SendThread extends Thread(
	//...
        void readResponse(ByteBuffer incomingBuffer) throws IOException{
		//...
		if(replyHdr.getXid() == -1){
   			//-1 means notification
			//...
			WatcherEvent event = new WatcherEvent();
			event.deserialize(bbia,"response");
			//convert from a server path to a client path
			if(chrootPath != null){
				String serverPath = event.getPath();
				if(serverPath.compareTo(chrootPath)==0)
					event.setPath("/");
				else if(serverPath.length()>chrootPath.length())
				event.setPath(serverPath.subString(chrootPath.length()));
				//...
			}
			WatchedEvent we = new WatchedEvent(event);
			//...
			evetnThread.queueEvent(we);
			return;
		}
	}
)

对于一个来自服务端的响应,客户端都是由SendThread。readResponse(ByteBuffer incomingBuffer)方法来统一进行处理的,如果响应头replyHdr中标识了XID为-1,表明这是一个通知类型的响应。

EventThread处理事件通知

  SendThread接收到服务端的通知事件后,会通过调用EventThread.queueEvent方法将事件传给EventThread线程,其逻辑如下:

public void queueEvent(WatchedEvent event) {
	if(event.getType() == EventType.None && sessionState == event.getState()){
		return;
	}
}
sessionState = event.getState();
//materialize the watchers based on the event
WatcherSetEventPair pair = new WatcherSetEventPair(watcher.materialize(event.getState(),event.getType(),event.getPaht(),event);
//queue the pair(watch set & event) for later processing
waitingEvents.add(pair);
}

queueEvent方法首先会根据该通知事件,从ZKWatchManager中取出所有相关的Watcher:

public Set<Watcher> materialize(Watcher.Event.KeeperState state,Watcher.Event.EventType type,String clientPath){
	Set<Watcher> result = new HashSet<Watcher>();
	switch(type){
		//...
		case NodeDataChanged:
		case NodeCreated;
			synchronized(dataWatches){
				addTo(dataWatches.remove(clientPath),result);
			}
			synchronized(existWatches){
				addTo(existWatches.remove(clientPath),result);
			}
			break;
			//...
			return result;
	}
	final private void addTo(Set<Watcher> from ,Set<Watcher> to){
		if(from != null){
			to.addAll(from);	
		}
	}
}

客户端在识别出事件类型EventType后,会从相应的Watcher存储(即dataWatches,existWatches或childWatches中的一个或多个,本例中就是从dataWatches和existWatches两个存储中获取)中去除对应的Watcher。注意,此处使用的是remove接口,因此也表明了客户端的Watcher机制同样也是一次性的,即一旦被触发后,该Watcher就失效了。
  获取到相关的额所有Watcher后,会将其放入waitingEvents这个队列中去。WaitingEvents是一个待处理Watcher队列,EventThread的run方法会不断对该队列进行处理:

public void run(){
	try{
		isRunning = true;
		while(true){
			Object event = waitingEvents.take();
			if(event == eventOfDeath){
				wasKilled = true;
			}else{
				processEvent(event);
			}
			//...
		}
	}
}
private void processEvent(Object event){
	try{
		if(evemt instanceof WatcherSetEventPair){
			//each watcher will process the event
			WatcherSetEventPair pair = (WatcherSetEventPair)event;
			for(Watcher watcher : pair.watchers){
\				try{
					watcher.process(pair.event);
				}catch(Throwable t){
				//....
			}
		}
	}
}

EventThread线程每次都会从waitingEvents队列中取出一个Watcher,并进行串行同步处理。注意,此处processEvent方法中的Watcher才是之前客户端真正注册的Watcher,调用其process方法就可以实现Watcher的回调了。

Zookeeper Watcher的运行机制

  1. Watch是轻量级的,其实是本地JVM的Callback,服务器端只是存了是否有设置了Watcher的布尔类型
  2. 在服务端,在FinalRequestProcessor处理对应的Znode操作时,会根据客户端传递的watcher变量,添加到对应的ZKDatabase中进行持久化存储,同时将自己NIOServerCnxn做为一个Watcher callback,监听服务端事件变化
  3. Leader通过投票通过了某次Znode变化的请求后,然后通知对应的Follower,Follower根据自己内存中的zkDataBase信息,发送notification信息给zookeeper客户端
  4. Zookeeper客户端接收到notification信息后,找到对应变化path的watcher列表,挨个进行触发回调
发布了107 篇原创文章 · 获赞 19 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/ThreeAspects/article/details/103558797