netty服务端启动过程分析

Love The Way You Lie 2023-06-13 04:42 73阅读 0赞

netty 服务端启动

  1. 创建ServerBootstrap,该类是Netty服务端的启动类
  2. 绑定Reactor线程池,EventLoopGroup,实际上就是EventLoop的数组.除了处理IO操作外,用户提交的task和定时任务也是由EventLoop执行.避免了多线程竞争的情况
  3. 设置并绑定服务端Channel,对于Nio服务端,使用的是NioServerSocketChannel
  4. 链路建立是创建并初始化ChannelPipeline.其本质是一个处理网络事件的职责链
  5. 初始化ChannelPipline完成之后,添加并设置ChannelHandler,
  6. 绑定并启动监听端口,在绑定之前系统会先进行一些初始化,完成之后会启动监听端口,并将ServerSocketChannel注册到Selector上监听客户端连接
  7. Selector轮询.由Reactor线程NioEventLoop负责调度和执行Selector轮询,选择准备就绪的Channel集合.
  8. 当轮询到准备就绪的Channel之后,由Reactor线程执行ChannelPipeline的相应方法,最终调度执行ChannelHandler
  9. 执行Netty系统ChannelHandler和用户自定义的ChannelHandler。ChannelPipeline根据网络事件的类型,调度并执行ChannelHandler。

源码分析

服务端从bind 函数启动。bind 函数最后访问到了AbstractBootstrap的 dobind 函数,如下

  1. private ChannelFuture doBind(final SocketAddress localAddress) {
  2. final ChannelFuture regFuture = initAndRegister();
  3. //省略其他函数
  4. }

初始化

  1. final ChannelFuture initAndRegister() {
  2. Channel channel = null;
  3. try {
  4. channel = channelFactory.newChannel();
  5. init(channel);
  6. //省略其他函数
  7. }
  1. 使用 channelFactory 的 newChannel 构造一个 channel,对于 Nio应用来说,这里是NioServerSocketChannel,其使用了反射来获取实例。
  2. 调用 init 函数

init 函数是一个抽象函数,被定义在了ServerBootstrap

  1. void init(Channel channel) throws Exception {
  2. final Map<ChannelOption<?>, Object> options = options0();
  3. 设置 Socket 参数和 NioServerSocketChannel 的附加属性
  4. synchronized (options) {
  5. setChannelOptions(channel, options, logger);
  6. }
  7. final Map<AttributeKey<?>, Object> attrs = attrs0();
  8. synchronized (attrs) {
  9. for (Entry<AttributeKey<?>, Object> e: attrs.entrySet()) {
  10. @SuppressWarnings("unchecked")
  11. AttributeKey<Object> key = (AttributeKey<Object>) e.getKey();
  12. channel.attr(key).set(e.getValue());
  13. }
  14. }
  15. //
  16. ChannelPipeline p = channel.pipeline();
  17. final EventLoopGroup currentChildGroup = childGroup;
  18. final ChannelHandler currentChildHandler = childHandler;
  19. final Entry<ChannelOption<?>, Object>[] currentChildOptions;
  20. final Entry<AttributeKey<?>, Object>[] currentChildAttrs;
  21. synchronized (childOptions) {
  22. currentChildOptions = childOptions.entrySet().toArray(newOptionArray(0));
  23. }
  24. synchronized (childAttrs) {
  25. currentChildAttrs = childAttrs.entrySet().toArray(newAttrArray(0));
  26. }
  27. p.addLast(new ChannelInitializer<Channel>() {
  28. @Override
  29. public void initChannel(final Channel ch) throws Exception {
  30. final ChannelPipeline pipeline = ch.pipeline();
  31. ChannelHandler handler = config.handler();
  32. if (handler != null) {
  33. pipeline.addLast(handler);///将 AbstractBootstrap 的 Handler 添加到 ChannelPipeline 中
  34. }
  35. ch.eventLoop().execute(new Runnable() {
  36. @Override
  37. public void run() {
  38. //添加用于注册的 handler
  39. pipeline.addLast(new ServerBootstrapAcceptor(
  40. ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
  41. }
  42. });
  43. }
  44. });
  45. }

前面一大堆其实都是设置连接参数,对于 Server 来说关键点在于添加了ServerBootstrapAcceptor这是一个内部类,并且其是server 的唯一一个handler。暂且略过不提。

注册

init 后回到initAndRegister函数

  1. final ChannelFuture initAndRegister() {
  2. //省略其他代码
  3. ChannelFuture regFuture = config().group().register(channel);
  4. if (regFuture.cause() != null) {
  5. if (channel.isRegistered()) {
  6. channel.close();
  7. } else {
  8. channel.unsafe().closeForcibly();
  9. }
  10. }
  11. return regFuture;
  12. }

从当前的 执行线程中获取一个并将 channel注册到这个线程中。

对于 NioServerChannel其调用到了SingleThreadEventLoop的 register 函数

  1. @Override
  2. public ChannelFuture register(Channel channel) {
  3. return register(new DefaultChannelPromise(channel, this));
  4. }
  5. @Override
  6. public ChannelFuture register(final ChannelPromise promise) {
  7. ObjectUtil.checkNotNull(promise, "promise");
  8. promise.channel().unsafe().register(this, promise);
  9. return promise;
  10. }

对于 NioServerChannel 的 unsafe 函数,其在AbstractNioMessageChannel中实现

而 register 函数,则在AbstractUnsafe中定义,并被声明为 final

  1. public final void register(EventLoop eventLoop, final ChannelPromise promise) {
  2. if (eventLoop == null) {
  3. throw new NullPointerException("eventLoop");
  4. }
  5. if (isRegistered()) {
  6. promise.setFailure(new IllegalStateException("registered to an event loop already"));
  7. return;
  8. }
  9. if (!isCompatible(eventLoop)) {
  10. promise.setFailure(
  11. new IllegalStateException("incompatible event loop type: " + eventLoop.getClass().getName()));
  12. return;
  13. }
  14. AbstractChannel.this.eventLoop = eventLoop;
  15. if (eventLoop.inEventLoop()) {
  16. register0(promise);
  17. } else {
  18. try {
  19. eventLoop.execute(new Runnable() {
  20. @Override
  21. public void run() {
  22. register0(promise);
  23. }
  24. });
  25. } catch (Throwable t) {
  26. logger.warn(
  27. "Force-closing a channel whose registration task was not accepted by an event loop: {}",
  28. AbstractChannel.this, t);
  29. closeForcibly();
  30. closeFuture.setClosed();
  31. safeSetFailure(promise, t);
  32. }
  33. }
  34. }

前面的函数是参数校验,

关键代码为

  1. AbstractChannel.this.eventLoop = eventLoop;

这行代码将 evetloop(即指定的线程) 绑定到了 channel 中。

此时调用线程仍然是用户线程,因此会进入

  1. eventLoop.execute(new Runnable() {
  2. @Override
  3. public void run() {
  4. register0(promise);
  5. }
  6. });

从此刻开始,netty 线程和用户线程就开始并行了。

随后由 eventLoop 来执行register0函数

  1. private void register0(ChannelPromise promise) {
  2. try {
  3. // check if the channel is still open as it could be closed in the mean time when the register
  4. // call was outside of the eventLoop
  5. if (!promise.setUncancellable() || !ensureOpen(promise)) {
  6. return;
  7. }
  8. boolean firstRegistration = neverRegistered;
  9. doRegister();
  10. neverRegistered = false;
  11. registered = true;
  12. // Ensure we call handlerAdded(...) before we actually notify the promise. This is needed as the
  13. // user may already fire events through the pipeline in the ChannelFutureListener.
  14. pipeline.invokeHandlerAddedIfNeeded();
  15. safeSetSuccess(promise);
  16. pipeline.fireChannelRegistered();
  17. // Only fire a channelActive if the channel has never been registered. This prevents firing
  18. // multiple channel actives if the channel is deregistered and re-registered.
  19. if (isActive()) {
  20. if (firstRegistration) {
  21. pipeline.fireChannelActive();
  22. } else if (config().isAutoRead()) {
  23. // This channel was registered before and autoRead() is set. This means we need to begin read
  24. // again so that we process inbound data.
  25. //
  26. // See https://github.com/netty/netty/issues/4805
  27. beginRead();
  28. }
  29. }
  30. } catch (Throwable t) {
  31. // Close the channel directly to avoid FD leak.
  32. closeForcibly();
  33. closeFuture.setClosed();
  34. safeSetFailure(promise, t);
  35. }
  36. }

AbstractNioChannel.doRegister

执行 doRegister 函数,其被定义在AbstractNioChannel

  1. protected void doRegister() throws Exception {
  2. boolean selected = false;
  3. for (;;) {
  4. try {
  5. selectionKey = javaChannel().register(eventLoop().unwrappedSelector(), 0, this);
  6. return;
  7. } catch (CancelledKeyException e) {
  8. if (!selected) {
  9. // Force the Selector to select now as the "canceled" SelectionKey may still be
  10. // cached and not removed because no Select.select(..) operation was called yet.
  11. eventLoop().selectNow();
  12. selected = true;
  13. } else {
  14. // We forced a select operation on the selector before but the SelectionKey is still cached
  15. // for whatever reason. JDK bug ?
  16. throw e;
  17. }
  18. }
  19. }
  20. }

其 javaChannel 由NioServerSocketChannel的构造器设置。

这里注册的是 0,表示不监听任何网络操作。

这里注册为 0 的原因有两点

  1. 该函数处于AbstractNioChannel,而 clientChannel 和 serverChannel 都是其子类,因此其不能设置特殊的操作
  2. 通过 SelectionKey 的 interestOps 可以修改其监听的网络操作

other

pipeline 实际上是一个AbstractChannelHandlerContext的双向链表,并且其默认的 head 和 tail 分别为HeadContext和TailContext。

headContext的 register 的实现为invokeHandlerAddedIfNeeded,即触发第一次注册事件,然而此时其实是不触发的,因为刚刚在之前已经触发过了,随后将在链表中传递注册事件

tailContext 是一个空操作。

初始化 server

除此之外,在初始化 server 时,还添加了一个 ChannelInitializer(在 init 函数中)

查看其实现

  1. @Override
  2. @SuppressWarnings("unchecked")
  3. public final void channelRegistered(ChannelHandlerContext ctx) throws Exception {
  4. // Normally this method will never be called as handlerAdded(...) should call initChannel(...) and remove
  5. // the handler.
  6. if (initChannel(ctx)) {
  7. // we called initChannel(...) so we need to call now pipeline.fireChannelRegistered() to ensure we not
  8. // miss an event.
  9. ctx.pipeline().fireChannelRegistered();
  10. // We are done with init the Channel, removing all the state for the Channel now.
  11. removeState(ctx);
  12. } else {
  13. // Called initChannel(...) before which is the expected behavior, so just forward the event.
  14. ctx.fireChannelRegistered();
  15. }
  16. }
  17. private boolean initChannel(ChannelHandlerContext ctx) throws Exception {
  18. if (initMap.add(ctx)) { // Guard against re-entrance.
  19. try {
  20. initChannel((C) ctx.channel());
  21. } catch (Throwable cause) {
  22. // Explicitly call exceptionCaught(...) as we removed the handler before calling initChannel(...).
  23. // We do so to prevent multiple calls to initChannel(...).
  24. exceptionCaught(ctx, cause);
  25. } finally {
  26. ChannelPipeline pipeline = ctx.pipeline();
  27. if (pipeline.context(this) != null) {
  28. pipeline.remove(this);
  29. }
  30. }
  31. return true;
  32. }
  33. return false;
  34. }

可以看到其在触发 register 事件触发时的默认操作为执行initChannel操作,随后结束移除 init 的上下文这个操作是自定义的,对于 server 来说这个操作为

  1. final ChannelPipeline pipeline = ch.pipeline();
  2. ChannelHandler handler = config.handler();
  3. if (handler != null) {
  4. pipeline.addLast(handler);
  5. }
  6. ch.eventLoop().execute(new Runnable() {
  7. @Override
  8. public void run() {
  9. pipeline.addLast(new ServerBootstrapAcceptor(
  10. ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
  11. }
  12. });

在这里又提交了一个 task 到 channel 绑定的 eventLoop 中,实际上当前正在进行的 register 也是一个 task,因此这里提交了下一个运行的任务。

需要注意的是这个提交的任务并不一定在下次执行,因为当前是 netty 线程执行,而用户线程可能是并行的。

随后调用 isActive,对于 Server 来说,其实现于NioServerSocketChannel

  1. public boolean isActive() {
  2. // As java.nio.ServerSocketChannel.isBound() will continue to return true even after the channel was closed
  3. // we will also need to check if it is open.
  4. return isOpen() && javaChannel().socket().isBound();
  5. }

随后触发 pipeline 的 active 操作,对于 head 来说在触发了链表的所有 active 操作后,若配置为 autoRead,则进行 channel的 read 操作

  1. private void readIfIsAutoRead() {
  2. if (channel.config().isAutoRead()) {
  3. channel.read();
  4. }
  5. }

随后若当前 channel 注册过,则触发beginRead 函数

此时将调用到AbstractNioChannel 的doBeginRead 操作,其将设置对 channel 添加一个 read 的interestOps。

  1. @Override
  2. protected void doBeginRead() throws Exception {
  3. // Channel.read() or ChannelHandlerContext.read() was called
  4. final SelectionKey selectionKey = this.selectionKey;
  5. if (!selectionKey.isValid()) {
  6. return;
  7. }
  8. readPending = true;
  9. final int interestOps = selectionKey.interestOps();
  10. if ((interestOps & readInterestOp) == 0) {
  11. selectionKey.interestOps(interestOps | readInterestOp);
  12. }
  13. }

然而对于NioServerSocketChannel来说,readInterestOps 为OP_ACCEPT

  1. public NioServerSocketChannel(ServerSocketChannel channel) {
  2. super(null, channel, SelectionKey.OP_ACCEPT);
  3. config = new NioServerSocketChannelConfig(this, javaChannel().socket());
  4. }

绑定

当触发并行时用户线程回到 bind 函数中

  1. private ChannelFuture doBind(final SocketAddress localAddress) {
  2. final ChannelFuture regFuture = initAndRegister();
  3. final Channel channel = regFuture.channel();
  4. if (regFuture.cause() != null) {
  5. return regFuture;
  6. }
  7. if (regFuture.isDone()) {
  8. // At this point we know that the registration was complete and successful.
  9. ChannelPromise promise = channel.newPromise();
  10. doBind0(regFuture, channel, localAddress, promise);
  11. return promise;
  12. } else {
  13. // Registration future is almost always fulfilled already, but just in case it's not.
  14. final PendingRegistrationPromise promise = new PendingRegistrationPromise(channel);
  15. regFuture.addListener(new ChannelFutureListener() {
  16. @Override
  17. public void operationComplete(ChannelFuture future) throws Exception {
  18. Throwable cause = future.cause();
  19. if (cause != null) {
  20. // Registration on the EventLoop failed so fail the ChannelPromise directly to not cause an
  21. // IllegalStateException once we try to access the EventLoop of the Channel.
  22. promise.setFailure(cause);
  23. } else {
  24. // Registration was successful, so set the correct executor to use.
  25. // See https://github.com/netty/netty/issues/2586
  26. promise.registered();
  27. doBind0(regFuture, channel, localAddress, promise);
  28. }
  29. }
  30. });
  31. return promise;
  32. }
  33. }
  1. 确定 initAndRegister 没有发生异常
  2. 判断 register 是否完成

注册完成时

若当前 register 已经完成了,则直接进行 bind0

  1. private static void doBind0(
  2. final ChannelFuture regFuture, final Channel channel,
  3. final SocketAddress localAddress, final ChannelPromise promise) {
  4. // This method is invoked before channelRegistered() is triggered. Give user handlers a chance to set up
  5. // the pipeline in its channelRegistered() implementation.
  6. channel.eventLoop().execute(new Runnable() {
  7. @Override
  8. public void run() {
  9. if (regFuture.isSuccess()) {
  10. channel.bind(localAddress, promise).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
  11. } else {
  12. promise.setFailure(regFuture.cause());
  13. }
  14. }
  15. });
  16. }

这个函数的目的是为了执行 bind,并且对 bind 事件添加失败关闭事件,要注意的是这里是给 channel 绑定的线程提交了一个任务,而非直接执行,bind 函数具体的操作暂且不提。

  1. ChannelFutureListener CLOSE_ON_FAILURE = new ChannelFutureListener() {
  2. @Override
  3. public void operationComplete(ChannelFuture future) {
  4. if (!future.isSuccess()) {
  5. future.channel().close();
  6. }
  7. }
  8. };

注册未完成时

给注册事件添加一个完成时事件

  1. final PendingRegistrationPromise promise = new PendingRegistrationPromise(channel);
  2. regFuture.addListener(new ChannelFutureListener() {
  3. @Override
  4. public void operationComplete(ChannelFuture future) throws Exception {
  5. Throwable cause = future.cause();
  6. if (cause != null) {
  7. // Registration on the EventLoop failed so fail the ChannelPromise directly to not cause an
  8. // IllegalStateException once we try to access the EventLoop of the Channel.
  9. promise.setFailure(cause);
  10. } else {
  11. // Registration was successful, so set the correct executor to use.
  12. // See https://github.com/netty/netty/issues/2586
  13. promise.registered();
  14. doBind0(regFuture, channel, localAddress, promise);
  15. }
  16. }
  17. });

最后仍然是执行 doBind0.

doBind0

bind 函数调用到AbstractChannel

  1. @Override
  2. public ChannelFuture bind(SocketAddress localAddress) {
  3. return pipeline.bind(localAddress);
  4. }

DefaultChannelPipeline 的 bind

  1. @Override
  2. public final ChannelFuture bind(SocketAddress localAddress) {
  3. return tail.bind(localAddress);
  4. }

TailContext 的 bind由AbstractChannelHandlerContext 实现

  1. public ChannelFuture bind(final SocketAddress localAddress, final ChannelPromise promise) {
  2. if (localAddress == null) {
  3. throw new NullPointerException("localAddress");
  4. }
  5. if (isNotValidPromise(promise, false)) {
  6. // cancelled
  7. return promise;
  8. }
  9. final AbstractChannelHandlerContext next = findContextOutbound(MASK_BIND);
  10. EventExecutor executor = next.executor();
  11. if (executor.inEventLoop()) {
  12. next.invokeBind(localAddress, promise);
  13. } else {
  14. safeExecute(executor, new Runnable() {
  15. @Override
  16. public void run() {
  17. next.invokeBind(localAddress, promise);
  18. }
  19. }, promise, null);
  20. }
  21. return promise;
  22. }

当前情况这里运行的线程为 eventLoop

  1. private void invokeBind(SocketAddress localAddress, ChannelPromise promise) {
  2. if (invokeHandler()) { //期望值为已完成 handler add 事件
  3. try {
  4. ((ChannelOutboundHandler) handler()).bind(this, localAddress, promise);
  5. } catch (Throwable t) {
  6. notifyOutboundHandlerException(t, promise);
  7. }
  8. } else { //递归回bind函数
  9. bind(localAddress, promise);
  10. }
  11. }

实际上由于 eventloop 是单线程的,因此执行到这里时,必定已经注册完成了,也就是

调用回 HeadContext

  1. @Override
  2. public void bind(
  3. ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) {
  4. unsafe.bind(localAddress, promise);
  5. }

由 AbstractUnsafe 实现

  1. @Override
  2. public final void bind(final SocketAddress localAddress, final ChannelPromise promise) {
  3. assertEventLoop();
  4. if (!promise.setUncancellable() || !ensureOpen(promise)) {
  5. return;
  6. }
  7. // See: https://github.com/netty/netty/issues/576
  8. if (Boolean.TRUE.equals(config().getOption(ChannelOption.SO_BROADCAST)) &&
  9. localAddress instanceof InetSocketAddress &&
  10. !((InetSocketAddress) localAddress).getAddress().isAnyLocalAddress() &&
  11. !PlatformDependent.isWindows() && !PlatformDependent.maybeSuperUser()) {
  12. // Warn a user about the fact that a non-root user can't receive a
  13. // broadcast packet on *nix if the socket is bound on non-wildcard address.
  14. logger.warn(
  15. "A non-root user can't receive a broadcast packet if the socket " +
  16. "is not bound to a wildcard address; binding to a non-wildcard " +
  17. "address (" + localAddress + ") anyway as requested.");
  18. }
  19. boolean wasActive = isActive();
  20. try {
  21. doBind(localAddress);
  22. } catch (Throwable t) {
  23. safeSetFailure(promise, t);
  24. closeIfClosed();
  25. return;
  26. }
  27. if (!wasActive && isActive()) {
  28. invokeLater(new Runnable() {
  29. @Override
  30. public void run() {
  31. pipeline.fireChannelActive();
  32. }
  33. });
  34. }
  35. safeSetSuccess(promise);
  36. }

doBind函数由 NioServerChannel 实现,这里是由 eventLoop 执行的

  1. @Override
  2. protected void doBind(SocketAddress localAddress) throws Exception {
  3. if (PlatformDependent.javaVersion() >= 7) {
  4. javaChannel().bind(localAddress, config.getBacklog());
  5. } else {
  6. javaChannel().socket().bind(localAddress, config.getBacklog());
  7. }
  8. }

随后若开始doBind前未 active,并且 bind 后active,则提交一个activefire任务到 eventloop 中。

至此服务端启动完成

发表评论

表情:
评论列表 (有 0 条评论,73人围观)

还没有评论,来说两句吧...

相关阅读