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 = Collections.newSetFromMap(
60 new ConcurrentHashMap<ChannelHandlerContext, Boolean>());
61
62 /**
63 * This method will be called once the {@link Channel} was registered. After the method returns this instance
64 * will be removed from the {@link ChannelPipeline} of the {@link Channel}.
65 *
66 * @param ch the {@link Channel} which was registered.
67 * @throws Exception is thrown if an error occurs. In that case it will be handled by
68 * {@link #exceptionCaught(ChannelHandlerContext, Throwable)} which will by default close
69 * the {@link Channel}.
70 */
71 protected abstract void initChannel(C ch) throws Exception;
72
73 @Override
74 @SuppressWarnings("unchecked")
75 public final void channelRegistered(ChannelHandlerContext ctx) throws Exception {
76 // Normally this method will never be called as handlerAdded(...) should call initChannel(...) and remove
77 // the handler.
78 if (initChannel(ctx)) {
79 // we called initChannel(...) so we need to call now pipeline.fireChannelRegistered() to ensure we not
80 // miss an event.
81 ctx.pipeline().fireChannelRegistered();
82
83 // We are done with init the Channel, removing all the state for the Channel now.
84 removeState(ctx);
85 } else {
86 // Called initChannel(...) before which is the expected behavior, so just forward the event.
87 ctx.fireChannelRegistered();
88 }
89 }
90
91 /**
92 * Handle the {@link Throwable} by logging and closing the {@link Channel}. Sub-classes may override this.
93 */
94 @Override
95 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
96 if (logger.isWarnEnabled()) {
97 logger.warn("Failed to initialize a channel. Closing: " + ctx.channel(), cause);
98 }
99 ctx.close();
100 }
101
102 /**
103 * {@inheritDoc} If override this method ensure you call super!
104 */
105 @Override
106 public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
107 if (ctx.channel().isRegistered()) {
108 // This should always be true with our current DefaultChannelPipeline implementation.
109 // The good thing about calling initChannel(...) in handlerAdded(...) is that there will be no ordering
110 // surprises if a ChannelInitializer will add another ChannelInitializer. This is as all handlers
111 // will be added in the expected order.
112 if (initChannel(ctx)) {
113
114 // We are done with init the Channel, removing the initializer now.
115 removeState(ctx);
116 }
117 }
118 }
119
120 @Override
121 public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
122 initMap.remove(ctx);
123 }
124
125 @SuppressWarnings("unchecked")
126 private boolean initChannel(ChannelHandlerContext ctx) throws Exception {
127 if (initMap.add(ctx)) { // Guard against re-entrance.
128 try {
129 initChannel((C) ctx.channel());
130 } catch (Throwable cause) {
131 // Explicitly call exceptionCaught(...) as we removed the handler before calling initChannel(...).
132 // We do so to prevent multiple calls to initChannel(...).
133 exceptionCaught(ctx, cause);
134 } finally {
135 if (!ctx.isRemoved()) {
136 ctx.pipeline().remove(this);
137 }
138 }
139 return true;
140 }
141 return false;
142 }
143
144 private void removeState(final ChannelHandlerContext ctx) {
145 // The removal may happen in an async fashion if the EventExecutor we use does something funky.
146 if (ctx.isRemoved()) {
147 initMap.remove(ctx);
148 } else {
149 // The context is not removed yet which is most likely the case because a custom EventExecutor is used.
150 // Let's schedule it on the EventExecutor to give it some more time to be completed in case it is offloaded.
151 ctx.executor().execute(new Runnable() {
152 @Override
153 public void run() {
154 initMap.remove(ctx);
155 }
156 });
157 }
158 }
159 }