PageRenderTime 70ms CodeModel.GetById 39ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main/java/org/elasticsearch/http/netty/NettyHttpServerTransport.java

https://github.com/holdenk/elasticsearch
Java | 315 lines | 238 code | 51 blank | 26 comment | 30 complexity | b2e18e585cd459b7af8be715f0703a08 MD5 | raw file
  1. /*
  2. * Licensed to ElasticSearch and Shay Banon under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. ElasticSearch licenses this
  6. * file 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. package org.elasticsearch.http.netty;
  20. import org.elasticsearch.ElasticSearchException;
  21. import org.elasticsearch.common.component.AbstractLifecycleComponent;
  22. import org.elasticsearch.common.inject.Inject;
  23. import org.elasticsearch.common.netty.OpenChannelsHandler;
  24. import org.elasticsearch.common.network.NetworkService;
  25. import org.elasticsearch.common.network.NetworkUtils;
  26. import org.elasticsearch.common.settings.Settings;
  27. import org.elasticsearch.common.transport.BoundTransportAddress;
  28. import org.elasticsearch.common.transport.InetSocketTransportAddress;
  29. import org.elasticsearch.common.transport.NetworkExceptionHelper;
  30. import org.elasticsearch.common.transport.PortsRange;
  31. import org.elasticsearch.common.unit.ByteSizeUnit;
  32. import org.elasticsearch.common.unit.ByteSizeValue;
  33. import org.elasticsearch.http.*;
  34. import org.elasticsearch.http.HttpRequest;
  35. import org.elasticsearch.transport.BindTransportException;
  36. import org.elasticsearch.transport.netty.NettyInternalESLoggerFactory;
  37. import org.jboss.netty.bootstrap.ServerBootstrap;
  38. import org.jboss.netty.channel.*;
  39. import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
  40. import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory;
  41. import org.jboss.netty.handler.codec.http.*;
  42. import org.jboss.netty.handler.timeout.ReadTimeoutException;
  43. import org.jboss.netty.logging.InternalLogger;
  44. import org.jboss.netty.logging.InternalLoggerFactory;
  45. import java.io.IOException;
  46. import java.net.InetAddress;
  47. import java.net.InetSocketAddress;
  48. import java.util.concurrent.Executors;
  49. import java.util.concurrent.atomic.AtomicReference;
  50. import static org.elasticsearch.common.network.NetworkService.TcpSettings.*;
  51. import static org.elasticsearch.common.util.concurrent.EsExecutors.daemonThreadFactory;
  52. /**
  53. *
  54. */
  55. public class NettyHttpServerTransport extends AbstractLifecycleComponent<HttpServerTransport> implements HttpServerTransport {
  56. static {
  57. InternalLoggerFactory.setDefaultFactory(new NettyInternalESLoggerFactory() {
  58. @Override
  59. public InternalLogger newInstance(String name) {
  60. return super.newInstance(name.replace("org.jboss.netty.", "netty.").replace("org.jboss.netty.", "netty."));
  61. }
  62. });
  63. }
  64. private final NetworkService networkService;
  65. final ByteSizeValue maxContentLength;
  66. final ByteSizeValue maxInitialLineLength;
  67. final ByteSizeValue maxHeaderSize;
  68. final ByteSizeValue maxChunkSize;
  69. private final int workerCount;
  70. private final boolean blockingServer;
  71. final boolean compression;
  72. private final int compressionLevel;
  73. final boolean resetCookies;
  74. private final String port;
  75. private final String bindHost;
  76. private final String publishHost;
  77. private final Boolean tcpNoDelay;
  78. private final Boolean tcpKeepAlive;
  79. private final Boolean reuseAddress;
  80. private final ByteSizeValue tcpSendBufferSize;
  81. private final ByteSizeValue tcpReceiveBufferSize;
  82. private volatile ServerBootstrap serverBootstrap;
  83. private volatile BoundTransportAddress boundAddress;
  84. private volatile Channel serverChannel;
  85. OpenChannelsHandler serverOpenChannels;
  86. private volatile HttpServerAdapter httpServerAdapter;
  87. @Inject
  88. public NettyHttpServerTransport(Settings settings, NetworkService networkService) {
  89. super(settings);
  90. this.networkService = networkService;
  91. ByteSizeValue maxContentLength = componentSettings.getAsBytesSize("max_content_length", settings.getAsBytesSize("http.max_content_length", new ByteSizeValue(100, ByteSizeUnit.MB)));
  92. this.maxChunkSize = componentSettings.getAsBytesSize("max_chunk_size", settings.getAsBytesSize("http.max_chunk_size", new ByteSizeValue(8, ByteSizeUnit.KB)));
  93. this.maxHeaderSize = componentSettings.getAsBytesSize("max_header_size", settings.getAsBytesSize("http.max_header_size", new ByteSizeValue(8, ByteSizeUnit.KB)));
  94. this.maxInitialLineLength = componentSettings.getAsBytesSize("max_initial_line_length", settings.getAsBytesSize("http.max_initial_line_length", new ByteSizeValue(4, ByteSizeUnit.KB)));
  95. // don't reset cookies by default, since I don't think we really need to, and parsing of cookies with netty is slow
  96. // and requires a large stack allocation because of the use of regex
  97. this.resetCookies = componentSettings.getAsBoolean("reset_cookies", settings.getAsBoolean("http.reset_cookies", false));
  98. this.workerCount = componentSettings.getAsInt("worker_count", Runtime.getRuntime().availableProcessors() * 2);
  99. this.blockingServer = settings.getAsBoolean("http.blocking_server", settings.getAsBoolean(TCP_BLOCKING_SERVER, settings.getAsBoolean(TCP_BLOCKING, false)));
  100. this.port = componentSettings.get("port", settings.get("http.port", "9200-9300"));
  101. this.bindHost = componentSettings.get("bind_host", settings.get("http.bind_host", settings.get("http.host")));
  102. this.publishHost = componentSettings.get("publish_host", settings.get("http.publish_host", settings.get("http.host")));
  103. this.tcpNoDelay = componentSettings.getAsBoolean("tcp_no_delay", settings.getAsBoolean(TCP_NO_DELAY, true));
  104. this.tcpKeepAlive = componentSettings.getAsBoolean("tcp_keep_alive", settings.getAsBoolean(TCP_KEEP_ALIVE, true));
  105. this.reuseAddress = componentSettings.getAsBoolean("reuse_address", settings.getAsBoolean(TCP_REUSE_ADDRESS, NetworkUtils.defaultReuseAddress()));
  106. this.tcpSendBufferSize = componentSettings.getAsBytesSize("tcp_send_buffer_size", settings.getAsBytesSize(TCP_SEND_BUFFER_SIZE, TCP_DEFAULT_SEND_BUFFER_SIZE));
  107. this.tcpReceiveBufferSize = componentSettings.getAsBytesSize("tcp_receive_buffer_size", settings.getAsBytesSize(TCP_RECEIVE_BUFFER_SIZE, TCP_DEFAULT_RECEIVE_BUFFER_SIZE));
  108. this.compression = settings.getAsBoolean("http.compression", false);
  109. this.compressionLevel = settings.getAsInt("http.compression_level", 6);
  110. // validate max content length
  111. if (maxContentLength.bytes() > Integer.MAX_VALUE) {
  112. logger.warn("maxContentLength[" + maxContentLength + "] set to high value, resetting it to [100mb]");
  113. maxContentLength = new ByteSizeValue(100, ByteSizeUnit.MB);
  114. }
  115. this.maxContentLength = maxContentLength;
  116. logger.debug("using max_chunk_size[{}], max_header_size[{}], max_initial_line_length[{}], max_content_length[{}]",
  117. maxChunkSize, maxHeaderSize, maxInitialLineLength, this.maxContentLength);
  118. }
  119. public void httpServerAdapter(HttpServerAdapter httpServerAdapter) {
  120. this.httpServerAdapter = httpServerAdapter;
  121. }
  122. @Override
  123. protected void doStart() throws ElasticSearchException {
  124. this.serverOpenChannels = new OpenChannelsHandler(logger);
  125. if (blockingServer) {
  126. serverBootstrap = new ServerBootstrap(new OioServerSocketChannelFactory(
  127. Executors.newCachedThreadPool(daemonThreadFactory(settings, "http_server_boss")),
  128. Executors.newCachedThreadPool(daemonThreadFactory(settings, "http_server_worker"))
  129. ));
  130. } else {
  131. serverBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
  132. Executors.newCachedThreadPool(daemonThreadFactory(settings, "http_server_boss")),
  133. Executors.newCachedThreadPool(daemonThreadFactory(settings, "http_server_worker")),
  134. workerCount));
  135. }
  136. serverBootstrap.setPipelineFactory(new MyChannelPipelineFactory(this));
  137. if (tcpNoDelay != null) {
  138. serverBootstrap.setOption("child.tcpNoDelay", tcpNoDelay);
  139. }
  140. if (tcpKeepAlive != null) {
  141. serverBootstrap.setOption("child.keepAlive", tcpKeepAlive);
  142. }
  143. if (tcpSendBufferSize != null) {
  144. serverBootstrap.setOption("child.sendBufferSize", tcpSendBufferSize.bytes());
  145. }
  146. if (tcpReceiveBufferSize != null) {
  147. serverBootstrap.setOption("child.receiveBufferSize", tcpReceiveBufferSize.bytes());
  148. }
  149. if (reuseAddress != null) {
  150. serverBootstrap.setOption("reuseAddress", reuseAddress);
  151. serverBootstrap.setOption("child.reuseAddress", reuseAddress);
  152. }
  153. // Bind and start to accept incoming connections.
  154. InetAddress hostAddressX;
  155. try {
  156. hostAddressX = networkService.resolveBindHostAddress(bindHost);
  157. } catch (IOException e) {
  158. throw new BindHttpException("Failed to resolve host [" + bindHost + "]", e);
  159. }
  160. final InetAddress hostAddress = hostAddressX;
  161. PortsRange portsRange = new PortsRange(port);
  162. final AtomicReference<Exception> lastException = new AtomicReference<Exception>();
  163. boolean success = portsRange.iterate(new PortsRange.PortCallback() {
  164. @Override
  165. public boolean onPortNumber(int portNumber) {
  166. try {
  167. serverChannel = serverBootstrap.bind(new InetSocketAddress(hostAddress, portNumber));
  168. } catch (Exception e) {
  169. lastException.set(e);
  170. return false;
  171. }
  172. return true;
  173. }
  174. });
  175. if (!success) {
  176. throw new BindHttpException("Failed to bind to [" + port + "]", lastException.get());
  177. }
  178. InetSocketAddress boundAddress = (InetSocketAddress) serverChannel.getLocalAddress();
  179. InetSocketAddress publishAddress;
  180. try {
  181. publishAddress = new InetSocketAddress(networkService.resolvePublishHostAddress(publishHost), boundAddress.getPort());
  182. } catch (Exception e) {
  183. throw new BindTransportException("Failed to resolve publish address", e);
  184. }
  185. this.boundAddress = new BoundTransportAddress(new InetSocketTransportAddress(boundAddress), new InetSocketTransportAddress(publishAddress));
  186. }
  187. @Override
  188. protected void doStop() throws ElasticSearchException {
  189. if (serverChannel != null) {
  190. serverChannel.close().awaitUninterruptibly();
  191. serverChannel = null;
  192. }
  193. if (serverOpenChannels != null) {
  194. serverOpenChannels.close();
  195. serverOpenChannels = null;
  196. }
  197. if (serverBootstrap != null) {
  198. serverBootstrap.releaseExternalResources();
  199. serverBootstrap = null;
  200. }
  201. }
  202. @Override
  203. protected void doClose() throws ElasticSearchException {
  204. }
  205. public BoundTransportAddress boundAddress() {
  206. return this.boundAddress;
  207. }
  208. @Override
  209. public HttpStats stats() {
  210. OpenChannelsHandler channels = serverOpenChannels;
  211. return new HttpStats(channels == null ? 0 : channels.numberOfOpenChannels(), channels == null ? 0 : channels.totalChannels());
  212. }
  213. void dispatchRequest(HttpRequest request, HttpChannel channel) {
  214. httpServerAdapter.dispatchRequest(request, channel);
  215. }
  216. void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
  217. if (e.getCause() instanceof ReadTimeoutException) {
  218. if (logger.isTraceEnabled()) {
  219. logger.trace("Connection timeout [{}]", ctx.getChannel().getRemoteAddress());
  220. }
  221. ctx.getChannel().close();
  222. } else {
  223. if (!lifecycle.started()) {
  224. // ignore
  225. return;
  226. }
  227. if (!NetworkExceptionHelper.isCloseConnectionException(e.getCause())) {
  228. logger.warn("Caught exception while handling client http traffic, closing connection {}", e.getCause(), ctx.getChannel());
  229. ctx.getChannel().close();
  230. } else {
  231. logger.debug("Caught exception while handling client http traffic, closing connection {}", e.getCause(), ctx.getChannel());
  232. ctx.getChannel().close();
  233. }
  234. }
  235. }
  236. static class MyChannelPipelineFactory implements ChannelPipelineFactory {
  237. private final NettyHttpServerTransport transport;
  238. private final HttpRequestHandler requestHandler;
  239. MyChannelPipelineFactory(NettyHttpServerTransport transport) {
  240. this.transport = transport;
  241. this.requestHandler = new HttpRequestHandler(transport);
  242. }
  243. @Override
  244. public ChannelPipeline getPipeline() throws Exception {
  245. ChannelPipeline pipeline = Channels.pipeline();
  246. pipeline.addLast("openChannels", transport.serverOpenChannels);
  247. pipeline.addLast("decoder", new HttpRequestDecoder(
  248. (int) transport.maxInitialLineLength.bytes(),
  249. (int) transport.maxHeaderSize.bytes(),
  250. (int) transport.maxChunkSize.bytes()
  251. ));
  252. if (transport.compression) {
  253. pipeline.addLast("decoder_compress", new HttpContentDecompressor());
  254. }
  255. pipeline.addLast("aggregator", new HttpChunkAggregator((int) transport.maxContentLength.bytes()));
  256. pipeline.addLast("encoder", new HttpResponseEncoder());
  257. if (transport.compression) {
  258. pipeline.addLast("encoder_compress", new HttpContentCompressor(transport.compressionLevel));
  259. }
  260. pipeline.addLast("handler", requestHandler);
  261. return pipeline;
  262. }
  263. }
  264. }