View Javadoc
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.channel;
17  
18  import io.netty.bootstrap.Bootstrap;
19  import io.netty.bootstrap.ServerBootstrap;
20  import io.netty.channel.ChannelHandler.Sharable;
21  import io.netty.util.internal.logging.InternalLogger;
22  import io.netty.util.internal.logging.InternalLoggerFactory;
23  
24  import java.util.Collections;
25  import java.util.Set;
26  import java.util.concurrent.ConcurrentHashMap;
27  
28  /**
29   * A special {@link ChannelInboundHandler} which offers an easy way to initialize a {@link Channel} once it was
30   * registered to its {@link EventLoop}.
31   *
32   * Implementations are most often used in the context of {@link Bootstrap#handler(ChannelHandler)} ,
33   * {@link ServerBootstrap#handler(ChannelHandler)} and {@link ServerBootstrap#childHandler(ChannelHandler)} to
34   * setup the {@link ChannelPipeline} of a {@link Channel}.
35   *
36   * <pre>
37   *
38   * public class MyChannelInitializer extends {@link ChannelInitializer} {
39   *     public void initChannel({@link Channel} channel) {
40   *         channel.pipeline().addLast("myHandler", new MyHandler());
41   *     }
42   * }
43   *
44   * {@link ServerBootstrap} bootstrap = ...;
45   * ...
46   * bootstrap.childHandler(new MyChannelInitializer());
47   * ...
48   * </pre>
49   * Be aware that this class is marked as {@link Sharable} and so the implementation must be safe to be re-used.
50   *
51   * @param <C>   A sub-type of {@link Channel}
52   */
53  @Sharable
54  public abstract class ChannelInitializer<C extends Channel> extends ChannelInboundHandlerAdapter {
55  
56      private static final InternalLogger logger = InternalLoggerFactory.getInstance(ChannelInitializer.class);
57      // We use a Set as a ChannelInitializer is usually shared between all Channels in a Bootstrap /
58      // ServerBootstrap. This way we can reduce the memory usage compared to use Attributes.
59      private final Set<ChannelHandlerContext> initMap = ConcurrentHashMap.newKeySet();
60  
61      /**
62       * This method will be called once the {@link Channel} was registered. After the method returns this instance
63       * will be removed from the {@link ChannelPipeline} of the {@link Channel}.
64       *
65       * @param ch            the {@link Channel} which was registered.
66       * @throws Exception    is thrown if an error occurs. In that case it will be handled by
67       *                      {@link #exceptionCaught(ChannelHandlerContext, Throwable)} which will by default close
68       *                      the {@link Channel}.
69       */
70      protected abstract void initChannel(C ch) throws Exception;
71  
72      @Override
73      @SuppressWarnings("unchecked")
74      public final void channelRegistered(ChannelHandlerContext ctx) throws Exception {
75          // Normally this method will never be called as handlerAdded(...) should call initChannel(...) and remove
76          // the handler.
77          if (initChannel(ctx)) {
78              // we called initChannel(...) so we need to call now pipeline.fireChannelRegistered() to ensure we not
79              // miss an event.
80              ctx.pipeline().fireChannelRegistered();
81  
82              // We are done with init the Channel, removing all the state for the Channel now.
83              removeState(ctx);
84          } else {
85              // Called initChannel(...) before which is the expected behavior, so just forward the event.
86              ctx.fireChannelRegistered();
87          }
88      }
89  
90      /**
91       * Handle the {@link Throwable} by logging and closing the {@link Channel}. Sub-classes may override this.
92       */
93      @Override
94      public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
95          if (logger.isWarnEnabled()) {
96              logger.warn("Failed to initialize a channel. Closing: " + ctx.channel(), cause);
97          }
98          ctx.close();
99      }
100 
101     /**
102      * {@inheritDoc} If override this method ensure you call super!
103      */
104     @Override
105     public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
106         if (ctx.channel().isRegistered()) {
107             // This should always be true with our current DefaultChannelPipeline implementation.
108             // The good thing about calling initChannel(...) in handlerAdded(...) is that there will be no ordering
109             // surprises if a ChannelInitializer will add another ChannelInitializer. This is as all handlers
110             // will be added in the expected order.
111             if (initChannel(ctx)) {
112 
113                 // We are done with init the Channel, removing the initializer now.
114                 removeState(ctx);
115             }
116         }
117     }
118 
119     @Override
120     public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
121         initMap.remove(ctx);
122     }
123 
124     @SuppressWarnings("unchecked")
125     private boolean initChannel(ChannelHandlerContext ctx) throws Exception {
126         if (initMap.add(ctx)) { // Guard against re-entrance.
127             try {
128                 initChannel((C) ctx.channel());
129             } catch (Throwable cause) {
130                 // Explicitly call exceptionCaught(...) as we removed the handler before calling initChannel(...).
131                 // We do so to prevent multiple calls to initChannel(...).
132                 exceptionCaught(ctx, cause);
133             } finally {
134                 if (!ctx.isRemoved()) {
135                     ctx.pipeline().remove(this);
136                 }
137             }
138             return true;
139         }
140         return false;
141     }
142 
143     private void removeState(final ChannelHandlerContext ctx) {
144         // The removal may happen in an async fashion if the EventExecutor we use does something funky.
145         if (ctx.isRemoved()) {
146             initMap.remove(ctx);
147         } else {
148             // The context is not removed yet which is most likely the case because a custom EventExecutor is used.
149             // Let's schedule it on the EventExecutor to give it some more time to be completed in case it is offloaded.
150             ctx.executor().execute(new Runnable() {
151                 @Override
152                 public void run() {
153                     initMap.remove(ctx);
154                 }
155             });
156         }
157     }
158 }