]> WPIA git - gigi.git/blob - lib/jetty/org/eclipse/jetty/server/ServerConnector.java
Importing upstream Jetty jetty-9.2.1.v20140609
[gigi.git] / lib / jetty / org / eclipse / jetty / server / ServerConnector.java
1 //
2 //  ========================================================================
3 //  Copyright (c) 1995-2014 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(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,-1,-1,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 -1 for a default value. Acceptors accept new TCP/IP connections.  If 0, then 
108      *          the selector threads are used to accept connections.
109      * @param selectors
110      *          the number of selector threads, or -1 for a default value. Selectors notice and schedule established connection that can make IO progress.
111      */
112     public ServerConnector(
113         @Name("server") Server server,
114         @Name("acceptors") int acceptors,
115         @Name("selectors") int selectors)
116     {
117         this(server,null,null,null,acceptors,selectors,new HttpConnectionFactory());
118     }
119
120     /* ------------------------------------------------------------ */
121     /** Generic Server Connection with default configuration.
122      * <p>Construct a Server Connector with the passed Connection factories.</p>
123      * @param server The {@link Server} this connector will accept connection for. 
124      * @param factories Zero or more {@link ConnectionFactory} instances used to create and configure connections.
125      */
126     public ServerConnector(
127         @Name("server") Server server,
128         @Name("factories") ConnectionFactory... factories)
129     {
130         this(server,null,null,null,-1,-1,factories);
131     }
132
133     /* ------------------------------------------------------------ */
134     /** HTTP Server Connection.
135      * <p>Construct a ServerConnector with a private instance of {@link HttpConnectionFactory} as the primary protocol</p>.
136      * @param server The {@link Server} this connector will accept connection for. 
137      * @param sslContextFactory If non null, then a {@link SslConnectionFactory} is instantiated and prepended to the 
138      * list of HTTP Connection Factory.
139      */
140     public ServerConnector(
141         @Name("server") Server server,
142         @Name("sslContextFactory") SslContextFactory sslContextFactory)
143     {
144         this(server,null,null,null,-1,-1,AbstractConnectionFactory.getFactories(sslContextFactory,new HttpConnectionFactory()));
145     }
146
147     /* ------------------------------------------------------------ */
148     /** HTTP Server Connection.
149      * <p>Construct a ServerConnector with a private instance of {@link HttpConnectionFactory} as the primary protocol</p>.
150      * @param server The {@link Server} this connector will accept connection for. 
151      * @param sslContextFactory If non null, then a {@link SslConnectionFactory} is instantiated and prepended to the 
152      * list of HTTP Connection Factory.
153      * @param acceptors 
154      *          the number of acceptor threads to use, or -1 for a default value. Acceptors accept new TCP/IP connections.  If 0, then 
155      *          the selector threads are used to accept connections.
156      * @param selectors
157      *          the number of selector threads, or -1 for a default value. Selectors notice and schedule established connection that can make IO progress.
158      */
159     public ServerConnector(
160         @Name("server") Server server,
161         @Name("acceptors") int acceptors,
162         @Name("selectors") int selectors,
163         @Name("sslContextFactory") SslContextFactory sslContextFactory)
164     {
165         this(server,null,null,null,acceptors,selectors,AbstractConnectionFactory.getFactories(sslContextFactory,new HttpConnectionFactory()));
166     }
167
168     /* ------------------------------------------------------------ */
169     /** Generic SSL Server Connection.
170      * @param server The {@link Server} this connector will accept connection for. 
171      * @param sslContextFactory If non null, then a {@link SslConnectionFactory} is instantiated and prepended to the 
172      * list of ConnectionFactories, with the first factory being the default protocol for the SslConnectionFactory.
173      * @param factories Zero or more {@link ConnectionFactory} instances used to create and configure connections.
174      */
175     public ServerConnector(
176         @Name("server") Server server,
177         @Name("sslContextFactory") SslContextFactory sslContextFactory,
178         @Name("factories") ConnectionFactory... factories)
179     {
180         this(server,null,null,null,-1,-1,AbstractConnectionFactory.getFactories(sslContextFactory,factories));
181     }
182
183     /** Generic Server Connection.
184      * @param server    
185      *          The server this connector will be accept connection for.  
186      * @param executor  
187      *          An executor used to run tasks for handling requests, acceptors and selectors. I
188      *          If null then use the servers executor
189      * @param scheduler 
190      *          A scheduler used to schedule timeouts. If null then use the servers scheduler
191      * @param bufferPool
192      *          A ByteBuffer pool used to allocate buffers.  If null then create a private pool with default configuration.
193      * @param acceptors 
194      *          the number of acceptor threads to use, or -1 for a default value. Acceptors accept new TCP/IP connections.  If 0, then 
195      *          the selector threads are used to accept connections.
196      * @param selectors
197      *          the number of selector threads, or -1 for a default value. Selectors notice and schedule established connection that can make IO progress.
198      * @param factories 
199      *          Zero or more {@link ConnectionFactory} instances used to create and configure connections.
200      */
201     public ServerConnector(
202         @Name("server") Server server,
203         @Name("executor") Executor executor,
204         @Name("scheduler") Scheduler scheduler,
205         @Name("bufferPool") ByteBufferPool bufferPool,
206         @Name("acceptors") int acceptors,
207         @Name("selectors") int selectors,
208         @Name("factories") ConnectionFactory... factories)
209     {
210         super(server,executor,scheduler,bufferPool,acceptors,factories);
211         _manager = new ServerConnectorManager(getExecutor(), getScheduler(), selectors > 0 ? selectors : Runtime.getRuntime().availableProcessors());
212         addBean(_manager, true);
213     }
214
215     @Override
216     protected void doStart() throws Exception
217     {
218         super.doStart();
219
220         if (getAcceptors()==0)
221         {
222             _acceptChannel.configureBlocking(false);
223             _manager.acceptor(_acceptChannel);
224         }
225     }
226
227     @Override
228     public boolean isOpen()
229     {
230         ServerSocketChannel channel = _acceptChannel;
231         return channel!=null && channel.isOpen();
232     }
233
234     /**
235      * @return whether this connector uses a channel inherited from the JVM.
236      * @see System#inheritedChannel()
237      */
238     public boolean isInheritChannel()
239     {
240         return _inheritChannel;
241     }
242
243     /**
244      * <p>Sets whether this connector uses a channel inherited from the JVM.</p>
245      * <p>If true, the connector first tries to inherit from a channel provided by the system.
246      * If there is no inherited channel available, or if the inherited channel is not usable,
247      * then it will fall back using {@link ServerSocketChannel}.</p>
248      * <p>Use it with xinetd/inetd, to launch an instance of Jetty on demand. The port
249      * used to access pages on the Jetty instance is the same as the port used to
250      * launch Jetty.</p>
251      *
252      * @param inheritChannel whether this connector uses a channel inherited from the JVM.
253      */
254     public void setInheritChannel(boolean inheritChannel)
255     {
256         _inheritChannel = inheritChannel;
257     }
258
259     @Override
260     public void open() throws IOException
261     {
262         if (_acceptChannel == null)
263         {
264             ServerSocketChannel serverChannel = null;
265             if (isInheritChannel())
266             {
267                 Channel channel = System.inheritedChannel();
268                 if (channel instanceof ServerSocketChannel)
269                     serverChannel = (ServerSocketChannel)channel;
270                 else
271                     LOG.warn("Unable to use System.inheritedChannel() [{}]. Trying a new ServerSocketChannel at {}:{}", channel, getHost(), getPort());
272             }
273
274             if (serverChannel == null)
275             {
276                 serverChannel = ServerSocketChannel.open();
277
278                 InetSocketAddress bindAddress = getHost() == null ? new InetSocketAddress(getPort()) : new InetSocketAddress(getHost(), getPort());
279                 serverChannel.socket().bind(bindAddress, getAcceptQueueSize());
280                 serverChannel.socket().setReuseAddress(getReuseAddress());
281
282                 _localPort = serverChannel.socket().getLocalPort();
283                 if (_localPort <= 0)
284                     throw new IOException("Server channel not bound");
285
286                 addBean(serverChannel);
287             }
288
289             serverChannel.configureBlocking(true);
290             addBean(serverChannel);
291
292             _acceptChannel = serverChannel;
293         }
294     }
295
296     @Override
297     public Future<Void> shutdown()
298     {
299         // TODO shutdown all the connections
300         return super.shutdown();
301     }
302
303     @Override
304     public void close()
305     {
306         ServerSocketChannel serverChannel = _acceptChannel;
307         _acceptChannel = null;
308
309         if (serverChannel != null)
310         {
311             removeBean(serverChannel);
312
313             // If the interrupt did not close it, we should close it
314             if (serverChannel.isOpen())
315             {
316                 try
317                 {
318                     serverChannel.close();
319                 }
320                 catch (IOException e)
321                 {
322                     LOG.warn(e);
323                 }
324             }
325         }
326         // super.close();
327         _localPort = -2;
328     }
329
330     @Override
331     public void accept(int acceptorID) throws IOException
332     {
333         ServerSocketChannel serverChannel = _acceptChannel;
334         if (serverChannel != null && serverChannel.isOpen())
335         {
336             SocketChannel channel = serverChannel.accept();
337             accepted(channel);
338         }
339     }
340     
341     private void accepted(SocketChannel channel) throws IOException
342     {
343         channel.configureBlocking(false);
344         Socket socket = channel.socket();
345         configure(socket);
346         _manager.accept(channel);
347     }
348
349     protected void configure(Socket socket)
350     {
351         try
352         {
353             socket.setTcpNoDelay(true);
354             if (_lingerTime >= 0)
355                 socket.setSoLinger(true, _lingerTime / 1000);
356             else
357                 socket.setSoLinger(false, 0);
358         }
359         catch (SocketException e)
360         {
361             LOG.ignore(e);
362         }
363     }
364
365     public SelectorManager getSelectorManager()
366     {
367         return _manager;
368     }
369
370     @Override
371     public Object getTransport()
372     {
373         return _acceptChannel;
374     }
375
376     @Override
377     @ManagedAttribute("local port")
378     public int getLocalPort()
379     {
380         return _localPort;
381     }
382
383     protected SelectChannelEndPoint newEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey key) throws IOException
384     {
385         return new SelectChannelEndPoint(channel, selectSet, key, getScheduler(), getIdleTimeout());
386     }
387
388     /**
389      * @return the linger time
390      * @see Socket#getSoLinger()
391      */
392     @ManagedAttribute("TCP/IP solinger time or -1 to disable")
393     public int getSoLingerTime()
394     {
395         return _lingerTime;
396     }
397
398     /**
399      * @param lingerTime the linger time. Use -1 to disable.
400      * @see Socket#setSoLinger(boolean, int)
401      */
402     public void setSoLingerTime(int lingerTime)
403     {
404         _lingerTime = lingerTime;
405     }
406
407     /**
408      * @return the accept queue size
409      */
410     @ManagedAttribute("Accept Queue size")
411     public int getAcceptQueueSize()
412     {
413         return _acceptQueueSize;
414     }
415
416     /**
417      * @param acceptQueueSize the accept queue size (also known as accept backlog)
418      */
419     public void setAcceptQueueSize(int acceptQueueSize)
420     {
421         _acceptQueueSize = acceptQueueSize;
422     }
423
424     /**
425      * @return whether the server socket reuses addresses
426      * @see ServerSocket#getReuseAddress()
427      */
428     public boolean getReuseAddress()
429     {
430         return _reuseAddress;
431     }
432
433     /**
434      * @param reuseAddress whether the server socket reuses addresses
435      * @see ServerSocket#setReuseAddress(boolean)
436      */
437     public void setReuseAddress(boolean reuseAddress)
438     {
439         _reuseAddress = reuseAddress;
440     }
441
442     private final class ServerConnectorManager extends SelectorManager
443     {
444         private ServerConnectorManager(Executor executor, Scheduler scheduler, int selectors)
445         {
446             super(executor, scheduler, selectors);
447         }
448
449         @Override
450         protected void accepted(SocketChannel channel) throws IOException
451         {
452             ServerConnector.this.accepted(channel);
453         }
454
455         @Override
456         protected SelectChannelEndPoint newEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey selectionKey) throws IOException
457         {
458             return ServerConnector.this.newEndPoint(channel, selectSet, selectionKey);
459         }
460
461         @Override
462         public Connection newConnection(SocketChannel channel, EndPoint endpoint, Object attachment) throws IOException
463         {
464             return getDefaultConnectionFactory().newConnection(ServerConnector.this, endpoint);
465         }
466
467         @Override
468         protected void endPointOpened(EndPoint endpoint)
469         {
470             super.endPointOpened(endpoint);
471             onEndPointOpened(endpoint);
472         }
473
474         @Override
475         protected void endPointClosed(EndPoint endpoint)
476         {
477             onEndPointClosed(endpoint);
478             super.endPointClosed(endpoint);
479         }
480         
481         
482     }
483 }