PageRenderTime 48ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/jetty-8.1.5.v20120716/jetty-server/src/main/java/org/eclipse/jetty/server/nio/BlockingChannelConnector.java

#
Java | 361 lines | 255 code | 40 blank | 66 comment | 20 complexity | eba06f2c2c40c8eb6ab8be5167e0304e MD5 | raw file
Possible License(s): Apache-2.0
  1. // ========================================================================
  2. // Copyright (c) 2003-2009 Mort Bay Consulting Pty. Ltd.
  3. // ------------------------------------------------------------------------
  4. // All rights reserved. This program and the accompanying materials
  5. // are made available under the terms of the Eclipse Public License v1.0
  6. // and Apache License v2.0 which accompanies this distribution.
  7. // The Eclipse Public License is available at
  8. // http://www.eclipse.org/legal/epl-v10.html
  9. // The Apache License v2.0 is available at
  10. // http://www.opensource.org/licenses/apache2.0.php
  11. // You may elect to redistribute this code under either of these licenses.
  12. // ========================================================================
  13. package org.eclipse.jetty.server.nio;
  14. import java.io.IOException;
  15. import java.net.InetSocketAddress;
  16. import java.net.Socket;
  17. import java.nio.channels.ByteChannel;
  18. import java.nio.channels.SelectionKey;
  19. import java.nio.channels.ServerSocketChannel;
  20. import java.nio.channels.SocketChannel;
  21. import java.util.Set;
  22. import org.eclipse.jetty.http.HttpException;
  23. import org.eclipse.jetty.io.Buffer;
  24. import org.eclipse.jetty.io.ConnectedEndPoint;
  25. import org.eclipse.jetty.io.Connection;
  26. import org.eclipse.jetty.io.EndPoint;
  27. import org.eclipse.jetty.io.EofException;
  28. import org.eclipse.jetty.io.nio.ChannelEndPoint;
  29. import org.eclipse.jetty.server.BlockingHttpConnection;
  30. import org.eclipse.jetty.server.Request;
  31. import org.eclipse.jetty.util.ConcurrentHashSet;
  32. import org.eclipse.jetty.util.log.Log;
  33. import org.eclipse.jetty.util.log.Logger;
  34. /* ------------------------------------------------------------------------------- */
  35. /** Blocking NIO connector.
  36. * This connector uses efficient NIO buffers with a traditional blocking thread model.
  37. * Direct NIO buffers are used and a thread is allocated per connections.
  38. *
  39. * This connector is best used when there are a few very active connections.
  40. *
  41. * @org.apache.xbean.XBean element="blockingNioConnector" description="Creates a blocking NIO based socket connector"
  42. *
  43. *
  44. *
  45. */
  46. public class BlockingChannelConnector extends AbstractNIOConnector
  47. {
  48. private static final Logger LOG = Log.getLogger(BlockingChannelConnector.class);
  49. private transient ServerSocketChannel _acceptChannel;
  50. private final Set<BlockingChannelEndPoint> _endpoints = new ConcurrentHashSet<BlockingChannelEndPoint>();
  51. /* ------------------------------------------------------------ */
  52. /** Constructor.
  53. *
  54. */
  55. public BlockingChannelConnector()
  56. {
  57. }
  58. /* ------------------------------------------------------------ */
  59. public Object getConnection()
  60. {
  61. return _acceptChannel;
  62. }
  63. /* ------------------------------------------------------------ */
  64. /**
  65. * @see org.eclipse.jetty.server.AbstractConnector#doStart()
  66. */
  67. @Override
  68. protected void doStart() throws Exception
  69. {
  70. super.doStart();
  71. getThreadPool().dispatch(new Runnable()
  72. {
  73. public void run()
  74. {
  75. while (isRunning())
  76. {
  77. try
  78. {
  79. Thread.sleep(400);
  80. long now=System.currentTimeMillis();
  81. for (BlockingChannelEndPoint endp : _endpoints)
  82. {
  83. endp.checkIdleTimestamp(now);
  84. }
  85. }
  86. catch(InterruptedException e)
  87. {
  88. LOG.ignore(e);
  89. }
  90. catch(Exception e)
  91. {
  92. LOG.warn(e);
  93. }
  94. }
  95. }
  96. });
  97. }
  98. /* ------------------------------------------------------------ */
  99. public void open() throws IOException
  100. {
  101. // Create a new server socket and set to non blocking mode
  102. _acceptChannel= ServerSocketChannel.open();
  103. _acceptChannel.configureBlocking(true);
  104. // Bind the server socket to the local host and port
  105. InetSocketAddress addr = getHost()==null?new InetSocketAddress(getPort()):new InetSocketAddress(getHost(),getPort());
  106. _acceptChannel.socket().bind(addr,getAcceptQueueSize());
  107. }
  108. /* ------------------------------------------------------------ */
  109. public void close() throws IOException
  110. {
  111. if (_acceptChannel != null)
  112. _acceptChannel.close();
  113. _acceptChannel=null;
  114. }
  115. /* ------------------------------------------------------------ */
  116. @Override
  117. public void accept(int acceptorID)
  118. throws IOException, InterruptedException
  119. {
  120. SocketChannel channel = _acceptChannel.accept();
  121. channel.configureBlocking(true);
  122. Socket socket=channel.socket();
  123. configure(socket);
  124. BlockingChannelEndPoint connection=new BlockingChannelEndPoint(channel);
  125. connection.dispatch();
  126. }
  127. /* ------------------------------------------------------------------------------- */
  128. @Override
  129. public void customize(EndPoint endpoint, Request request)
  130. throws IOException
  131. {
  132. super.customize(endpoint, request);
  133. endpoint.setMaxIdleTime(_maxIdleTime);
  134. configure(((SocketChannel)endpoint.getTransport()).socket());
  135. }
  136. /* ------------------------------------------------------------------------------- */
  137. public int getLocalPort()
  138. {
  139. if (_acceptChannel==null || !_acceptChannel.isOpen())
  140. return -1;
  141. return _acceptChannel.socket().getLocalPort();
  142. }
  143. /* ------------------------------------------------------------------------------- */
  144. /* ------------------------------------------------------------------------------- */
  145. /* ------------------------------------------------------------------------------- */
  146. private class BlockingChannelEndPoint extends ChannelEndPoint implements Runnable, ConnectedEndPoint
  147. {
  148. private Connection _connection;
  149. private int _timeout;
  150. private volatile long _idleTimestamp;
  151. BlockingChannelEndPoint(ByteChannel channel)
  152. throws IOException
  153. {
  154. super(channel,BlockingChannelConnector.this._maxIdleTime);
  155. _connection = new BlockingHttpConnection(BlockingChannelConnector.this,this,getServer());
  156. }
  157. /* ------------------------------------------------------------ */
  158. /** Get the connection.
  159. * @return the connection
  160. */
  161. public Connection getConnection()
  162. {
  163. return _connection;
  164. }
  165. /* ------------------------------------------------------------ */
  166. public void setConnection(Connection connection)
  167. {
  168. _connection=connection;
  169. }
  170. /* ------------------------------------------------------------ */
  171. public void checkIdleTimestamp(long now)
  172. {
  173. if (_idleTimestamp!=0 && _timeout>0 && now>(_idleTimestamp+_timeout))
  174. {
  175. idleExpired();
  176. }
  177. }
  178. /* ------------------------------------------------------------ */
  179. protected void idleExpired()
  180. {
  181. try
  182. {
  183. super.close();
  184. }
  185. catch (IOException e)
  186. {
  187. LOG.ignore(e);
  188. }
  189. }
  190. /* ------------------------------------------------------------ */
  191. void dispatch() throws IOException
  192. {
  193. if (!getThreadPool().dispatch(this))
  194. {
  195. LOG.warn("dispatch failed for {}",_connection);
  196. super.close();
  197. }
  198. }
  199. /* ------------------------------------------------------------ */
  200. /**
  201. * @see org.eclipse.jetty.io.nio.ChannelEndPoint#fill(org.eclipse.jetty.io.Buffer)
  202. */
  203. @Override
  204. public int fill(Buffer buffer) throws IOException
  205. {
  206. _idleTimestamp=System.currentTimeMillis();
  207. return super.fill(buffer);
  208. }
  209. /* ------------------------------------------------------------ */
  210. /**
  211. * @see org.eclipse.jetty.io.nio.ChannelEndPoint#flush(org.eclipse.jetty.io.Buffer)
  212. */
  213. @Override
  214. public int flush(Buffer buffer) throws IOException
  215. {
  216. _idleTimestamp=System.currentTimeMillis();
  217. return super.flush(buffer);
  218. }
  219. /* ------------------------------------------------------------ */
  220. /**
  221. * @see org.eclipse.jetty.io.nio.ChannelEndPoint#flush(org.eclipse.jetty.io.Buffer, org.eclipse.jetty.io.Buffer, org.eclipse.jetty.io.Buffer)
  222. */
  223. @Override
  224. public int flush(Buffer header, Buffer buffer, Buffer trailer) throws IOException
  225. {
  226. _idleTimestamp=System.currentTimeMillis();
  227. return super.flush(header,buffer,trailer);
  228. }
  229. /* ------------------------------------------------------------ */
  230. public void run()
  231. {
  232. try
  233. {
  234. _timeout=getMaxIdleTime();
  235. connectionOpened(_connection);
  236. _endpoints.add(this);
  237. while (isOpen())
  238. {
  239. _idleTimestamp=System.currentTimeMillis();
  240. if (_connection.isIdle())
  241. {
  242. if (getServer().getThreadPool().isLowOnThreads())
  243. {
  244. int lrmit = getLowResourcesMaxIdleTime();
  245. if (lrmit>=0 && _timeout!= lrmit)
  246. {
  247. _timeout=lrmit;
  248. }
  249. }
  250. }
  251. else
  252. {
  253. if (_timeout!=getMaxIdleTime())
  254. {
  255. _timeout=getMaxIdleTime();
  256. }
  257. }
  258. _connection = _connection.handle();
  259. }
  260. }
  261. catch (EofException e)
  262. {
  263. LOG.debug("EOF", e);
  264. try{BlockingChannelEndPoint.this.close();}
  265. catch(IOException e2){LOG.ignore(e2);}
  266. }
  267. catch (HttpException e)
  268. {
  269. LOG.debug("BAD", e);
  270. try{super.close();}
  271. catch(IOException e2){LOG.ignore(e2);}
  272. }
  273. catch(Throwable e)
  274. {
  275. LOG.warn("handle failed",e);
  276. try{super.close();}
  277. catch(IOException e2){LOG.ignore(e2);}
  278. }
  279. finally
  280. {
  281. connectionClosed(_connection);
  282. _endpoints.remove(this);
  283. // wait for client to close, but if not, close ourselves.
  284. try
  285. {
  286. if (!_socket.isClosed())
  287. {
  288. long timestamp=System.currentTimeMillis();
  289. int max_idle=getMaxIdleTime();
  290. _socket.setSoTimeout(getMaxIdleTime());
  291. int c=0;
  292. do
  293. {
  294. c = _socket.getInputStream().read();
  295. }
  296. while (c>=0 && (System.currentTimeMillis()-timestamp)<max_idle);
  297. if (!_socket.isClosed())
  298. _socket.close();
  299. }
  300. }
  301. catch(IOException e)
  302. {
  303. LOG.ignore(e);
  304. }
  305. }
  306. }
  307. /* ------------------------------------------------------------ */
  308. @Override
  309. public String toString()
  310. {
  311. return String.format("BCEP@%x{l(%s)<->r(%s),open=%b,ishut=%b,oshut=%b}-{%s}",
  312. hashCode(),
  313. _socket.getRemoteSocketAddress(),
  314. _socket.getLocalSocketAddress(),
  315. isOpen(),
  316. isInputShutdown(),
  317. isOutputShutdown(),
  318. _connection);
  319. }
  320. }
  321. }