深入分析 Watcher 机制的实现原理(二)服务端接收请求处理流程

本文主要是介绍深入分析 Watcher 机制的实现原理(二)服务端接收请求处理流程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

服务端接收请求处理流程

服务端有一个 NettyServerCnxn 类,用来处理客户端发送过来的请求

private void receiveMessage(ByteBuf message) {checkIsInEventLoop("receiveMessage");try {while (message.isReadable() && !throttled.get()) {// //ByteBuffer 不为空if (bb != null) {if (LOG.isTraceEnabled()) {LOG.trace("message readable {} bb len {} {}", message.readableBytes(), bb.remaining(), bb);ByteBuffer dat = bb.duplicate();dat.flip();LOG.trace("0x{} bb {}", Long.toHexString(sessionId), ByteBufUtil.hexDump(Unpooled.wrappedBuffer(dat)));}//bb 剩余空间大于 message 中可读字节大小if (bb.remaining() > message.readableBytes()) {int newLimit = bb.position() + message.readableBytes();bb.limit(newLimit);}// 将 message 写入 bb 中message.readBytes(bb);bb.limit(bb.capacity());if (LOG.isTraceEnabled()) {LOG.trace("after readBytes message readable {} bb len {} {}", message.readableBytes(), bb.remaining(), bb);ByteBuffer dat = bb.duplicate();dat.flip();LOG.trace("after readbytes 0x{} bb {}",Long.toHexString(sessionId),ByteBufUtil.hexDump(Unpooled.wrappedBuffer(dat)));}// 已经读完 messageif (bb.remaining() == 0) {bb.flip();//统计接收信息packetReceived(4 + bb.remaining());ZooKeeperServer zks = this.zkServer;if (zks == null || !zks.isRunning()) {throw new IOException("ZK down");}if (initialized) {// TODO: if zks.processPacket() is changed to take a ByteBuffer[],// we could implement zero-copy queueing.//处理客户端传送过来的数据包zks.processPacket(this, bb);} else {LOG.debug("got conn req request from {}", getRemoteSocketAddress());zks.processConnectRequest(this, bb);initialized = true;}bb = null;}} else {if (LOG.isTraceEnabled()) {LOG.trace("message readable {} bblenrem {}", message.readableBytes(), bbLen.remaining());ByteBuffer dat = bbLen.duplicate();dat.flip();LOG.trace("0x{} bbLen {}", Long.toHexString(sessionId), ByteBufUtil.hexDump(Unpooled.wrappedBuffer(dat)));}if (message.readableBytes() < bbLen.remaining()) {bbLen.limit(bbLen.position() + message.readableBytes());}message.readBytes(bbLen);bbLen.limit(bbLen.capacity());if (bbLen.remaining() == 0) {bbLen.flip();if (LOG.isTraceEnabled()) {LOG.trace("0x{} bbLen {}", Long.toHexString(sessionId), ByteBufUtil.hexDump(Unpooled.wrappedBuffer(bbLen)));}int len = bbLen.getInt();if (LOG.isTraceEnabled()) {LOG.trace("0x{} bbLen len is {}", Long.toHexString(sessionId), len);}bbLen.clear();if (!initialized) {if (checkFourLetterWord(channel, message, len)) {return;}}if (len < 0 || len > BinaryInputArchive.maxBuffer) {throw new IOException("Len error " + len);}// checkRequestSize will throw IOException if request is rejectedzkServer.checkRequestSizeWhenReceivingMessage(len);bb = ByteBuffer.allocate(len);}}}} catch (IOException e) {LOG.warn("Closing connection to {}", getRemoteSocketAddress(), e);close(DisconnectReason.IO_EXCEPTION);} catch (ClientCnxnLimitException e) {// Common case exception, print at debug levelServerMetrics.getMetrics().CONNECTION_REJECTED.add(1);LOG.debug("Closing connection to {}", getRemoteSocketAddress(), e);close(DisconnectReason.CLIENT_RATE_LIMIT);}}

zks.processPacket(this, bb) 方法:

public void processPacket(ServerCnxn cnxn, ByteBuffer incomingBuffer) throws IOException {// We have the request, now process and setup for nextInputStream bais = new ByteBufferInputStream(incomingBuffer);BinaryInputArchive bia = BinaryInputArchive.getArchive(bais);RequestHeader h = new RequestHeader();//反序列化客户端 header 头信息h.deserialize(bia, "header");// Need to increase the outstanding request count first, otherwise// there might be a race condition that it enabled recv after// processing request and then disabled when check throttling.//// Be aware that we're actually checking the global outstanding// request before this request.//// It's fine if the IOException thrown before we decrease the count// in cnxn, since it will close the cnxn anyway.cnxn.incrOutstandingAndCheckThrottle(h);// Through the magic of byte buffers, txn will not be// pointing// to the start of the txnincomingBuffer = incomingBuffer.slice();//判断当前操作类型if (h.getType() == OpCode.auth) {LOG.info("got auth packet {}", cnxn.getRemoteSocketAddress());AuthPacket authPacket = new AuthPacket();ByteBufferInputStream.byteBuffer2Record(incomingBuffer, authPacket);String scheme = authPacket.getScheme();ServerAuthenticationProvider ap = ProviderRegistry.getServerProvider(scheme);Code authReturn = KeeperException.Code.AUTHFAILED;if (ap != null) {try {// handleAuthentication may close the connection, to allow the client to choose// a different server to connect to.authReturn = ap.handleAuthentication(new ServerAuthenticationProvider.ServerObjs(this, cnxn),authPacket.getAuth());} catch (RuntimeException e) {LOG.warn("Caught runtime exception from AuthenticationProvider: {}", scheme, e);authReturn = KeeperException.Code.AUTHFAILED;}}if (authReturn == KeeperException.Code.OK) {LOG.debug("Authentication succeeded for scheme: {}", scheme);LOG.info("auth success {}", cnxn.getRemoteSocketAddress());ReplyHeader rh = new ReplyHeader(h.getXid(), 0, KeeperException.Code.OK.intValue());cnxn.sendResponse(rh, null, null);} else {if (ap == null) {LOG.warn("No authentication provider for scheme: {} has {}",scheme,ProviderRegistry.listProviders());} else {LOG.warn("Authentication failed for scheme: {}", scheme);}// send a response...ReplyHeader rh = new ReplyHeader(h.getXid(), 0, KeeperException.Code.AUTHFAILED.intValue());cnxn.sendResponse(rh, null, null);// ... and close connectioncnxn.sendBuffer(ServerCnxnFactory.closeConn);cnxn.disableRecv();}return;} else if (h.getType() == OpCode.sasl) {//如果不是授权操作,再判断是否为 sasl 操作processSasl(incomingBuffer, cnxn, h);} else {if (shouldRequireClientSaslAuth() && !hasCnxSASLAuthenticated(cnxn)) {ReplyHeader replyHeader = new ReplyHeader(h.getXid(), 0, Code.SESSIONCLOSEDREQUIRESASLAUTH.intValue());cnxn.sendResponse(replyHeader, null, "response");cnxn.sendCloseSession();cnxn.disableRecv();} else {//最终进入这个代码块进行处理//封装请求对象Request si = new Request(cnxn, cnxn.getSessionId(), h.getXid(), h.getType(), incomingBuffer, cnxn.getAuthInfo());int length = incomingBuffer.limit();if (isLargeRequest(length)) {// checkRequestSize will throw IOException if request is rejectedcheckRequestSizeWhenMessageReceived(length);si.setLargeRequestSize(length);}si.setOwner(ServerCnxn.me);//提交请求submitRequest(si);}}}

submitRequest方法 负责在服务端提交当前请求

public void submitRequestNow(Request si) {if (firstProcessor == null) {synchronized (this) {try {// Since all requests are passed to the request// processor it should wait for setting up the request// processor chain. The state will be updated to RUNNING// after the setup.while (state == State.INITIAL) {wait(1000);}} catch (InterruptedException e) {LOG.warn("Unexpected interruption", e);}if (firstProcessor == null || state != State.RUNNING) {throw new RuntimeException("Not started");}}}try {touch(si.cnxn);boolean validpacket = Request.isValid(si.type);if (validpacket) {setLocalSessionFlag(si);//处理请求 责任链模式firstProcessor.processRequest(si);if (si.cnxn != null) {incInProcess();}} else {LOG.warn("Received packet at server of unknown type {}", si.type);// Update request accounting/throttling limitsrequestFinished(si);new UnimplementedRequestProcessor().processRequest(si);}} catch (MissingSessionException e) {LOG.debug("Dropping request.", e);// Update request accounting/throttling limitsrequestFinished(si);} catch (RequestProcessorException e) {LOG.error("Unable to process request", e);// Update request accounting/throttling limitsrequestFinished(si);}}

firstProcessor.processRequest(si);

firstProcessor 的 初 始 化 是 在 ZookeeperServer 的setupRequestProcessor 中完成的,代码如下

protected void setupRequestProcessors() {RequestProcessor finalProcessor = new FinalRequestProcessor(this);RequestProcessor syncProcessor = new SyncRequestProcessor(this, finalProcessor);((SyncRequestProcessor) syncProcessor).start();firstProcessor = new PrepRequestProcessor(this, syncProcessor);((PrepRequestProcessor) firstProcessor).start();}

这里用的责任链模式

从上面我们可以看到 firstProcessor 的实例是一个PrepRequestProcessor,而这个构造方法中又传递了一
个 Processor 构成了一个调用链。RequestProcessor syncProcessor = new SyncRequestProcessor(this, finalProcessor);
而syncProcessor的构造方法传递的又是一个Processor,对应的是 FinalRequestProcessor

所 以 整 个 调 用 链 是 PrepRequestProcessor ->SyncRequestProcessor ->FinalRequestProcessor

PrepRequestProcessor 的processRequest方法

LinkedBlockingQueue<Request> submittedRequests = new LinkedBlockingQueue<Request>();public void processRequest(Request request) {request.prepQueueStartTime = Time.currentElapsedTime();submittedRequests.add(request);ServerMetrics.getMetrics().PREP_PROCESSOR_QUEUED.add(1);
}

PrepRequestProcessor 这个类又继承了线程类 是基于异步化的操作 看run()方法

public void run() {try {while (true) {ServerMetrics.getMetrics().PREP_PROCESSOR_QUEUE_SIZE.add(submittedRequests.size());//从阻塞队列中拿到请求进行处理Request request = submittedRequests.take();ServerMetrics.getMetrics().PREP_PROCESSOR_QUEUE_TIME.add(Time.currentElapsedTime() - request.prepQueueStartTime);long traceMask = ZooTrace.CLIENT_REQUEST_TRACE_MASK;if (request.type == OpCode.ping) {traceMask = ZooTrace.CLIENT_PING_TRACE_MASK;}if (LOG.isTraceEnabled()) {ZooTrace.logRequest(LOG, traceMask, 'P', request, "");}if (Request.requestOfDeath == request) {break;}request.prepStartTime = Time.currentElapsedTime();//调用pRequest 进行预处理pRequest(request);}} catch (Exception e) {handleException(this.getName(), e);}LOG.info("PrepRequestProcessor exited loop!");}

pRequest方法

protected void pRequest(Request request) throws RequestProcessorException {// LOG.info("Prep>>> cxid = " + request.cxid + " type = " +// request.type + " id = 0x" + Long.toHexString(request.sessionId));request.setHdr(null);request.setTxn(null);if (!request.isThrottled()) {pRequestHelper(request);}request.zxid = zks.getZxid();ServerMetrics.getMetrics().PREP_PROCESS_TIME.add(Time.currentElapsedTime() - request.prepStartTime);nextProcessor.processRequest(request);}

nextProcessor 对 应 的 应 该 是SyncRequestProcessor

S yncRequestProcessor. processRequest方法

private final BlockingQueue<Request> queuedRequests = new LinkedBlockingQueue<Request>();public void processRequest(final Request request) {Objects.requireNonNull(request, "Request cannot be null");request.syncQueueStartTime = Time.currentElapsedTime();queuedRequests.add(request);ServerMetrics.getMetrics().SYNC_PROCESSOR_QUEUED.add(1);}

也看run方法

@Overridepublic void run() {try {// we do this in an attempt to ensure that not all of the servers// in the ensemble take a snapshot at the same timeresetSnapshotStats();lastFlushTime = Time.currentElapsedTime();while (true) {ServerMetrics.getMetrics().SYNC_PROCESSOR_QUEUE_SIZE.add(queuedRequests.size());long pollTime = Math.min(zks.getMaxWriteQueuePollTime(), getRemainingDelay());Request si = queuedRequests.poll(pollTime, TimeUnit.MILLISECONDS);if (si == null) {/* We timed out looking for more writes to batch, go ahead and flush immediately */flush();//从阻塞队列中获取请求si = queuedRequests.take();}if (si == REQUEST_OF_DEATH) {break;}long startProcessTime = Time.currentElapsedTime();ServerMetrics.getMetrics().SYNC_PROCESSOR_QUEUE_TIME.add(startProcessTime - si.syncQueueStartTime);// track the number of records written to the log//下面这块代码,粗略看来是触发快照操作,启动一个处理快照的线程if (!si.isThrottled() && zks.getZKDatabase().append(si)) {if (shouldSnapshot()) {resetSnapshotStats();// roll the logzks.getZKDatabase().rollLog();// take a snapshotif (!snapThreadMutex.tryAcquire()) {LOG.warn("Too busy to snap, skipping");} else {new ZooKeeperThread("Snapshot Thread") {public void run() {try {zks.takeSnapshot();} catch (Exception e) {LOG.warn("Unexpected exception", e);} finally {snapThreadMutex.release();}}}.start();}}} else if (toFlush.isEmpty()) {// optimization for read heavy workloads// iff this is a read or a throttled request(which doesn't need to be written to the disk),// and there are no pending flushes (writes), then just pass this to the next processorif (nextProcessor != null) {继续调用下一个处理器来处理请求nextProcessor.processRequest(si);if (nextProcessor instanceof Flushable) {((Flushable) nextProcessor).flush();}}continue;}toFlush.add(si);if (shouldFlush()) {flush();}ServerMetrics.getMetrics().SYNC_PROCESS_TIME.add(Time.currentElapsedTime() - startProcessTime);}} catch (Throwable t) {handleException(this.getName(), t);}LOG.info("SyncRequestProcessor exited!");}

FinalRe questProcessor. . processRequest方 法 并 根 据Request 对象中的操作更新内存中 Session 信息或者znode 数据。

关键代码:

ExistsRequest existsRequest = new ExistsRequest();//反序列化 (将 ByteBuffer 反序列化成为 ExitsRequest.这个就是我们在客户端发起请求的时候传递过来的 Request 对象ByteBufferInputStream.byteBuffer2Record(request.request, existsRequest);//得到请求路径path = existsRequest.getPath();if (path.indexOf('\0') != -1) {throw new KeeperException.BadArgumentsException();}//终于找到一个很关键的代码,判断请求的 getWatch 是否存在,如果存在,则传递 cnxn(servercnxn)//对于 exists 请求,需要监听 data 变化事件,添加 watcherStat stat = zks.getZKDatabase().statNode(path, existsRequest.getWatch() ? cnxn : null);//在服务端内存数据库中根据路径得到结果进行组装,设置为 ExistsResponsersp = new ExistsResponse(stat);requestPathMetricsCollector.registerRequest(request.type, path);break;

statNode方法:

public Stat statNode(String path, Watcher watcher) throws KeeperException.NoNodeException {Stat stat = new Stat();//获得节点数据DataNode n = nodes.get(path);//如果 watcher 不为空,则讲当前的 watcher 和 path 进行绑定if (watcher != null) {dataWatches.addWatch(path, watcher);}if (n == null) {throw new KeeperException.NoNodeException();}synchronized (n) {n.copyStat(stat);}updateReadStat(path, 0L);return stat;}

WatchManager的addWatch方法:

@Overridepublic synchronized boolean addWatch(String path, Watcher watcher, WatcherMode watcherMode) {if (isDeadWatcher(watcher)) {LOG.debug("Ignoring addWatch with closed cnxn");return false;}//判断 watcherTable 中是否存在当前路径对应的 watcherSet<Watcher> list = watchTable.get(path);//不存在则主动添加if (list == null) {// don't waste memory if there are few watches on a node// rehash when the 4th entry is added, doubling size thereafter// seems like a good compromise// 新生成 watcher 集合list = new HashSet<>(4);watchTable.put(path, list);}list.add(watcher);Set<String> paths = watch2Paths.get(watcher);if (paths == null) {// cnxns typically have many watches, so use default cap herepaths = new HashSet<>();// 设置watcher 到节点路径的映射watch2Paths.put(watcher, paths);}watcherModeManager.setWatcherMode(watcher, path, watcherMode);// 将路径添加至paths集合return paths.add(path);}

其大致流程如下
① 通过传入的 path(节点路径)从 watchTable 获取相应的 watcher 集合,进入②
② 判断①中的 watcher 是否为空,若为空,则进入③,否则,进入④
③ 新生成 watcher 集合,并将路径 path 和此集合添加至 watchTable 中,进入④
④ 将传入的 watcher 添加至 watcher 集合,即完成了path 和 watcher 添加至 watchTable 的步骤,进入⑤
⑤ 通过传入的 watcher 从 watch2Paths 中获取相应的 path 集合,进入⑥
⑥ 判断 path 集合是否为空,若为空,则进入⑦,否则,进入⑧
⑦ 新生成 path 集合,并将 watcher 和 paths 添加至watch2Paths 中,进入⑧
⑧ 将传入的 path(节点路径)添加至 path 集合,即完成了 path 和 watcher 添加至 watch2Paths 的步骤

NettyServerCnxn的sendResponse()方法

@Overridepublic void sendResponse(ReplyHeader h, Record r, String tag,String cacheKey, Stat stat, int opCode) throws IOException {// cacheKey and stat are used in caching, which is not// implemented here. Implementation example can be found in NIOServerCnxn.if (closingChannel || !channel.isOpen()) {return;}sendBuffer(serialize(h, r, tag, cacheKey, stat, opCode));decrOutstandingAndCheckThrottle(h);}

服务端接收请求处理流程图:

image-20200531004628210

这篇关于深入分析 Watcher 机制的实现原理(二)服务端接收请求处理流程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/360432

相关文章

canal实现mysql数据同步的详细过程

《canal实现mysql数据同步的详细过程》:本文主要介绍canal实现mysql数据同步的详细过程,本文通过实例图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的... 目录1、canal下载2、mysql同步用户创建和授权3、canal admin安装和启动4、canal

Maven 配置中的 <mirror>绕过 HTTP 阻断机制的方法

《Maven配置中的<mirror>绕过HTTP阻断机制的方法》:本文主要介绍Maven配置中的<mirror>绕过HTTP阻断机制的方法,本文给大家分享问题原因及解决方案,感兴趣的朋友一... 目录一、问题场景:升级 Maven 后构建失败二、解决方案:通过 <mirror> 配置覆盖默认行为1. 配置示

Nexus安装和启动的实现教程

《Nexus安装和启动的实现教程》:本文主要介绍Nexus安装和启动的实现教程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、Nexus下载二、Nexus安装和启动三、关闭Nexus总结一、Nexus下载官方下载链接:DownloadWindows系统根

java Long 与long之间的转换流程

《javaLong与long之间的转换流程》Long类提供了一些方法,用于在long和其他数据类型(如String)之间进行转换,本文将详细介绍如何在Java中实现Long和long之间的转换,感... 目录概述流程步骤1:将long转换为Long对象步骤2:将Longhttp://www.cppcns.c

SpringBoot集成LiteFlow实现轻量级工作流引擎的详细过程

《SpringBoot集成LiteFlow实现轻量级工作流引擎的详细过程》LiteFlow是一款专注于逻辑驱动流程编排的轻量级框架,它以组件化方式快速构建和执行业务流程,有效解耦复杂业务逻辑,下面给大... 目录一、基础概念1.1 组件(Component)1.2 规则(Rule)1.3 上下文(Conte

MySQL 横向衍生表(Lateral Derived Tables)的实现

《MySQL横向衍生表(LateralDerivedTables)的实现》横向衍生表适用于在需要通过子查询获取中间结果集的场景,相对于普通衍生表,横向衍生表可以引用在其之前出现过的表名,本文就来... 目录一、横向衍生表用法示例1.1 用法示例1.2 使用建议前面我们介绍过mysql中的衍生表(From子句

Mybatis的分页实现方式

《Mybatis的分页实现方式》MyBatis的分页实现方式主要有以下几种,每种方式适用于不同的场景,且在性能、灵活性和代码侵入性上有所差异,对Mybatis的分页实现方式感兴趣的朋友一起看看吧... 目录​1. 原生 SQL 分页(物理分页)​​2. RowBounds 分页(逻辑分页)​​3. Page

Python基于微信OCR引擎实现高效图片文字识别

《Python基于微信OCR引擎实现高效图片文字识别》这篇文章主要为大家详细介绍了一款基于微信OCR引擎的图片文字识别桌面应用开发全过程,可以实现从图片拖拽识别到文字提取,感兴趣的小伙伴可以跟随小编一... 目录一、项目概述1.1 开发背景1.2 技术选型1.3 核心优势二、功能详解2.1 核心功能模块2.

MYSQL查询结果实现发送给客户端

《MYSQL查询结果实现发送给客户端》:本文主要介绍MYSQL查询结果实现发送给客户端方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录mysql取数据和发数据的流程(边读边发)Sending to clientSending DataLRU(Least Rec

Java中实现线程的创建和启动的方法

《Java中实现线程的创建和启动的方法》在Java中,实现线程的创建和启动是两个不同但紧密相关的概念,理解为什么要启动线程(调用start()方法)而非直接调用run()方法,是掌握多线程编程的关键,... 目录1. 线程的生命周期2. start() vs run() 的本质区别3. 为什么必须通过 st