View Javadoc

1   /*
2    *  Licensed to the Apache Software Foundation (ASF) under one
3    *  or more contributor license agreements.  See the NOTICE file
4    *  distributed with this work for additional information
5    *  regarding copyright ownership.  The ASF licenses this file
6    *  to you under the Apache License, Version 2.0 (the
7    *  "License"); you may not use this file except in compliance
8    *  with the License.  You may obtain a copy of the License at
9    *  
10   *    http://www.apache.org/licenses/LICENSE-2.0
11   *  
12   *  Unless required by applicable law or agreed to in writing,
13   *  software distributed under the License is distributed on an
14   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   *  KIND, either express or implied.  See the License for the
16   *  specific language governing permissions and limitations
17   *  under the License. 
18   *  
19   */
20  package org.apache.mina.transport.socket.nio;
21  
22  import java.io.IOException;
23  import java.net.ConnectException;
24  import java.net.InetSocketAddress;
25  import java.net.SocketAddress;
26  import java.nio.channels.SelectionKey;
27  import java.nio.channels.Selector;
28  import java.nio.channels.SocketChannel;
29  import java.util.Iterator;
30  import java.util.Set;
31  
32  import org.apache.mina.common.ConnectFuture;
33  import org.apache.mina.common.ExceptionMonitor;
34  import org.apache.mina.common.IoConnector;
35  import org.apache.mina.common.IoConnectorConfig;
36  import org.apache.mina.common.IoHandler;
37  import org.apache.mina.common.IoServiceConfig;
38  import org.apache.mina.common.support.AbstractIoFilterChain;
39  import org.apache.mina.common.support.BaseIoConnector;
40  import org.apache.mina.common.support.DefaultConnectFuture;
41  import org.apache.mina.util.Queue;
42  import org.apache.mina.util.NewThreadExecutor;
43  import org.apache.mina.util.NamePreservingRunnable;
44  import edu.emory.mathcs.backport.java.util.concurrent.Executor;
45  
46  /**
47   * {@link IoConnector} for socket transport (TCP/IP).
48   *
49   * @author The Apache Directory Project (mina-dev@directory.apache.org)
50   * @version $Rev: 389042 $, $Date: 2006-03-27 07:49:41Z $
51   */
52  public class SocketConnector extends BaseIoConnector {
53      /**
54       * @noinspection StaticNonFinalField
55       */
56      private static volatile int nextId = 0;
57  
58      private final Object lock = new Object();
59  
60      private final int id = nextId++;
61  
62      private final String threadName = "SocketConnector-" + id;
63  
64      private SocketConnectorConfig defaultConfig = new SocketConnectorConfig();
65  
66      private final Queue connectQueue = new Queue();
67  
68      private final SocketIoProcessor[] ioProcessors;
69  
70      private final int processorCount;
71  
72      private final Executor executor;
73  
74      /**
75       * @noinspection FieldAccessedSynchronizedAndUnsynchronized
76       */
77      private Selector selector;
78  
79      private Worker worker;
80  
81      private int processorDistributor = 0;
82  
83      private int workerTimeout = 60; // 1 min.
84  
85      /**
86       * Create a connector with a single processing thread using a NewThreadExecutor 
87       */
88      public SocketConnector() {
89          this(1, new NewThreadExecutor());
90      }
91  
92      /**
93       * Create a connector with the desired number of processing threads
94       *
95       * @param processorCount Number of processing threads
96       * @param executor Executor to use for launching threads
97       */
98      public SocketConnector(int processorCount, Executor executor) {
99          if (processorCount < 1) {
100             throw new IllegalArgumentException(
101                     "Must have at least one processor");
102         }
103 
104         this.executor = executor;
105         this.processorCount = processorCount;
106         ioProcessors = new SocketIoProcessor[processorCount];
107 
108         for (int i = 0; i < processorCount; i++) {
109             ioProcessors[i] = new SocketIoProcessor(
110                     "SocketConnectorIoProcessor-" + id + "." + i, executor);
111         }
112     }
113 
114     /**
115      * How many seconds to keep the connection thread alive between connection requests
116      *
117      * @return the number of seconds to keep connection thread alive.
118      *         0 means that the connection thread will terminate immediately
119      *         when there's no connection to make.
120      */
121     public int getWorkerTimeout() {
122         return workerTimeout;
123     }
124 
125     /**
126      * Set how many seconds the connection worker thread should remain alive once idle before terminating itself.
127      *
128      * @param workerTimeout the number of seconds to keep thread alive.
129      *                      Must be >=0.  If 0 is specified, the connection
130      *                      worker thread will terminate immediately when
131      *                      there's no connection to make.
132      */
133     public void setWorkerTimeout(int workerTimeout) {
134         if (workerTimeout < 0) {
135             throw new IllegalArgumentException("Must be >= 0");
136         }
137         this.workerTimeout = workerTimeout;
138     }
139 
140     public ConnectFuture connect(SocketAddress address, IoHandler handler,
141             IoServiceConfig config) {
142         return connect(address, null, handler, config);
143     }
144 
145     public ConnectFuture connect(SocketAddress address,
146             SocketAddress localAddress, IoHandler handler,
147             IoServiceConfig config) {
148         if (address == null)
149             throw new NullPointerException("address");
150         if (handler == null)
151             throw new NullPointerException("handler");
152 
153         if (!(address instanceof InetSocketAddress))
154             throw new IllegalArgumentException("Unexpected address type: "
155                     + address.getClass());
156 
157         if (localAddress != null
158                 && !(localAddress instanceof InetSocketAddress))
159             throw new IllegalArgumentException(
160                     "Unexpected local address type: " + localAddress.getClass());
161 
162         if (config == null) {
163             config = getDefaultConfig();
164         }
165 
166         SocketChannel ch = null;
167         boolean success = false;
168         try {
169             ch = SocketChannel.open();
170             ch.socket().setReuseAddress(true);
171             if (localAddress != null) {
172                 ch.socket().bind(localAddress);
173             }
174 
175             ch.configureBlocking(false);
176 
177             if (ch.connect(address)) {
178                 DefaultConnectFuture future = new DefaultConnectFuture();
179                 newSession(ch, handler, config, future);
180                 success = true;
181                 return future;
182             }
183 
184             success = true;
185         } catch (IOException e) {
186             return DefaultConnectFuture.newFailedFuture(e);
187         } finally {
188             if (!success && ch != null) {
189                 try {
190                     ch.close();
191                 } catch (IOException e) {
192                     ExceptionMonitor.getInstance().exceptionCaught(e);
193                 }
194             }
195         }
196 
197         ConnectionRequest request = new ConnectionRequest(ch, handler, config);
198         synchronized (lock) {
199             try {
200                 startupWorker();
201             } catch (IOException e) {
202                 try {
203                     ch.close();
204                 } catch (IOException e2) {
205                     ExceptionMonitor.getInstance().exceptionCaught(e2);
206                 }
207     
208                 return DefaultConnectFuture.newFailedFuture(e);
209             }
210     
211             synchronized (connectQueue) {
212                 connectQueue.push(request);
213             }
214             selector.wakeup();
215         }
216 
217         return request;
218     }
219 
220     public IoServiceConfig getDefaultConfig() {
221         return defaultConfig;
222     }
223 
224     /**
225      * Sets the config this connector will use by default.
226      * 
227      * @param defaultConfig the default config.
228      * @throws NullPointerException if the specified value is <code>null</code>.
229      */
230     public void setDefaultConfig(SocketConnectorConfig defaultConfig) {
231         if (defaultConfig == null) {
232             throw new NullPointerException("defaultConfig");
233         }
234         this.defaultConfig = defaultConfig;
235     }
236     
237     private Selector getSelector() {
238         synchronized (lock) {
239             return this.selector;
240         }
241     }
242 
243     private void startupWorker() throws IOException {
244         synchronized (lock) {
245             if (worker == null) {
246                 selector = Selector.open();
247                 worker = new Worker();
248                 executor.execute(new NamePreservingRunnable(worker));
249             }
250         }
251     }
252 
253     private void registerNew() {
254         if (connectQueue.isEmpty())
255             return;
256 
257         Selector selector = getSelector();
258         for (;;) {
259             ConnectionRequest req;
260             synchronized (connectQueue) {
261                 req = (ConnectionRequest) connectQueue.pop();
262             }
263 
264             if (req == null)
265                 break;
266 
267             SocketChannel ch = req.channel;
268             try {
269                 ch.register(selector, SelectionKey.OP_CONNECT, req);
270             } catch (IOException e) {
271                 req.setException(e);
272             }
273         }
274     }
275 
276     private void processSessions(Set keys) {
277         Iterator it = keys.iterator();
278 
279         while (it.hasNext()) {
280             SelectionKey key = (SelectionKey) it.next();
281 
282             if (!key.isConnectable())
283                 continue;
284 
285             SocketChannel ch = (SocketChannel) key.channel();
286             ConnectionRequest entry = (ConnectionRequest) key.attachment();
287 
288             boolean success = false;
289             try {
290                 ch.finishConnect();
291                 newSession(ch, entry.handler, entry.config, entry);
292                 success = true;
293             } catch (Throwable e) {
294                 entry.setException(e);
295             } finally {
296                 key.cancel();
297                 if (!success) {
298                     try {
299                         ch.close();
300                     } catch (IOException e) {
301                         ExceptionMonitor.getInstance().exceptionCaught(e);
302                     }
303                 }
304             }
305         }
306 
307         keys.clear();
308     }
309 
310     private void processTimedOutSessions(Set keys) {
311         long currentTime = System.currentTimeMillis();
312         Iterator it = keys.iterator();
313 
314         while (it.hasNext()) {
315             SelectionKey key = (SelectionKey) it.next();
316 
317             if (!key.isValid())
318                 continue;
319 
320             ConnectionRequest entry = (ConnectionRequest) key.attachment();
321 
322             if (currentTime >= entry.deadline) {
323                 entry.setException(new ConnectException());
324                 try {
325                     key.channel().close();
326                 } catch (IOException e) {
327                     ExceptionMonitor.getInstance().exceptionCaught(e);
328                 } finally {
329                     key.cancel();
330                 }
331             }
332         }
333     }
334 
335     private void newSession(SocketChannel ch, IoHandler handler,
336             IoServiceConfig config, ConnectFuture connectFuture)
337             throws IOException {
338         SocketSessionImpl session = new SocketSessionImpl(this,
339                 nextProcessor(), getListeners(), config, ch, handler, ch
340                         .socket().getRemoteSocketAddress());
341         try {
342             getFilterChainBuilder().buildFilterChain(session.getFilterChain());
343             config.getFilterChainBuilder().buildFilterChain(
344                     session.getFilterChain());
345             config.getThreadModel().buildFilterChain(session.getFilterChain());
346         } catch (Throwable e) {
347             throw (IOException) new IOException("Failed to create a session.")
348                     .initCause(e);
349         }
350 
351         // Set the ConnectFuture of the specified session, which will be
352         // removed and notified by AbstractIoFilterChain eventually.
353         session.setAttribute(AbstractIoFilterChain.CONNECT_FUTURE,
354                 connectFuture);
355 
356         // Forward the remaining process to the SocketIoProcessor.
357         session.getIoProcessor().addNew(session);
358     }
359 
360     private SocketIoProcessor nextProcessor() {
361         if (this.processorDistributor == Integer.MAX_VALUE) {
362             this.processorDistributor = Integer.MAX_VALUE % this.processorCount;
363         }
364 
365         return ioProcessors[processorDistributor++ % processorCount];
366     }
367 
368     private class Worker implements Runnable {
369         private long lastActive = System.currentTimeMillis();
370 
371         public void run() {
372             Thread.currentThread().setName(SocketConnector.this.threadName);
373 
374             Selector selector = getSelector();
375             for (;;) {
376                 try {
377                     int nKeys = selector.select(1000);
378 
379                     registerNew();
380 
381                     if (nKeys > 0) {
382                         processSessions(selector.selectedKeys());
383                     }
384 
385                     processTimedOutSessions(selector.keys());
386 
387                     if (selector.keys().isEmpty()) {
388                         if (System.currentTimeMillis() - lastActive > workerTimeout * 1000L) {
389                             synchronized (lock) {
390                                 if (selector.keys().isEmpty()
391                                         && connectQueue.isEmpty()) {
392                                     worker = null;
393                                     try {
394                                         selector.close();
395                                     } catch (IOException e) {
396                                         ExceptionMonitor.getInstance()
397                                                 .exceptionCaught(e);
398                                     } finally {
399                                         SocketConnector.this.selector = null;
400                                     }
401                                     break;
402                                 }
403                             }
404                         }
405                     } else {
406                         lastActive = System.currentTimeMillis();
407                     }
408                 } catch (IOException e) {
409                     ExceptionMonitor.getInstance().exceptionCaught(e);
410 
411                     try {
412                         Thread.sleep(1000);
413                     } catch (InterruptedException e1) {
414                         ExceptionMonitor.getInstance().exceptionCaught(e1);
415                     }
416                 }
417             }
418         }
419     }
420 
421     private class ConnectionRequest extends DefaultConnectFuture {
422         private final SocketChannel channel;
423 
424         private final long deadline;
425 
426         private final IoHandler handler;
427 
428         private final IoServiceConfig config;
429 
430         private ConnectionRequest(SocketChannel channel, IoHandler handler,
431                 IoServiceConfig config) {
432             this.channel = channel;
433             long timeout;
434             if (config instanceof IoConnectorConfig) {
435                 timeout = ((IoConnectorConfig) config)
436                         .getConnectTimeoutMillis();
437             } else {
438                 timeout = ((IoConnectorConfig) getDefaultConfig())
439                         .getConnectTimeoutMillis();
440             }
441             this.deadline = System.currentTimeMillis() + timeout;
442             this.handler = handler;
443             this.config = config;
444         }
445     }
446 }