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    *   http://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.bootstrap;
17  
18  import io.netty.channel.Channel;
19  import io.netty.channel.ChannelFuture;
20  import io.netty.channel.ChannelFutureListener;
21  import io.netty.channel.ChannelOption;
22  import io.netty.channel.ChannelPipeline;
23  import io.netty.channel.ChannelPromise;
24  import io.netty.channel.EventLoop;
25  import io.netty.resolver.DefaultNameResolverGroup;
26  import io.netty.resolver.NameResolver;
27  import io.netty.resolver.NameResolverGroup;
28  import io.netty.util.AttributeKey;
29  import io.netty.util.concurrent.Future;
30  import io.netty.util.concurrent.FutureListener;
31  import io.netty.util.internal.logging.InternalLogger;
32  import io.netty.util.internal.logging.InternalLoggerFactory;
33  
34  import java.net.InetAddress;
35  import java.net.InetSocketAddress;
36  import java.net.SocketAddress;
37  import java.util.Map;
38  import java.util.Map.Entry;
39  
40  /**
41   * A {@link Bootstrap} that makes it easy to bootstrap a {@link Channel} to use
42   * for clients.
43   *
44   * <p>The {@link #bind()} methods are useful in combination with connectionless transports such as datagram (UDP).
45   * For regular TCP connections, please use the provided {@link #connect()} methods.</p>
46   */
47  public class Bootstrap extends AbstractBootstrap<Bootstrap, Channel> {
48  
49      private static final InternalLogger logger = InternalLoggerFactory.getInstance(Bootstrap.class);
50  
51      private static final NameResolverGroup<?> DEFAULT_RESOLVER = DefaultNameResolverGroup.INSTANCE;
52  
53      @SuppressWarnings("unchecked")
54      private volatile NameResolverGroup<SocketAddress> resolver = (NameResolverGroup<SocketAddress>) DEFAULT_RESOLVER;
55      private volatile SocketAddress remoteAddress;
56  
57      public Bootstrap() { }
58  
59      private Bootstrap(Bootstrap bootstrap) {
60          super(bootstrap);
61          resolver = bootstrap.resolver;
62          remoteAddress = bootstrap.remoteAddress;
63      }
64  
65      /**
66       * Sets the {@link NameResolver} which will resolve the address of the unresolved named address.
67       */
68      @SuppressWarnings("unchecked")
69      public Bootstrap resolver(NameResolverGroup<?> resolver) {
70          if (resolver == null) {
71              throw new NullPointerException("resolver");
72          }
73          this.resolver = (NameResolverGroup<SocketAddress>) resolver;
74          return this;
75      }
76  
77      /**
78       * The {@link SocketAddress} to connect to once the {@link #connect()} method
79       * is called.
80       */
81      public Bootstrap remoteAddress(SocketAddress remoteAddress) {
82          this.remoteAddress = remoteAddress;
83          return this;
84      }
85  
86      /**
87       * @see {@link #remoteAddress(SocketAddress)}
88       */
89      public Bootstrap remoteAddress(String inetHost, int inetPort) {
90          remoteAddress = InetSocketAddress.createUnresolved(inetHost, inetPort);
91          return this;
92      }
93  
94      /**
95       * @see {@link #remoteAddress(SocketAddress)}
96       */
97      public Bootstrap remoteAddress(InetAddress inetHost, int inetPort) {
98          remoteAddress = new InetSocketAddress(inetHost, inetPort);
99          return this;
100     }
101 
102     /**
103      * Connect a {@link Channel} to the remote peer.
104      */
105     public ChannelFuture connect() {
106         validate();
107         SocketAddress remoteAddress = this.remoteAddress;
108         if (remoteAddress == null) {
109             throw new IllegalStateException("remoteAddress not set");
110         }
111 
112         return doResolveAndConnect(remoteAddress, localAddress());
113     }
114 
115     /**
116      * Connect a {@link Channel} to the remote peer.
117      */
118     public ChannelFuture connect(String inetHost, int inetPort) {
119         return connect(InetSocketAddress.createUnresolved(inetHost, inetPort));
120     }
121 
122     /**
123      * Connect a {@link Channel} to the remote peer.
124      */
125     public ChannelFuture connect(InetAddress inetHost, int inetPort) {
126         return connect(new InetSocketAddress(inetHost, inetPort));
127     }
128 
129     /**
130      * Connect a {@link Channel} to the remote peer.
131      */
132     public ChannelFuture connect(SocketAddress remoteAddress) {
133         if (remoteAddress == null) {
134             throw new NullPointerException("remoteAddress");
135         }
136 
137         validate();
138         return doResolveAndConnect(remoteAddress, localAddress());
139     }
140 
141     /**
142      * Connect a {@link Channel} to the remote peer.
143      */
144     public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) {
145         if (remoteAddress == null) {
146             throw new NullPointerException("remoteAddress");
147         }
148         validate();
149         return doResolveAndConnect(remoteAddress, localAddress);
150     }
151 
152     /**
153      * @see {@link #connect()}
154      */
155     private ChannelFuture doResolveAndConnect(SocketAddress remoteAddress, final SocketAddress localAddress) {
156         final ChannelFuture regFuture = initAndRegister();
157         if (regFuture.cause() != null) {
158             return regFuture;
159         }
160 
161         final Channel channel = regFuture.channel();
162         final EventLoop eventLoop = channel.eventLoop();
163         final NameResolver<SocketAddress> resolver = this.resolver.getResolver(eventLoop);
164 
165         if (!resolver.isSupported(remoteAddress) || resolver.isResolved(remoteAddress)) {
166             // Resolver has no idea about what to do with the specified remote address or it's resolved already.
167             return doConnect(remoteAddress, localAddress, regFuture, channel.newPromise());
168         }
169 
170         final Future<SocketAddress> resolveFuture = resolver.resolve(remoteAddress);
171         final Throwable resolveFailureCause = resolveFuture.cause();
172 
173         if (resolveFailureCause != null) {
174             // Failed to resolve immediately
175             channel.close();
176             return channel.newFailedFuture(resolveFailureCause);
177         }
178 
179         if (resolveFuture.isDone()) {
180             // Succeeded to resolve immediately; cached? (or did a blocking lookup)
181             return doConnect(resolveFuture.getNow(), localAddress, regFuture, channel.newPromise());
182         }
183 
184         // Wait until the name resolution is finished.
185         final ChannelPromise connectPromise = channel.newPromise();
186         resolveFuture.addListener(new FutureListener<SocketAddress>() {
187             @Override
188             public void operationComplete(Future<SocketAddress> future) throws Exception {
189                 if (future.cause() != null) {
190                     channel.close();
191                     connectPromise.setFailure(future.cause());
192                 } else {
193                     doConnect(future.getNow(), localAddress, regFuture, connectPromise);
194                 }
195             }
196         });
197 
198         return connectPromise;
199     }
200 
201     private static ChannelFuture doConnect(
202             final SocketAddress remoteAddress, final SocketAddress localAddress,
203             final ChannelFuture regFuture, final ChannelPromise connectPromise) {
204         if (regFuture.isDone()) {
205             doConnect0(remoteAddress, localAddress, regFuture, connectPromise);
206         } else {
207             regFuture.addListener(new ChannelFutureListener() {
208                 @Override
209                 public void operationComplete(ChannelFuture future) throws Exception {
210                     doConnect0(remoteAddress, localAddress, regFuture, connectPromise);
211                 }
212             });
213         }
214 
215         return connectPromise;
216     }
217 
218     private static void doConnect0(
219             final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelFuture regFuture,
220             final ChannelPromise connectPromise) {
221 
222         // This method is invoked before channelRegistered() is triggered.  Give user handlers a chance to set up
223         // the pipeline in its channelRegistered() implementation.
224         final Channel channel = connectPromise.channel();
225         channel.eventLoop().execute(new Runnable() {
226             @Override
227             public void run() {
228                 if (regFuture.isSuccess()) {
229                     if (localAddress == null) {
230                         channel.connect(remoteAddress, connectPromise);
231                     } else {
232                         channel.connect(remoteAddress, localAddress, connectPromise);
233                     }
234                     connectPromise.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
235                 } else {
236                     connectPromise.setFailure(regFuture.cause());
237                 }
238             }
239         });
240     }
241 
242     @Override
243     @SuppressWarnings("unchecked")
244     void init(Channel channel) throws Exception {
245         ChannelPipeline p = channel.pipeline();
246         p.addLast(handler());
247 
248         final Map<ChannelOption<?>, Object> options = options();
249         synchronized (options) {
250             for (Entry<ChannelOption<?>, Object> e: options.entrySet()) {
251                 try {
252                     if (!channel.config().setOption((ChannelOption<Object>) e.getKey(), e.getValue())) {
253                         logger.warn("Unknown channel option: " + e);
254                     }
255                 } catch (Throwable t) {
256                     logger.warn("Failed to set a channel option: " + channel, t);
257                 }
258             }
259         }
260 
261         final Map<AttributeKey<?>, Object> attrs = attrs();
262         synchronized (attrs) {
263             for (Entry<AttributeKey<?>, Object> e: attrs.entrySet()) {
264                 channel.attr((AttributeKey<Object>) e.getKey()).set(e.getValue());
265             }
266         }
267     }
268 
269     @Override
270     public Bootstrap validate() {
271         super.validate();
272         if (handler() == null) {
273             throw new IllegalStateException("handler not set");
274         }
275         return this;
276     }
277 
278     @Override
279     @SuppressWarnings("CloneDoesntCallSuperClone")
280     public Bootstrap clone() {
281         return new Bootstrap(this);
282     }
283 
284     @Override
285     public String toString() {
286         if (remoteAddress == null) {
287             return super.toString();
288         }
289 
290         StringBuilder buf = new StringBuilder(super.toString());
291         buf.setLength(buf.length() - 1);
292 
293         return buf.append(", remoteAddress: ")
294                   .append(remoteAddress)
295                   .append(')')
296                   .toString();
297     }
298 }