View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.server;
20  
21  import java.io.IOException;
22  import java.net.InetSocketAddress;
23  import java.net.ServerSocket;
24  import java.net.Socket;
25  import java.net.SocketException;
26  import java.nio.channels.Channel;
27  import java.nio.channels.SelectionKey;
28  import java.nio.channels.Selector;
29  import java.nio.channels.ServerSocketChannel;
30  import java.nio.channels.SocketChannel;
31  import java.util.concurrent.Executor;
32  import java.util.concurrent.Future;
33  
34  import org.eclipse.jetty.io.ByteBufferPool;
35  import org.eclipse.jetty.io.Connection;
36  import org.eclipse.jetty.io.EndPoint;
37  import org.eclipse.jetty.io.SelectChannelEndPoint;
38  import org.eclipse.jetty.io.SelectorManager;
39  import org.eclipse.jetty.io.SelectorManager.ManagedSelector;
40  import org.eclipse.jetty.util.Callback;
41  import org.eclipse.jetty.util.annotation.ManagedAttribute;
42  import org.eclipse.jetty.util.annotation.ManagedObject;
43  import org.eclipse.jetty.util.annotation.Name;
44  import org.eclipse.jetty.util.ssl.SslContextFactory;
45  import org.eclipse.jetty.util.thread.Scheduler;
46  
47  /**
48   * This {@link Connector} implementation is the primary connector for the
49   * Jetty server over TCP/IP.  By the use of various {@link ConnectionFactory} instances it is able
50   * to accept connections for HTTP, SPDY and WebSocket, either directly or over SSL.
51   * <p>
52   * The connector is a fully asynchronous NIO based implementation that by default will
53   * use all the commons services (eg {@link Executor}, {@link Scheduler})  of the
54   * passed {@link Server} instance, but all services may also be constructor injected
55   * into the connector so that it may operate with dedicated or otherwise shared services.
56   * <p>
57   * <h2>Connection Factories</h2>
58   * Various convenience constructors are provided to assist with common configurations of
59   * ConnectionFactories, whose generic use is described in {@link AbstractConnector}.
60   * If no connection factories are passed, then the connector will
61   * default to use a {@link HttpConnectionFactory}.  If an non null {@link SslContextFactory}
62   * instance is passed, then this used to instantiate a {@link SslConnectionFactory} which is
63   * prepended to the other passed or default factories.
64   * <p>
65   * <h2>Selectors</h2>
66   * The connector will use the {@link Executor} service to execute a number of Selector Tasks,
67   * which are implemented to each use a NIO {@link Selector} instance to asynchronously
68   * schedule a set of accepted connections.  It is the selector thread that will call the
69   * {@link Callback} instances passed in the {@link EndPoint#fillInterested(Callback)} or
70   * {@link EndPoint#write(Object, Callback, java.nio.ByteBuffer...)} methods.  It is expected
71   * that these callbacks may do some non-blocking IO work, but will always dispatch to the
72   * {@link Executor} service any blocking, long running or application tasks.
73   * <p>
74   * The default number of selectors is equal to the number of processors available to the JVM,
75   * which should allow optimal performance even if all the connections used are performing
76   * significant non-blocking work in the callback tasks.
77   *
78   */
79  @ManagedObject("HTTP connector using NIO ByteChannels and Selectors")
80  public class ServerConnector extends AbstractNetworkConnector
81  {
82      private final SelectorManager _manager;
83      private volatile ServerSocketChannel _acceptChannel;
84      private volatile boolean _inheritChannel = false;
85      private volatile int _localPort = -1;
86      private volatile int _acceptQueueSize = 0;
87      private volatile boolean _reuseAddress = true;
88      private volatile int _lingerTime = -1;
89  
90  
91      /* ------------------------------------------------------------ */
92      /** HTTP Server Connection.
93       * <p>Construct a ServerConnector with a private instance of {@link HttpConnectionFactory} as the only factory.</p>
94       * @param server The {@link Server} this connector will accept connection for. 
95       */
96      public ServerConnector(
97          @Name("server") Server server)
98      {
99          this(server,null,null,null,0,0,new HttpConnectionFactory());
100     }
101     
102     /* ------------------------------------------------------------ */
103     /** HTTP Server Connection.
104      * <p>Construct a ServerConnector with a private instance of {@link HttpConnectionFactory} as the only factory.</p>
105      * @param server The {@link Server} this connector will accept connection for. 
106      * @param acceptors 
107      *          the number of acceptor threads to use, or 0 for a default value. Acceptors accept new TCP/IP connections.
108      * @param selectors
109      *          the number of selector threads, or 0 for a default value. Selectors notice and schedule established connection that can make IO progress.
110      */
111     public ServerConnector(
112         @Name("server") Server server,
113         @Name("acceptors") int acceptors,
114         @Name("selectors") int selectors)
115     {
116         this(server,null,null,null,acceptors,selectors,new HttpConnectionFactory());
117     }
118 
119     /* ------------------------------------------------------------ */
120     /** Generic Server Connection with default configuration.
121      * <p>Construct a Server Connector with the passed Connection factories.</p>
122      * @param server The {@link Server} this connector will accept connection for. 
123      * @param factories Zero or more {@link ConnectionFactory} instances used to create and configure connections.
124      */
125     public ServerConnector(
126         @Name("server") Server server,
127         @Name("factories") ConnectionFactory... factories)
128     {
129         this(server,null,null,null,0,0,factories);
130     }
131 
132     /* ------------------------------------------------------------ */
133     /** HTTP Server Connection.
134      * <p>Construct a ServerConnector with a private instance of {@link HttpConnectionFactory} as the primary protocol</p>.
135      * @param server The {@link Server} this connector will accept connection for. 
136      * @param sslContextFactory If non null, then a {@link SslConnectionFactory} is instantiated and prepended to the 
137      * list of HTTP Connection Factory.
138      */
139     public ServerConnector(
140         @Name("server") Server server,
141         @Name("sslContextFactory") SslContextFactory sslContextFactory)
142     {
143         this(server,null,null,null,0,0,AbstractConnectionFactory.getFactories(sslContextFactory,new HttpConnectionFactory()));
144     }
145 
146     /* ------------------------------------------------------------ */
147     /** HTTP Server Connection.
148      * <p>Construct a ServerConnector with a private instance of {@link HttpConnectionFactory} as the primary protocol</p>.
149      * @param server The {@link Server} this connector will accept connection for. 
150      * @param sslContextFactory If non null, then a {@link SslConnectionFactory} is instantiated and prepended to the 
151      * list of HTTP Connection Factory.
152      * @param acceptors 
153      *          the number of acceptor threads to use, or 0 for a default value. Acceptors accept new TCP/IP connections.
154      * @param selectors
155      *          the number of selector threads, or 0 for a default value. Selectors notice and schedule established connection that can make IO progress.
156      */
157     public ServerConnector(
158         @Name("server") Server server,
159         @Name("acceptors") int acceptors,
160         @Name("selectors") int selectors,
161         @Name("sslContextFactory") SslContextFactory sslContextFactory)
162     {
163         this(server,null,null,null,acceptors,selectors,AbstractConnectionFactory.getFactories(sslContextFactory,new HttpConnectionFactory()));
164     }
165 
166     /* ------------------------------------------------------------ */
167     /** Generic SSL Server Connection.
168      * @param server The {@link Server} this connector will accept connection for. 
169      * @param sslContextFactory If non null, then a {@link SslConnectionFactory} is instantiated and prepended to the 
170      * list of ConnectionFactories, with the first factory being the default protocol for the SslConnectionFactory.
171      * @param factories Zero or more {@link ConnectionFactory} instances used to create and configure connections.
172      */
173     public ServerConnector(
174         @Name("server") Server server,
175         @Name("sslContextFactory") SslContextFactory sslContextFactory,
176         @Name("factories") ConnectionFactory... factories)
177     {
178         this(server,null,null,null,0,0,AbstractConnectionFactory.getFactories(sslContextFactory,factories));
179     }
180 
181     /** Generic Server Connection.
182      * @param server    
183      *          The server this connector will be accept connection for.  
184      * @param executor  
185      *          An executor used to run tasks for handling requests, acceptors and selectors. I
186      *          If null then use the servers executor
187      * @param scheduler 
188      *          A scheduler used to schedule timeouts. If null then use the servers scheduler
189      * @param bufferPool
190      *          A ByteBuffer pool used to allocate buffers.  If null then create a private pool with default configuration.
191      * @param acceptors 
192      *          the number of acceptor threads to use, or 0 for a default value. Acceptors accept new TCP/IP connections.
193      * @param selectors
194      *          the number of selector threads, or 0 for a default value. Selectors notice and schedule established connection that can make IO progress.
195      * @param factories 
196      *          Zero or more {@link ConnectionFactory} instances used to create and configure connections.
197      */
198     public ServerConnector(
199         @Name("server") Server server,
200         @Name("executor") Executor executor,
201         @Name("scheduler") Scheduler scheduler,
202         @Name("bufferPool") ByteBufferPool bufferPool,
203         @Name("acceptors") int acceptors,
204         @Name("selectors") int selectors,
205         @Name("factories") ConnectionFactory... factories)
206     {
207         super(server,executor,scheduler,bufferPool,acceptors,factories);
208         _manager = new ServerConnectorManager(getExecutor(), getScheduler(), selectors > 0 ? selectors : Runtime.getRuntime().availableProcessors());
209         addBean(_manager, true);
210     }
211 
212     @Override
213     public boolean isOpen()
214     {
215         ServerSocketChannel channel = _acceptChannel;
216         return channel!=null && channel.isOpen();
217     }
218 
219     /**
220      * @return whether this connector uses a channel inherited from the JVM.
221      * @see System#inheritedChannel()
222      */
223     public boolean isInheritChannel()
224     {
225         return _inheritChannel;
226     }
227 
228     /**
229      * <p>Sets whether this connector uses a channel inherited from the JVM.</p>
230      * <p>If true, the connector first tries to inherit from a channel provided by the system.
231      * If there is no inherited channel available, or if the inherited channel is not usable,
232      * then it will fall back using {@link ServerSocketChannel}.</p>
233      * <p>Use it with xinetd/inetd, to launch an instance of Jetty on demand. The port
234      * used to access pages on the Jetty instance is the same as the port used to
235      * launch Jetty.</p>
236      *
237      * @param inheritChannel whether this connector uses a channel inherited from the JVM.
238      */
239     public void setInheritChannel(boolean inheritChannel)
240     {
241         _inheritChannel = inheritChannel;
242     }
243 
244     @Override
245     public void open() throws IOException
246     {
247         if (_acceptChannel == null)
248         {
249             ServerSocketChannel serverChannel = null;
250             if (isInheritChannel())
251             {
252                 Channel channel = System.inheritedChannel();
253                 if (channel instanceof ServerSocketChannel)
254                     serverChannel = (ServerSocketChannel)channel;
255                 else
256                     LOG.warn("Unable to use System.inheritedChannel() [{}]. Trying a new ServerSocketChannel at {}:{}", channel, getHost(), getPort());
257             }
258 
259             if (serverChannel == null)
260             {
261                 serverChannel = ServerSocketChannel.open();
262 
263                 InetSocketAddress bindAddress = getHost() == null ? new InetSocketAddress(getPort()) : new InetSocketAddress(getHost(), getPort());
264                 serverChannel.socket().bind(bindAddress, getAcceptQueueSize());
265                 serverChannel.socket().setReuseAddress(getReuseAddress());
266 
267                 _localPort = serverChannel.socket().getLocalPort();
268                 if (_localPort <= 0)
269                     throw new IOException("Server channel not bound");
270 
271                 addBean(serverChannel);
272             }
273 
274             serverChannel.configureBlocking(true);
275             addBean(serverChannel);
276 
277             _acceptChannel = serverChannel;
278         }
279     }
280 
281     @Override
282     public Future<Void> shutdown()
283     {
284         // TODO shutdown all the connections
285         return super.shutdown();
286     }
287 
288     @Override
289     public void close()
290     {
291         ServerSocketChannel serverChannel = _acceptChannel;
292         _acceptChannel = null;
293 
294         if (serverChannel != null)
295         {
296             removeBean(serverChannel);
297 
298             // If the interrupt did not close it, we should close it
299             if (serverChannel.isOpen())
300             {
301                 try
302                 {
303                     serverChannel.close();
304                 }
305                 catch (IOException e)
306                 {
307                     LOG.warn(e);
308                 }
309             }
310         }
311         // super.close();
312         _localPort = -2;
313     }
314 
315     @Override
316     public void accept(int acceptorID) throws IOException
317     {
318         ServerSocketChannel serverChannel = _acceptChannel;
319         if (serverChannel != null && serverChannel.isOpen())
320         {
321             SocketChannel channel = serverChannel.accept();
322             channel.configureBlocking(false);
323             Socket socket = channel.socket();
324             configure(socket);
325             _manager.accept(channel);
326         }
327     }
328 
329     protected void configure(Socket socket)
330     {
331         try
332         {
333             socket.setTcpNoDelay(true);
334             if (_lingerTime >= 0)
335                 socket.setSoLinger(true, _lingerTime / 1000);
336             else
337                 socket.setSoLinger(false, 0);
338         }
339         catch (SocketException e)
340         {
341             LOG.ignore(e);
342         }
343     }
344 
345     public SelectorManager getSelectorManager()
346     {
347         return _manager;
348     }
349 
350     @Override
351     public Object getTransport()
352     {
353         return _acceptChannel;
354     }
355 
356     @Override
357     @ManagedAttribute("local port")
358     public int getLocalPort()
359     {
360         return _localPort;
361     }
362 
363     protected SelectChannelEndPoint newEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey key) throws IOException
364     {
365         return new SelectChannelEndPoint(channel, selectSet, key, getScheduler(), getIdleTimeout());
366     }
367 
368     /**
369      * @return the linger time
370      * @see Socket#getSoLinger()
371      */
372     @ManagedAttribute("TCP/IP solinger time or -1 to disable")
373     public int getSoLingerTime()
374     {
375         return _lingerTime;
376     }
377 
378     /**
379      * @param lingerTime the linger time. Use -1 to disable.
380      * @see Socket#setSoLinger(boolean, int)
381      */
382     public void setSoLingerTime(int lingerTime)
383     {
384         _lingerTime = lingerTime;
385     }
386 
387     /**
388      * @return the accept queue size
389      */
390     @ManagedAttribute("Accept Queue size")
391     public int getAcceptQueueSize()
392     {
393         return _acceptQueueSize;
394     }
395 
396     /**
397      * @param acceptQueueSize the accept queue size (also known as accept backlog)
398      */
399     public void setAcceptQueueSize(int acceptQueueSize)
400     {
401         _acceptQueueSize = acceptQueueSize;
402     }
403 
404     /**
405      * @return whether the server socket reuses addresses
406      * @see ServerSocket#getReuseAddress()
407      */
408     public boolean getReuseAddress()
409     {
410         return _reuseAddress;
411     }
412 
413     /**
414      * @param reuseAddress whether the server socket reuses addresses
415      * @see ServerSocket#setReuseAddress(boolean)
416      */
417     public void setReuseAddress(boolean reuseAddress)
418     {
419         _reuseAddress = reuseAddress;
420     }
421 
422     private final class ServerConnectorManager extends SelectorManager
423     {
424         private ServerConnectorManager(Executor executor, Scheduler scheduler, int selectors)
425         {
426             super(executor, scheduler, selectors);
427         }
428 
429         @Override
430         protected SelectChannelEndPoint newEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey selectionKey) throws IOException
431         {
432             return ServerConnector.this.newEndPoint(channel, selectSet, selectionKey);
433         }
434 
435         @Override
436         public Connection newConnection(SocketChannel channel, EndPoint endpoint, Object attachment) throws IOException
437         {
438             return getDefaultConnectionFactory().newConnection(ServerConnector.this, endpoint);
439         }
440 
441         @Override
442         protected void endPointOpened(EndPoint endpoint)
443         {
444             super.endPointOpened(endpoint);
445             onEndPointOpened(endpoint);
446         }
447 
448         @Override
449         protected void endPointClosed(EndPoint endpoint)
450         {
451             onEndPointClosed(endpoint);
452             super.endPointClosed(endpoint);
453         }
454         
455         
456     }
457 }