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.
9 // The Eclipse Public License is available at
10 // http://www.eclipse.org/legal/epl-v10.html
12 // The Apache License v2.0 is available at
13 // http://www.opensource.org/licenses/apache2.0.php
15 // You may elect to redistribute this code under either of these licenses.
16 // ========================================================================
19 package org.eclipse.jetty.server;
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;
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;
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.
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.
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.
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.
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.
79 @ManagedObject("HTTP connector using NIO ByteChannels and Selectors")
80 public class ServerConnector extends AbstractNetworkConnector
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;
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.
96 public ServerConnector(
97 @Name("server") Server server)
99 this(server,null,null,null,-1,-1,new HttpConnectionFactory());
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.
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.
110 * the number of selector threads, or -1 for a default value. Selectors notice and schedule established connection that can make IO progress.
112 public ServerConnector(
113 @Name("server") Server server,
114 @Name("acceptors") int acceptors,
115 @Name("selectors") int selectors)
117 this(server,null,null,null,acceptors,selectors,new HttpConnectionFactory());
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.
126 public ServerConnector(
127 @Name("server") Server server,
128 @Name("factories") ConnectionFactory... factories)
130 this(server,null,null,null,-1,-1,factories);
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.
140 public ServerConnector(
141 @Name("server") Server server,
142 @Name("sslContextFactory") SslContextFactory sslContextFactory)
144 this(server,null,null,null,-1,-1,AbstractConnectionFactory.getFactories(sslContextFactory,new HttpConnectionFactory()));
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.
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.
157 * the number of selector threads, or -1 for a default value. Selectors notice and schedule established connection that can make IO progress.
159 public ServerConnector(
160 @Name("server") Server server,
161 @Name("acceptors") int acceptors,
162 @Name("selectors") int selectors,
163 @Name("sslContextFactory") SslContextFactory sslContextFactory)
165 this(server,null,null,null,acceptors,selectors,AbstractConnectionFactory.getFactories(sslContextFactory,new HttpConnectionFactory()));
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.
175 public ServerConnector(
176 @Name("server") Server server,
177 @Name("sslContextFactory") SslContextFactory sslContextFactory,
178 @Name("factories") ConnectionFactory... factories)
180 this(server,null,null,null,-1,-1,AbstractConnectionFactory.getFactories(sslContextFactory,factories));
183 /** Generic Server Connection.
185 * The server this connector will be accept connection for.
187 * An executor used to run tasks for handling requests, acceptors and selectors. I
188 * If null then use the servers executor
190 * A scheduler used to schedule timeouts. If null then use the servers scheduler
192 * A ByteBuffer pool used to allocate buffers. If null then create a private pool with default configuration.
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.
197 * the number of selector threads, or -1 for a default value. Selectors notice and schedule established connection that can make IO progress.
199 * Zero or more {@link ConnectionFactory} instances used to create and configure connections.
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)
210 super(server,executor,scheduler,bufferPool,acceptors,factories);
211 _manager = new ServerConnectorManager(getExecutor(), getScheduler(), selectors > 0 ? selectors : Runtime.getRuntime().availableProcessors());
212 addBean(_manager, true);
216 protected void doStart() throws Exception
220 if (getAcceptors()==0)
222 _acceptChannel.configureBlocking(false);
223 _manager.acceptor(_acceptChannel);
228 public boolean isOpen()
230 ServerSocketChannel channel = _acceptChannel;
231 return channel!=null && channel.isOpen();
235 * @return whether this connector uses a channel inherited from the JVM.
236 * @see System#inheritedChannel()
238 public boolean isInheritChannel()
240 return _inheritChannel;
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
252 * @param inheritChannel whether this connector uses a channel inherited from the JVM.
254 public void setInheritChannel(boolean inheritChannel)
256 _inheritChannel = inheritChannel;
260 public void open() throws IOException
262 if (_acceptChannel == null)
264 ServerSocketChannel serverChannel = null;
265 if (isInheritChannel())
267 Channel channel = System.inheritedChannel();
268 if (channel instanceof ServerSocketChannel)
269 serverChannel = (ServerSocketChannel)channel;
271 LOG.warn("Unable to use System.inheritedChannel() [{}]. Trying a new ServerSocketChannel at {}:{}", channel, getHost(), getPort());
274 if (serverChannel == null)
276 serverChannel = ServerSocketChannel.open();
278 InetSocketAddress bindAddress = getHost() == null ? new InetSocketAddress(getPort()) : new InetSocketAddress(getHost(), getPort());
279 serverChannel.socket().bind(bindAddress, getAcceptQueueSize());
280 serverChannel.socket().setReuseAddress(getReuseAddress());
282 _localPort = serverChannel.socket().getLocalPort();
284 throw new IOException("Server channel not bound");
286 addBean(serverChannel);
289 serverChannel.configureBlocking(true);
290 addBean(serverChannel);
292 _acceptChannel = serverChannel;
297 public Future<Void> shutdown()
299 // TODO shutdown all the connections
300 return super.shutdown();
306 ServerSocketChannel serverChannel = _acceptChannel;
307 _acceptChannel = null;
309 if (serverChannel != null)
311 removeBean(serverChannel);
313 // If the interrupt did not close it, we should close it
314 if (serverChannel.isOpen())
318 serverChannel.close();
320 catch (IOException e)
331 public void accept(int acceptorID) throws IOException
333 ServerSocketChannel serverChannel = _acceptChannel;
334 if (serverChannel != null && serverChannel.isOpen())
336 SocketChannel channel = serverChannel.accept();
341 private void accepted(SocketChannel channel) throws IOException
343 channel.configureBlocking(false);
344 Socket socket = channel.socket();
346 _manager.accept(channel);
349 protected void configure(Socket socket)
353 socket.setTcpNoDelay(true);
354 if (_lingerTime >= 0)
355 socket.setSoLinger(true, _lingerTime / 1000);
357 socket.setSoLinger(false, 0);
359 catch (SocketException e)
365 public SelectorManager getSelectorManager()
371 public Object getTransport()
373 return _acceptChannel;
377 @ManagedAttribute("local port")
378 public int getLocalPort()
383 protected SelectChannelEndPoint newEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey key) throws IOException
385 return new SelectChannelEndPoint(channel, selectSet, key, getScheduler(), getIdleTimeout());
389 * @return the linger time
390 * @see Socket#getSoLinger()
392 @ManagedAttribute("TCP/IP solinger time or -1 to disable")
393 public int getSoLingerTime()
399 * @param lingerTime the linger time. Use -1 to disable.
400 * @see Socket#setSoLinger(boolean, int)
402 public void setSoLingerTime(int lingerTime)
404 _lingerTime = lingerTime;
408 * @return the accept queue size
410 @ManagedAttribute("Accept Queue size")
411 public int getAcceptQueueSize()
413 return _acceptQueueSize;
417 * @param acceptQueueSize the accept queue size (also known as accept backlog)
419 public void setAcceptQueueSize(int acceptQueueSize)
421 _acceptQueueSize = acceptQueueSize;
425 * @return whether the server socket reuses addresses
426 * @see ServerSocket#getReuseAddress()
428 public boolean getReuseAddress()
430 return _reuseAddress;
434 * @param reuseAddress whether the server socket reuses addresses
435 * @see ServerSocket#setReuseAddress(boolean)
437 public void setReuseAddress(boolean reuseAddress)
439 _reuseAddress = reuseAddress;
442 private final class ServerConnectorManager extends SelectorManager
444 private ServerConnectorManager(Executor executor, Scheduler scheduler, int selectors)
446 super(executor, scheduler, selectors);
450 protected void accepted(SocketChannel channel) throws IOException
452 ServerConnector.this.accepted(channel);
456 protected SelectChannelEndPoint newEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey selectionKey) throws IOException
458 return ServerConnector.this.newEndPoint(channel, selectSet, selectionKey);
462 public Connection newConnection(SocketChannel channel, EndPoint endpoint, Object attachment) throws IOException
464 return getDefaultConnectionFactory().newConnection(ServerConnector.this, endpoint);
468 protected void endPointOpened(EndPoint endpoint)
470 super.endPointOpened(endpoint);
471 onEndPointOpened(endpoint);
475 protected void endPointClosed(EndPoint endpoint)
477 onEndPointClosed(endpoint);
478 super.endPointClosed(endpoint);