AbstractHttpServerTransport.java 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. /*
  2. * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
  3. * or more contributor license agreements. Licensed under the Elastic License
  4. * 2.0 and the Server Side Public License, v 1; you may not use this file except
  5. * in compliance with, at your election, the Elastic License 2.0 or the Server
  6. * Side Public License, v 1.
  7. */
  8. package org.elasticsearch.http;
  9. import org.apache.logging.log4j.Level;
  10. import org.apache.logging.log4j.LogManager;
  11. import org.apache.logging.log4j.Logger;
  12. import org.apache.lucene.util.BytesRef;
  13. import org.elasticsearch.ElasticsearchTimeoutException;
  14. import org.elasticsearch.ExceptionsHelper;
  15. import org.elasticsearch.action.ActionListener;
  16. import org.elasticsearch.action.support.PlainActionFuture;
  17. import org.elasticsearch.common.Strings;
  18. import org.elasticsearch.common.component.AbstractLifecycleComponent;
  19. import org.elasticsearch.common.network.CloseableChannel;
  20. import org.elasticsearch.common.network.NetworkAddress;
  21. import org.elasticsearch.common.network.NetworkService;
  22. import org.elasticsearch.common.recycler.Recycler;
  23. import org.elasticsearch.common.settings.ClusterSettings;
  24. import org.elasticsearch.common.settings.Settings;
  25. import org.elasticsearch.common.transport.BoundTransportAddress;
  26. import org.elasticsearch.common.transport.NetworkExceptionHelper;
  27. import org.elasticsearch.common.transport.PortsRange;
  28. import org.elasticsearch.common.transport.TransportAddress;
  29. import org.elasticsearch.common.unit.ByteSizeValue;
  30. import org.elasticsearch.common.util.concurrent.ConcurrentCollections;
  31. import org.elasticsearch.common.util.concurrent.FutureUtils;
  32. import org.elasticsearch.common.util.concurrent.ThreadContext;
  33. import org.elasticsearch.common.xcontent.LoggingDeprecationHandler;
  34. import org.elasticsearch.core.AbstractRefCounted;
  35. import org.elasticsearch.core.RefCounted;
  36. import org.elasticsearch.rest.RestChannel;
  37. import org.elasticsearch.rest.RestRequest;
  38. import org.elasticsearch.rest.RestResponse;
  39. import org.elasticsearch.tasks.Task;
  40. import org.elasticsearch.telemetry.tracing.Tracer;
  41. import org.elasticsearch.threadpool.ThreadPool;
  42. import org.elasticsearch.transport.BindTransportException;
  43. import org.elasticsearch.transport.TransportSettings;
  44. import org.elasticsearch.xcontent.NamedXContentRegistry;
  45. import org.elasticsearch.xcontent.XContentParserConfiguration;
  46. import java.io.IOException;
  47. import java.net.InetAddress;
  48. import java.net.InetSocketAddress;
  49. import java.nio.channels.CancelledKeyException;
  50. import java.util.ArrayList;
  51. import java.util.Arrays;
  52. import java.util.HashSet;
  53. import java.util.List;
  54. import java.util.Map;
  55. import java.util.Set;
  56. import java.util.concurrent.ConcurrentHashMap;
  57. import java.util.concurrent.TimeUnit;
  58. import java.util.concurrent.atomic.AtomicLong;
  59. import java.util.concurrent.atomic.AtomicReference;
  60. import java.util.concurrent.locks.ReadWriteLock;
  61. import java.util.concurrent.locks.StampedLock;
  62. import static org.elasticsearch.core.Strings.format;
  63. import static org.elasticsearch.http.HttpTransportSettings.SETTING_HTTP_BIND_HOST;
  64. import static org.elasticsearch.http.HttpTransportSettings.SETTING_HTTP_MAX_CONTENT_LENGTH;
  65. import static org.elasticsearch.http.HttpTransportSettings.SETTING_HTTP_PORT;
  66. import static org.elasticsearch.http.HttpTransportSettings.SETTING_HTTP_PUBLISH_HOST;
  67. import static org.elasticsearch.http.HttpTransportSettings.SETTING_HTTP_PUBLISH_PORT;
  68. import static org.elasticsearch.http.HttpTransportSettings.SETTING_HTTP_SERVER_SHUTDOWN_GRACE_PERIOD;
  69. public abstract class AbstractHttpServerTransport extends AbstractLifecycleComponent implements HttpServerTransport {
  70. private static final Logger logger = LogManager.getLogger(AbstractHttpServerTransport.class);
  71. protected final Settings settings;
  72. public final HttpHandlingSettings handlingSettings;
  73. protected final NetworkService networkService;
  74. protected final Recycler<BytesRef> recycler;
  75. protected final ThreadPool threadPool;
  76. protected final Dispatcher dispatcher;
  77. protected final CorsHandler corsHandler;
  78. private final XContentParserConfiguration parserConfig;
  79. protected final PortsRange port;
  80. protected final ByteSizeValue maxContentLength;
  81. private final String[] bindHosts;
  82. private final String[] publishHosts;
  83. private volatile BoundTransportAddress boundAddress;
  84. private final AtomicLong totalChannelsAccepted = new AtomicLong();
  85. private final Map<HttpChannel, RequestTrackingHttpChannel> httpChannels = new ConcurrentHashMap<>();
  86. private final PlainActionFuture<Void> allClientsClosedListener = new PlainActionFuture<>();
  87. private final RefCounted refCounted = AbstractRefCounted.of(() -> allClientsClosedListener.onResponse(null));
  88. private final Set<HttpServerChannel> httpServerChannels = ConcurrentCollections.newConcurrentSet();
  89. private final long shutdownGracePeriodMillis;
  90. private final HttpClientStatsTracker httpClientStatsTracker;
  91. private final HttpTracer httpLogger;
  92. private final Tracer tracer;
  93. private volatile boolean shuttingDown;
  94. private final ReadWriteLock shuttingDownRWLock = new StampedLock().asReadWriteLock();
  95. private volatile long slowLogThresholdMs;
  96. protected AbstractHttpServerTransport(
  97. Settings settings,
  98. NetworkService networkService,
  99. Recycler<BytesRef> recycler,
  100. ThreadPool threadPool,
  101. NamedXContentRegistry xContentRegistry,
  102. Dispatcher dispatcher,
  103. ClusterSettings clusterSettings,
  104. Tracer tracer
  105. ) {
  106. this.settings = settings;
  107. this.networkService = networkService;
  108. this.recycler = recycler;
  109. this.threadPool = threadPool;
  110. this.parserConfig = XContentParserConfiguration.EMPTY.withRegistry(xContentRegistry)
  111. .withDeprecationHandler(LoggingDeprecationHandler.INSTANCE);
  112. this.dispatcher = dispatcher;
  113. this.handlingSettings = HttpHandlingSettings.fromSettings(settings);
  114. this.corsHandler = CorsHandler.fromSettings(settings);
  115. // we can't make the network.bind_host a fallback since we already fall back to http.host hence the extra conditional here
  116. List<String> httpBindHost = SETTING_HTTP_BIND_HOST.get(settings);
  117. this.bindHosts = (httpBindHost.isEmpty() ? NetworkService.GLOBAL_NETWORK_BIND_HOST_SETTING.get(settings) : httpBindHost).toArray(
  118. Strings.EMPTY_ARRAY
  119. );
  120. // we can't make the network.publish_host a fallback since we already fall back to http.host hence the extra conditional here
  121. List<String> httpPublishHost = SETTING_HTTP_PUBLISH_HOST.get(settings);
  122. this.publishHosts = (httpPublishHost.isEmpty() ? NetworkService.GLOBAL_NETWORK_PUBLISH_HOST_SETTING.get(settings) : httpPublishHost)
  123. .toArray(Strings.EMPTY_ARRAY);
  124. this.port = SETTING_HTTP_PORT.get(settings);
  125. this.maxContentLength = SETTING_HTTP_MAX_CONTENT_LENGTH.get(settings);
  126. this.tracer = tracer;
  127. this.httpLogger = new HttpTracer(settings, clusterSettings);
  128. clusterSettings.addSettingsUpdateConsumer(
  129. TransportSettings.SLOW_OPERATION_THRESHOLD_SETTING,
  130. slowLogThreshold -> this.slowLogThresholdMs = slowLogThreshold.getMillis()
  131. );
  132. slowLogThresholdMs = TransportSettings.SLOW_OPERATION_THRESHOLD_SETTING.get(settings).getMillis();
  133. httpClientStatsTracker = new HttpClientStatsTracker(settings, clusterSettings, threadPool);
  134. shutdownGracePeriodMillis = SETTING_HTTP_SERVER_SHUTDOWN_GRACE_PERIOD.get(settings).getMillis();
  135. }
  136. public Recycler<BytesRef> recycler() {
  137. return recycler;
  138. }
  139. @Override
  140. public BoundTransportAddress boundAddress() {
  141. return this.boundAddress;
  142. }
  143. @Override
  144. public HttpInfo info() {
  145. BoundTransportAddress boundTransportAddress = boundAddress();
  146. if (boundTransportAddress == null) {
  147. return null;
  148. }
  149. return new HttpInfo(boundTransportAddress, maxContentLength.getBytes());
  150. }
  151. @Override
  152. public HttpStats stats() {
  153. return new HttpStats(
  154. httpChannels.size(),
  155. totalChannelsAccepted.get(),
  156. httpClientStatsTracker.getClientStats(),
  157. dispatcher.getStats()
  158. );
  159. }
  160. protected void bindServer() {
  161. // Bind and start to accept incoming connections.
  162. final InetAddress[] hostAddresses;
  163. try {
  164. hostAddresses = networkService.resolveBindHostAddresses(bindHosts);
  165. } catch (IOException e) {
  166. throw new BindHttpException("Failed to resolve host [" + Arrays.toString(bindHosts) + "]", e);
  167. }
  168. List<TransportAddress> boundAddresses = new ArrayList<>(hostAddresses.length);
  169. for (InetAddress address : hostAddresses) {
  170. boundAddresses.add(bindAddress(address));
  171. }
  172. final InetAddress publishInetAddress;
  173. try {
  174. publishInetAddress = networkService.resolvePublishHostAddresses(publishHosts);
  175. } catch (Exception e) {
  176. throw new BindTransportException("Failed to resolve publish address", e);
  177. }
  178. final int publishPort = resolvePublishPort(settings, boundAddresses, publishInetAddress);
  179. TransportAddress publishAddress = new TransportAddress(new InetSocketAddress(publishInetAddress, publishPort));
  180. this.boundAddress = new BoundTransportAddress(boundAddresses.toArray(new TransportAddress[0]), publishAddress);
  181. logger.info("{}", boundAddress);
  182. }
  183. private TransportAddress bindAddress(final InetAddress hostAddress) {
  184. final AtomicReference<Exception> lastException = new AtomicReference<>();
  185. final AtomicReference<InetSocketAddress> boundSocket = new AtomicReference<>();
  186. boolean success = port.iterate(portNumber -> {
  187. try {
  188. synchronized (httpServerChannels) {
  189. HttpServerChannel httpServerChannel = bind(new InetSocketAddress(hostAddress, portNumber));
  190. httpServerChannels.add(httpServerChannel);
  191. boundSocket.set(httpServerChannel.getLocalAddress());
  192. }
  193. } catch (Exception e) {
  194. lastException.set(e);
  195. return false;
  196. }
  197. return true;
  198. });
  199. if (success == false) {
  200. throw new BindHttpException("Failed to bind to " + NetworkAddress.format(hostAddress, port), lastException.get());
  201. }
  202. if (logger.isDebugEnabled()) {
  203. logger.debug("Bound http to address {{}}", NetworkAddress.format(boundSocket.get()));
  204. }
  205. return new TransportAddress(boundSocket.get());
  206. }
  207. protected abstract HttpServerChannel bind(InetSocketAddress hostAddress) throws Exception;
  208. /**
  209. * Gracefully shut down. If {@link HttpTransportSettings#SETTING_HTTP_SERVER_SHUTDOWN_GRACE_PERIOD} is zero, the default, then
  210. * forcefully close all open connections immediately.
  211. * Serially run through the following steps:
  212. * <ol>
  213. * <li> Stop listening for new HTTP connections, which means no new HttpChannel are added to the {@link #httpChannels} list.
  214. * {@link #serverAcceptedChannel(HttpChannel)} will close any new channels to ensure this is true.
  215. * <li> Close the HttpChannel after a new request completes on all existing channels.
  216. * <li> Close all idle channels.
  217. * <li> If grace period is set, wait for all httpChannels to close via 2 for up to the configured grace period,
  218. * {@link #shutdownGracePeriodMillis}.
  219. * If all connections are closed before the expiration of the grace period, stop waiting early.
  220. * <li> Close all remaining open httpChannels even if requests are in flight.
  221. * </ol>
  222. */
  223. @Override
  224. protected void doStop() {
  225. synchronized (httpServerChannels) {
  226. if (httpServerChannels.isEmpty() == false) {
  227. try {
  228. CloseableChannel.closeChannels(new ArrayList<>(httpServerChannels), true);
  229. } catch (Exception e) {
  230. logger.warn("exception while closing channels", e);
  231. } finally {
  232. httpServerChannels.clear();
  233. }
  234. }
  235. }
  236. var wlock = shuttingDownRWLock.writeLock();
  237. try {
  238. wlock.lock();
  239. shuttingDown = true;
  240. refCounted.decRef();
  241. httpChannels.values().forEach(RequestTrackingHttpChannel::setCloseWhenIdle);
  242. } finally {
  243. wlock.unlock();
  244. }
  245. boolean closed = false;
  246. if (shutdownGracePeriodMillis > 0) {
  247. try {
  248. logger.debug(format("waiting [%d]ms for clients to close connections", shutdownGracePeriodMillis));
  249. FutureUtils.get(allClientsClosedListener, shutdownGracePeriodMillis, TimeUnit.MILLISECONDS);
  250. closed = true;
  251. } catch (ElasticsearchTimeoutException t) {
  252. logger.warn(format("timed out while waiting [%d]ms for clients to close connections", shutdownGracePeriodMillis));
  253. }
  254. } else {
  255. logger.debug("closing all client connections immediately");
  256. }
  257. if (closed == false) {
  258. try {
  259. CloseableChannel.closeChannels(new ArrayList<>(httpChannels.values()), true);
  260. } catch (Exception e) {
  261. logger.warn("unexpected exception while closing http channels", e);
  262. }
  263. try {
  264. allClientsClosedListener.get();
  265. } catch (Exception e) {
  266. assert false : e;
  267. logger.warn("unexpected exception while waiting for http channels to close", e);
  268. }
  269. }
  270. stopInternal();
  271. }
  272. boolean isAcceptingConnections() {
  273. return shuttingDown == false;
  274. }
  275. @Override
  276. protected void doClose() {}
  277. /**
  278. * Called to tear down internal resources
  279. */
  280. protected abstract void stopInternal();
  281. // package private for tests
  282. static int resolvePublishPort(Settings settings, List<TransportAddress> boundAddresses, InetAddress publishInetAddress) {
  283. int publishPort = SETTING_HTTP_PUBLISH_PORT.get(settings);
  284. if (publishPort < 0) {
  285. for (TransportAddress boundAddress : boundAddresses) {
  286. InetAddress boundInetAddress = boundAddress.address().getAddress();
  287. if (boundInetAddress.isAnyLocalAddress() || boundInetAddress.equals(publishInetAddress)) {
  288. publishPort = boundAddress.getPort();
  289. break;
  290. }
  291. }
  292. }
  293. // if no matching boundAddress found, check if there is a unique port for all bound addresses
  294. if (publishPort < 0) {
  295. final Set<Integer> ports = new HashSet<>();
  296. for (TransportAddress boundAddress : boundAddresses) {
  297. ports.add(boundAddress.getPort());
  298. }
  299. if (ports.size() == 1) {
  300. publishPort = ports.iterator().next();
  301. }
  302. }
  303. if (publishPort < 0) {
  304. throw new BindHttpException(
  305. "Failed to auto-resolve http publish port, multiple bound addresses "
  306. + boundAddresses
  307. + " with distinct ports and none of them matched the publish address ("
  308. + publishInetAddress
  309. + "). "
  310. + "Please specify a unique port by setting "
  311. + SETTING_HTTP_PORT.getKey()
  312. + " or "
  313. + SETTING_HTTP_PUBLISH_PORT.getKey()
  314. );
  315. }
  316. return publishPort;
  317. }
  318. public void onException(HttpChannel channel, Exception e) {
  319. try {
  320. if (lifecycle.started() == false) {
  321. // just close and ignore - we are already stopped and just need to make sure we release all resources
  322. return;
  323. }
  324. if (NetworkExceptionHelper.getCloseConnectionExceptionLevel(e, false) != Level.OFF) {
  325. logger.trace(
  326. () -> format("close connection exception caught while handling client http traffic, closing connection %s", channel),
  327. e
  328. );
  329. } else if (NetworkExceptionHelper.isConnectException(e)) {
  330. logger.trace(
  331. () -> format("connect exception caught while handling client http traffic, closing connection %s", channel),
  332. e
  333. );
  334. } else if (e instanceof HttpReadTimeoutException) {
  335. logger.trace(() -> format("http read timeout, closing connection %s", channel), e);
  336. } else if (e instanceof CancelledKeyException) {
  337. logger.trace(
  338. () -> format("cancelled key exception caught while handling client http traffic, closing connection %s", channel),
  339. e
  340. );
  341. } else {
  342. logger.warn(() -> format("caught exception while handling client http traffic, closing connection %s", channel), e);
  343. }
  344. } finally {
  345. CloseableChannel.closeChannel(channel);
  346. }
  347. }
  348. protected static void onServerException(HttpServerChannel channel, Exception e) {
  349. logger.error(() -> "exception from http server channel caught on transport layer [channel=" + channel + "]", e);
  350. }
  351. protected void serverAcceptedChannel(HttpChannel httpChannel) {
  352. var rlock = shuttingDownRWLock.readLock();
  353. try {
  354. rlock.lock();
  355. if (shuttingDown) {
  356. throw new IllegalStateException("Server cannot accept new channel while shutting down");
  357. }
  358. RequestTrackingHttpChannel trackingChannel = httpChannels.putIfAbsent(httpChannel, new RequestTrackingHttpChannel(httpChannel));
  359. assert trackingChannel == null : "Channel should only be added to http channel set once";
  360. } finally {
  361. rlock.unlock();
  362. }
  363. refCounted.incRef();
  364. httpChannel.addCloseListener(ActionListener.running(() -> {
  365. httpChannels.remove(httpChannel);
  366. refCounted.decRef();
  367. }));
  368. totalChannelsAccepted.incrementAndGet();
  369. httpClientStatsTracker.addClientStats(httpChannel);
  370. logger.trace(() -> format("Http channel accepted: %s", httpChannel));
  371. }
  372. /**
  373. * This method handles an incoming http request.
  374. *
  375. * @param httpRequest that is incoming
  376. * @param httpChannel that received the http request
  377. */
  378. public void incomingRequest(final HttpRequest httpRequest, final HttpChannel httpChannel) {
  379. httpClientStatsTracker.updateClientStats(httpRequest, httpChannel);
  380. final RequestTrackingHttpChannel trackingChannel = httpChannels.get(httpChannel);
  381. final long startTime = threadPool.rawRelativeTimeInMillis();
  382. try {
  383. // The channel may not be present if the close listener (set in serverAcceptedChannel) runs before this method because the
  384. // connection closed early
  385. if (trackingChannel == null) {
  386. httpRequest.release();
  387. logger.warn(
  388. "http channel [{}] closed before starting to handle [{}][{}][{}]",
  389. httpChannel,
  390. httpRequest.header(Task.X_OPAQUE_ID_HTTP_HEADER),
  391. httpRequest.method(),
  392. httpRequest.uri()
  393. );
  394. return;
  395. }
  396. trackingChannel.incomingRequest();
  397. handleIncomingRequest(httpRequest, trackingChannel, httpRequest.getInboundException());
  398. } finally {
  399. final long took = threadPool.rawRelativeTimeInMillis() - startTime;
  400. networkService.getHandlingTimeTracker().addHandlingTime(took);
  401. final long logThreshold = slowLogThresholdMs;
  402. if (logThreshold > 0 && took > logThreshold) {
  403. logger.warn(
  404. "handling request [{}][{}][{}][{}] took [{}ms] which is above the warn threshold of [{}ms]",
  405. httpRequest.header(Task.X_OPAQUE_ID_HTTP_HEADER),
  406. httpRequest.method(),
  407. httpRequest.uri(),
  408. httpChannel,
  409. took,
  410. logThreshold
  411. );
  412. }
  413. }
  414. }
  415. // Visible for testing
  416. void dispatchRequest(final RestRequest restRequest, final RestChannel channel, final Throwable badRequestCause) {
  417. final ThreadContext threadContext = threadPool.getThreadContext();
  418. try (ThreadContext.StoredContext ignore = threadContext.stashContext()) {
  419. if (badRequestCause != null) {
  420. dispatcher.dispatchBadRequest(channel, threadContext, badRequestCause);
  421. } else {
  422. populatePerRequestThreadContext0(restRequest, channel, threadContext);
  423. dispatcher.dispatchRequest(restRequest, channel, threadContext);
  424. }
  425. }
  426. }
  427. private void populatePerRequestThreadContext0(RestRequest restRequest, RestChannel channel, ThreadContext threadContext) {
  428. try {
  429. populatePerRequestThreadContext(restRequest, threadContext);
  430. } catch (Exception e) {
  431. try {
  432. channel.sendResponse(new RestResponse(channel, e));
  433. } catch (Exception inner) {
  434. inner.addSuppressed(e);
  435. logger.error(() -> "failed to send failure response for uri [" + restRequest.uri() + "]", inner);
  436. }
  437. }
  438. }
  439. protected void populatePerRequestThreadContext(RestRequest restRequest, ThreadContext threadContext) {}
  440. private void handleIncomingRequest(final HttpRequest httpRequest, final HttpChannel httpChannel, final Exception exception) {
  441. if (exception == null) {
  442. HttpResponse earlyResponse = corsHandler.handleInbound(httpRequest);
  443. if (earlyResponse != null) {
  444. httpChannel.sendResponse(earlyResponse, earlyResponseListener(httpRequest, httpChannel));
  445. httpRequest.release();
  446. return;
  447. }
  448. }
  449. Exception badRequestCause = exception;
  450. /*
  451. * We want to create a REST request from the incoming request from Netty. However, creating this request could fail if there
  452. * are incorrectly encoded parameters, or the Content-Type header is invalid. If one of these specific failures occurs, we
  453. * attempt to create a REST request again without the input that caused the exception (e.g., we remove the Content-Type header,
  454. * or skip decoding the parameters). Once we have a request in hand, we then dispatch the request as a bad request with the
  455. * underlying exception that caused us to treat the request as bad.
  456. */
  457. final RestRequest restRequest;
  458. {
  459. RestRequest innerRestRequest;
  460. try {
  461. innerRestRequest = RestRequest.request(parserConfig, httpRequest, httpChannel);
  462. } catch (final RestRequest.MediaTypeHeaderException e) {
  463. badRequestCause = ExceptionsHelper.useOrSuppress(badRequestCause, e);
  464. innerRestRequest = requestWithoutFailedHeader(httpRequest, httpChannel, badRequestCause, e.getFailedHeaderNames());
  465. } catch (final RestRequest.BadParameterException e) {
  466. badRequestCause = ExceptionsHelper.useOrSuppress(badRequestCause, e);
  467. innerRestRequest = RestRequest.requestWithoutParameters(parserConfig, httpRequest, httpChannel);
  468. }
  469. restRequest = innerRestRequest;
  470. }
  471. final HttpTracer maybeHttpLogger = httpLogger.maybeLogRequest(restRequest, exception);
  472. /*
  473. * We now want to create a channel used to send the response on. However, creating this channel can fail if there are invalid
  474. * parameter values for any of the filter_path, human, or pretty parameters. We detect these specific failures via an
  475. * IllegalArgumentException from the channel constructor and then attempt to create a new channel that bypasses parsing of these
  476. * parameter values.
  477. */
  478. final RestChannel channel;
  479. {
  480. RestChannel innerChannel;
  481. ThreadContext threadContext = threadPool.getThreadContext();
  482. try {
  483. innerChannel = new DefaultRestChannel(
  484. httpChannel,
  485. httpRequest,
  486. restRequest,
  487. recycler,
  488. handlingSettings,
  489. threadContext,
  490. corsHandler,
  491. maybeHttpLogger,
  492. tracer
  493. );
  494. } catch (final IllegalArgumentException e) {
  495. badRequestCause = ExceptionsHelper.useOrSuppress(badRequestCause, e);
  496. final RestRequest innerRequest = RestRequest.requestWithoutParameters(parserConfig, httpRequest, httpChannel);
  497. innerChannel = new DefaultRestChannel(
  498. httpChannel,
  499. httpRequest,
  500. innerRequest,
  501. recycler,
  502. handlingSettings,
  503. threadContext,
  504. corsHandler,
  505. httpLogger,
  506. tracer
  507. );
  508. }
  509. channel = innerChannel;
  510. }
  511. dispatchRequest(restRequest, channel, badRequestCause);
  512. }
  513. private RestRequest requestWithoutFailedHeader(
  514. HttpRequest httpRequest,
  515. HttpChannel httpChannel,
  516. Exception badRequestCause,
  517. Set<String> failedHeaderNames
  518. ) {
  519. assert failedHeaderNames.size() > 0;
  520. HttpRequest httpRequestWithoutHeader = httpRequest;
  521. for (String failedHeaderName : failedHeaderNames) {
  522. httpRequestWithoutHeader = httpRequestWithoutHeader.removeHeader(failedHeaderName);
  523. }
  524. try {
  525. return RestRequest.request(parserConfig, httpRequestWithoutHeader, httpChannel);
  526. } catch (final RestRequest.MediaTypeHeaderException e) {
  527. badRequestCause = ExceptionsHelper.useOrSuppress(badRequestCause, e);
  528. return requestWithoutFailedHeader(httpRequestWithoutHeader, httpChannel, badRequestCause, e.getFailedHeaderNames());
  529. } catch (final RestRequest.BadParameterException e) {
  530. badRequestCause.addSuppressed(e);
  531. return RestRequest.requestWithoutParameters(parserConfig, httpRequestWithoutHeader, httpChannel);
  532. }
  533. }
  534. private static ActionListener<Void> earlyResponseListener(HttpRequest request, HttpChannel httpChannel) {
  535. if (HttpUtils.shouldCloseConnection(request)) {
  536. return ActionListener.running(() -> CloseableChannel.closeChannel(httpChannel));
  537. } else {
  538. return ActionListener.noop();
  539. }
  540. }
  541. public ThreadPool getThreadPool() {
  542. return threadPool;
  543. }
  544. /**
  545. * A {@link HttpChannel} that tracks number of requests via a {@link RefCounted}.
  546. */
  547. private static class RequestTrackingHttpChannel implements HttpChannel {
  548. /**
  549. * Only counts down to zero via {@link #setCloseWhenIdle()}.
  550. */
  551. final RefCounted refCounted = AbstractRefCounted.of(this::closeInner);
  552. final HttpChannel inner;
  553. RequestTrackingHttpChannel(HttpChannel inner) {
  554. this.inner = inner;
  555. }
  556. public void incomingRequest() throws IllegalStateException {
  557. refCounted.incRef();
  558. }
  559. /**
  560. * Close the channel when there are no more requests in flight.
  561. */
  562. public void setCloseWhenIdle() {
  563. refCounted.decRef();
  564. }
  565. @Override
  566. public void close() {
  567. closeInner();
  568. }
  569. /**
  570. * Synchronized to avoid double close due to a natural close and a close via {@link #setCloseWhenIdle()}
  571. */
  572. private void closeInner() {
  573. synchronized (inner) {
  574. if (inner.isOpen()) {
  575. inner.close();
  576. } else {
  577. logger.info("channel [{}] already closed", inner);
  578. }
  579. }
  580. }
  581. @Override
  582. public void addCloseListener(ActionListener<Void> listener) {
  583. inner.addCloseListener(listener);
  584. }
  585. @Override
  586. public boolean isOpen() {
  587. return inner.isOpen();
  588. }
  589. @Override
  590. public void sendResponse(HttpResponse response, ActionListener<Void> listener) {
  591. inner.sendResponse(
  592. response,
  593. listener != null ? ActionListener.runAfter(listener, refCounted::decRef) : ActionListener.running(refCounted::decRef)
  594. );
  595. }
  596. @Override
  597. public InetSocketAddress getLocalAddress() {
  598. return inner.getLocalAddress();
  599. }
  600. @Override
  601. public InetSocketAddress getRemoteAddress() {
  602. return inner.getRemoteAddress();
  603. }
  604. @Override
  605. public String toString() {
  606. return inner.toString();
  607. }
  608. }
  609. }